From 589ee29ce5d47b5664939e6ae2b4fafd78391295 Mon Sep 17 00:00:00 2001 From: clonker Date: Thu, 18 Jul 2024 14:15:22 +0200 Subject: [PATCH] Yul: Prepare removal of YulString by replacing its occurrences by YulName typedef --- libsolc/libsolc.cpp | 2 +- libsolidity/analysis/ReferencesResolver.cpp | 2 +- libsolidity/analysis/ReferencesResolver.h | 2 +- libsolidity/codegen/CompilerContext.cpp | 10 +- libsolidity/codegen/CompilerContext.h | 2 +- libsolidity/codegen/ContractCompiler.cpp | 2 +- .../codegen/ir/IRGeneratorForStatements.cpp | 6 +- .../codegen/IRGeneratorForStatements.cpp | 6 +- libsolidity/interface/CompilerStack.cpp | 2 +- libyul/AST.h | 10 +- libyul/AsmAnalysis.cpp | 52 ++++---- libyul/AsmAnalysis.h | 18 +-- libyul/AsmJsonImporter.cpp | 10 +- libyul/AsmParser.cpp | 6 +- libyul/AsmParser.h | 2 +- libyul/AsmPrinter.cpp | 2 +- libyul/AsmPrinter.h | 4 +- libyul/CMakeLists.txt | 1 + libyul/CompilabilityChecker.h | 4 +- libyul/ControlFlowSideEffectsCollector.cpp | 4 +- libyul/ControlFlowSideEffectsCollector.h | 2 +- libyul/Dialect.cpp | 31 +++-- libyul/Dialect.h | 37 +++--- libyul/Exceptions.h | 10 +- libyul/FunctionReferenceResolver.h | 2 +- libyul/Object.h | 1 - libyul/ObjectParser.h | 1 - libyul/Scope.cpp | 8 +- libyul/Scope.h | 20 +-- libyul/YulName.h | 26 ++++ libyul/YulString.h | 2 +- libyul/backends/evm/ConstantOptimiser.cpp | 16 +-- libyul/backends/evm/ConstantOptimiser.h | 6 +- .../backends/evm/ControlFlowGraphBuilder.cpp | 10 +- libyul/backends/evm/ControlFlowGraphBuilder.h | 4 +- libyul/backends/evm/EVMCodeTransform.cpp | 12 +- libyul/backends/evm/EVMCodeTransform.h | 8 +- libyul/backends/evm/EVMDialect.cpp | 122 +++++++++--------- libyul/backends/evm/EVMDialect.h | 33 +++-- libyul/backends/evm/EVMObjectCompiler.cpp | 2 +- .../evm/OptimizedEVMCodeTransform.cpp | 14 +- libyul/backends/evm/StackLayoutGenerator.cpp | 10 +- libyul/backends/evm/StackLayoutGenerator.h | 6 +- .../backends/evm/VariableReferenceCounter.cpp | 2 +- .../backends/evm/VariableReferenceCounter.h | 2 +- libyul/optimiser/ASTCopier.cpp | 4 +- libyul/optimiser/ASTCopier.h | 10 +- libyul/optimiser/ASTWalker.h | 2 +- libyul/optimiser/BlockHasher.h | 6 +- libyul/optimiser/CallGraphGenerator.cpp | 14 +- libyul/optimiser/CallGraphGenerator.h | 8 +- libyul/optimiser/CircularReferencesPruner.cpp | 12 +- libyul/optimiser/CircularReferencesPruner.h | 7 +- .../CommonSubexpressionEliminator.cpp | 6 +- .../optimiser/CommonSubexpressionEliminator.h | 8 +- libyul/optimiser/ConditionalSimplifier.cpp | 4 +- libyul/optimiser/ConditionalSimplifier.h | 4 +- libyul/optimiser/ConditionalUnsimplifier.cpp | 4 +- libyul/optimiser/ConditionalUnsimplifier.h | 4 +- libyul/optimiser/ControlFlowSimplifier.cpp | 2 +- libyul/optimiser/DataFlowAnalyzer.cpp | 64 ++++----- libyul/optimiser/DataFlowAnalyzer.h | 56 ++++---- libyul/optimiser/DeadCodeEliminator.h | 6 +- libyul/optimiser/Disambiguator.cpp | 2 +- libyul/optimiser/Disambiguator.h | 8 +- libyul/optimiser/EqualStoreEliminator.cpp | 4 +- libyul/optimiser/EqualStoreEliminator.h | 2 +- libyul/optimiser/EquivalentFunctionCombiner.h | 4 +- libyul/optimiser/EquivalentFunctionDetector.h | 4 +- libyul/optimiser/ExpressionInliner.cpp | 4 +- libyul/optimiser/ExpressionInliner.h | 9 +- libyul/optimiser/ExpressionJoiner.h | 2 +- libyul/optimiser/ExpressionSimplifier.cpp | 2 +- libyul/optimiser/ExpressionSplitter.cpp | 4 +- .../optimiser/ForLoopConditionOutOfBody.cpp | 2 +- libyul/optimiser/FullInliner.cpp | 35 +++-- libyul/optimiser/FullInliner.h | 32 ++--- libyul/optimiser/FunctionCallFinder.cpp | 10 +- libyul/optimiser/FunctionCallFinder.h | 6 +- libyul/optimiser/FunctionSpecializer.cpp | 12 +- libyul/optimiser/FunctionSpecializer.h | 8 +- .../InlinableExpressionFunctionFinder.cpp | 4 +- .../InlinableExpressionFunctionFinder.h | 8 +- libyul/optimiser/KnowledgeBase.cpp | 36 +++--- libyul/optimiser/KnowledgeBase.h | 38 +++--- libyul/optimiser/LoadResolver.cpp | 4 +- libyul/optimiser/LoadResolver.h | 2 +- libyul/optimiser/LoopInvariantCodeMotion.cpp | 8 +- libyul/optimiser/LoopInvariantCodeMotion.h | 10 +- libyul/optimiser/Metrics.cpp | 2 +- libyul/optimiser/Metrics.h | 4 +- libyul/optimiser/NameCollector.cpp | 22 ++-- libyul/optimiser/NameCollector.h | 31 ++--- libyul/optimiser/NameDispenser.cpp | 13 +- libyul/optimiser/NameDispenser.h | 18 +-- libyul/optimiser/NameDisplacer.cpp | 4 +- libyul/optimiser/NameDisplacer.h | 14 +- libyul/optimiser/NameSimplifier.cpp | 14 +- libyul/optimiser/NameSimplifier.h | 8 +- libyul/optimiser/OptimiserStep.h | 3 +- libyul/optimiser/OptimizerUtilities.cpp | 4 +- libyul/optimiser/OptimizerUtilities.h | 6 +- libyul/optimiser/Rematerialiser.cpp | 8 +- libyul/optimiser/Rematerialiser.h | 8 +- libyul/optimiser/SSATransform.cpp | 52 ++++---- libyul/optimiser/SSAValueTracker.cpp | 6 +- libyul/optimiser/SSAValueTracker.h | 12 +- libyul/optimiser/Semantics.cpp | 18 +-- libyul/optimiser/Semantics.h | 22 ++-- libyul/optimiser/SimplificationRules.cpp | 8 +- libyul/optimiser/SimplificationRules.h | 6 +- libyul/optimiser/StackCompressor.cpp | 44 +++---- libyul/optimiser/StackLimitEvader.cpp | 33 +++-- libyul/optimiser/StackLimitEvader.h | 4 +- libyul/optimiser/StackToMemoryMover.cpp | 16 +-- libyul/optimiser/StackToMemoryMover.h | 21 +-- libyul/optimiser/Substitution.cpp | 2 +- libyul/optimiser/Substitution.h | 6 +- libyul/optimiser/Suite.cpp | 4 +- libyul/optimiser/Suite.h | 4 +- libyul/optimiser/SyntacticalEquality.h | 6 +- libyul/optimiser/TypeInfo.cpp | 12 +- libyul/optimiser/TypeInfo.h | 16 +-- libyul/optimiser/UnusedAssignEliminator.cpp | 4 +- libyul/optimiser/UnusedAssignEliminator.h | 8 +- .../UnusedFunctionParameterPruner.cpp | 14 +- libyul/optimiser/UnusedFunctionsCommon.cpp | 4 +- libyul/optimiser/UnusedFunctionsCommon.h | 4 +- libyul/optimiser/UnusedPruner.cpp | 20 +-- libyul/optimiser/UnusedPruner.h | 26 ++-- libyul/optimiser/UnusedStoreBase.h | 2 +- libyul/optimiser/UnusedStoreEliminator.cpp | 24 ++-- libyul/optimiser/UnusedStoreEliminator.h | 22 ++-- libyul/optimiser/VarNameCleaner.cpp | 16 +-- libyul/optimiser/VarNameCleaner.h | 16 +-- test/libsolidity/MemoryGuardTest.cpp | 2 +- test/libyul/FunctionSideEffects.cpp | 2 +- test/libyul/KnowledgeBaseTest.cpp | 50 +++---- test/libyul/Parser.cpp | 6 +- test/libyul/StackShufflingTest.cpp | 8 +- test/libyul/StackShufflingTest.h | 4 +- test/libyul/YulOptimizerTestCommon.cpp | 10 +- test/libyul/YulOptimizerTestCommon.h | 4 +- test/tools/yulInterpreter/Inspector.h | 10 +- test/tools/yulInterpreter/Interpreter.cpp | 6 +- test/tools/yulInterpreter/Interpreter.h | 14 +- test/tools/yulopti.cpp | 2 +- tools/yulPhaser/Program.cpp | 6 +- 148 files changed, 879 insertions(+), 871 deletions(-) create mode 100644 libyul/YulName.h diff --git a/libsolc/libsolc.cpp b/libsolc/libsolc.cpp index 105949253260..b49905130ccc 100644 --- a/libsolc/libsolc.cpp +++ b/libsolc/libsolc.cpp @@ -24,7 +24,7 @@ #include #include #include -#include +#include #include #include diff --git a/libsolidity/analysis/ReferencesResolver.cpp b/libsolidity/analysis/ReferencesResolver.cpp index fd7def71459a..270e1a55abc5 100644 --- a/libsolidity/analysis/ReferencesResolver.cpp +++ b/libsolidity/analysis/ReferencesResolver.cpp @@ -488,7 +488,7 @@ void ReferencesResolver::resolveInheritDoc(StructuredDocumentation const& _docum } } -void ReferencesResolver::validateYulIdentifierName(yul::YulString _name, SourceLocation const& _location) +void ReferencesResolver::validateYulIdentifierName(yul::YulName _name, SourceLocation const& _location) { if (util::contains(_name.str(), '.')) m_errorReporter.declarationError( diff --git a/libsolidity/analysis/ReferencesResolver.h b/libsolidity/analysis/ReferencesResolver.h index 13752e9c9345..0b7f9d37329f 100644 --- a/libsolidity/analysis/ReferencesResolver.h +++ b/libsolidity/analysis/ReferencesResolver.h @@ -94,7 +94,7 @@ class ReferencesResolver: private ASTConstVisitor, private yul::ASTWalker void resolveInheritDoc(StructuredDocumentation const& _documentation, StructurallyDocumentedAnnotation& _annotation); /// Checks if the name contains a '.'. - void validateYulIdentifierName(yul::YulString _name, langutil::SourceLocation const& _location); + void validateYulIdentifierName(yul::YulName _name, langutil::SourceLocation const& _location); langutil::ErrorReporter& m_errorReporter; NameAndTypeResolver& m_resolver; diff --git a/libsolidity/codegen/CompilerContext.cpp b/libsolidity/codegen/CompilerContext.cpp index d9264c6ac5f1..4d522072af06 100644 --- a/libsolidity/codegen/CompilerContext.cpp +++ b/libsolidity/codegen/CompilerContext.cpp @@ -38,7 +38,7 @@ #include #include #include -#include +#include #include #include @@ -388,11 +388,11 @@ void CompilerContext::appendInlineAssembly( { unsigned startStackHeight = stackHeight(); - std::set externallyUsedIdentifiers; + std::set externallyUsedIdentifiers; for (auto const& fun: _externallyUsedFunctions) - externallyUsedIdentifiers.insert(yul::YulString(fun)); + externallyUsedIdentifiers.insert(yul::YulName(fun)); for (auto const& var: _localVariables) - externallyUsedIdentifiers.insert(yul::YulString(var)); + externallyUsedIdentifiers.insert(yul::YulName(var)); yul::ExternalIdentifierAccess identifierAccess; identifierAccess.resolve = [&]( @@ -532,7 +532,7 @@ void CompilerContext::appendInlineAssembly( } -void CompilerContext::optimizeYul(yul::Object& _object, yul::EVMDialect const& _dialect, OptimiserSettings const& _optimiserSettings, std::set const& _externalIdentifiers) +void CompilerContext::optimizeYul(yul::Object& _object, yul::EVMDialect const& _dialect, OptimiserSettings const& _optimiserSettings, std::set const& _externalIdentifiers) { #ifdef SOL_OUTPUT_ASM cout << yul::AsmPrinter(*dialect)(*_object.code) << endl; diff --git a/libsolidity/codegen/CompilerContext.h b/libsolidity/codegen/CompilerContext.h index 8eba084eba7b..c6972f92b83b 100644 --- a/libsolidity/codegen/CompilerContext.h +++ b/libsolidity/codegen/CompilerContext.h @@ -277,7 +277,7 @@ class CompilerContext /// Otherwise returns "revert(0, 0)". std::string revertReasonIfDebug(std::string const& _message = ""); - void optimizeYul(yul::Object& _object, yul::EVMDialect const& _dialect, OptimiserSettings const& _optimiserSetting, std::set const& _externalIdentifiers = {}); + void optimizeYul(yul::Object& _object, yul::EVMDialect const& _dialect, OptimiserSettings const& _optimiserSetting, std::set const& _externalIdentifiers = {}); /// Appends arbitrary data to the end of the bytecode. void appendToAuxiliaryData(bytes const& _data) { m_asm->appendToAuxiliaryData(_data); } diff --git a/libsolidity/codegen/ContractCompiler.cpp b/libsolidity/codegen/ContractCompiler.cpp index 2326d3336364..0ed17f6d02b0 100644 --- a/libsolidity/codegen/ContractCompiler.cpp +++ b/libsolidity/codegen/ContractCompiler.cpp @@ -38,7 +38,7 @@ #include #include #include -#include +#include #include #include diff --git a/libsolidity/codegen/ir/IRGeneratorForStatements.cpp b/libsolidity/codegen/ir/IRGeneratorForStatements.cpp index 0579f50c2d96..5be4d550e767 100644 --- a/libsolidity/codegen/ir/IRGeneratorForStatements.cpp +++ b/libsolidity/codegen/ir/IRGeneratorForStatements.cpp @@ -78,7 +78,7 @@ struct CopyTranslate: public yul::ASTCopier return ASTCopier::operator()(_identifier); } - yul::YulString translateIdentifier(yul::YulString _name) override + yul::YulName translateIdentifier(yul::YulName _name) override { // Strictly, the dialect used by inline assembly (m_dialect) could be different // from the Yul dialect we are compiling to. So we are assuming here that the builtin @@ -87,7 +87,7 @@ struct CopyTranslate: public yul::ASTCopier if (m_dialect.builtin(_name)) return _name; else - return yul::YulString{"usr$" + _name.str()}; + return yul::YulName{"usr$" + _name.str()}; } yul::Identifier translate(yul::Identifier const& _identifier) override @@ -206,7 +206,7 @@ struct CopyTranslate: public yul::ASTCopier if (isDigit(value.front())) return yul::Literal{_identifier.debugData, yul::LiteralKind::Number, yul::valueOfNumberLiteral(value), {}}; else - return yul::Identifier{_identifier.debugData, yul::YulString{value}}; + return yul::Identifier{_identifier.debugData, yul::YulName{value}}; } diff --git a/libsolidity/experimental/codegen/IRGeneratorForStatements.cpp b/libsolidity/experimental/codegen/IRGeneratorForStatements.cpp index cb4705f0d189..f9c50cf7a78c 100644 --- a/libsolidity/experimental/codegen/IRGeneratorForStatements.cpp +++ b/libsolidity/experimental/codegen/IRGeneratorForStatements.cpp @@ -70,12 +70,12 @@ struct CopyTranslate: public yul::ASTCopier return ASTCopier::operator()(_identifier); } - yul::YulString translateIdentifier(yul::YulString _name) override + yul::YulName translateIdentifier(yul::YulName _name) override { if (m_dialect.builtin(_name)) return _name; else - return yul::YulString{"usr$" + _name.str()}; + return yul::YulName{"usr$" + _name.str()}; } yul::Identifier translate(yul::Identifier const& _identifier) override @@ -102,7 +102,7 @@ struct CopyTranslate: public yul::ASTCopier solAssert(type); solAssert(m_context.env->typeEquals(*type, m_context.analysis.typeSystem().type(PrimitiveType::Word, {}))); std::string value = IRNames::localVariable(*varDecl); - return yul::Identifier{_identifier.debugData, yul::YulString{value}}; + return yul::Identifier{_identifier.debugData, yul::YulName{value}}; } IRGenerationContext const& m_context; diff --git a/libsolidity/interface/CompilerStack.cpp b/libsolidity/interface/CompilerStack.cpp index 8ee55d87f5a5..b82e4edaff4b 100644 --- a/libsolidity/interface/CompilerStack.cpp +++ b/libsolidity/interface/CompilerStack.cpp @@ -66,7 +66,7 @@ #include -#include +#include #include #include #include diff --git a/libyul/AST.h b/libyul/AST.h index ad60e468592a..72be60a46843 100644 --- a/libyul/AST.h +++ b/libyul/AST.h @@ -24,7 +24,7 @@ #pragma once #include -#include +#include #include @@ -36,9 +36,9 @@ namespace solidity::yul { -using Type = YulString; +using Type = YulName; -struct TypedName { langutil::DebugData::ConstPtr debugData; YulString name; Type type; }; +struct TypedName { langutil::DebugData::ConstPtr debugData; YulName name; Type type; }; using TypedNameList = std::vector; /// Literal number or string (up to 32 bytes) @@ -70,7 +70,7 @@ class LiteralValue { }; struct Literal { langutil::DebugData::ConstPtr debugData; LiteralKind kind; LiteralValue value; Type type; }; /// External / internal identifier or label reference -struct Identifier { langutil::DebugData::ConstPtr debugData; YulString name; }; +struct Identifier { langutil::DebugData::ConstPtr debugData; YulName name; }; /// Assignment ("x := mload(20:u256)", expects push-1-expression on the right hand /// side and requires x to occupy exactly one stack slot. /// @@ -86,7 +86,7 @@ struct VariableDeclaration { langutil::DebugData::ConstPtr debugData; TypedNameL /// Block that creates a scope (frees declared stack variables) struct Block { langutil::DebugData::ConstPtr debugData; std::vector statements; }; /// Function definition ("function f(a, b) -> (d, e) { ... }") -struct FunctionDefinition { langutil::DebugData::ConstPtr debugData; YulString name; TypedNameList parameters; TypedNameList returnVariables; Block body; }; +struct FunctionDefinition { langutil::DebugData::ConstPtr debugData; YulName name; TypedNameList parameters; TypedNameList returnVariables; Block body; }; /// Conditional execution without "else" part. struct If { langutil::DebugData::ConstPtr debugData; std::unique_ptr condition; Block body; }; /// Switch case or default case diff --git a/libyul/AsmAnalysis.cpp b/libyul/AsmAnalysis.cpp index 38b9c782e0fc..cccb3de42158 100644 --- a/libyul/AsmAnalysis.cpp +++ b/libyul/AsmAnalysis.cpp @@ -100,7 +100,7 @@ AsmAnalysisInfo AsmAnalyzer::analyzeStrictAssertCorrect(Dialect const& _dialect, return analysisInfo; } -std::vector AsmAnalyzer::operator()(Literal const& _literal) +std::vector AsmAnalyzer::operator()(Literal const& _literal) { expectValidType(_literal.type, nativeLocationOf(_literal)); bool erroneousLiteralValue = false; @@ -132,11 +132,11 @@ std::vector AsmAnalyzer::operator()(Literal const& _literal) return {_literal.type}; } -std::vector AsmAnalyzer::operator()(Identifier const& _identifier) +std::vector AsmAnalyzer::operator()(Identifier const& _identifier) { yulAssert(!_identifier.name.empty(), ""); auto watcher = m_errorReporter.errorWatcher(); - YulString type = m_dialect.defaultType; + YulName type = m_dialect.defaultType; if (m_currentScope->lookup(_identifier.name, GenericVisitor{ [&](Scope::Variable const& _var) @@ -190,7 +190,7 @@ std::vector AsmAnalyzer::operator()(Identifier const& _identifier) void AsmAnalyzer::operator()(ExpressionStatement const& _statement) { auto watcher = m_errorReporter.errorWatcher(); - std::vector types = std::visit(*this, _statement.expression); + std::vector types = std::visit(*this, _statement.expression); if (watcher.ok() && !types.empty()) m_errorReporter.typeError( 3083_error, @@ -209,7 +209,7 @@ void AsmAnalyzer::operator()(Assignment const& _assignment) size_t const numVariables = _assignment.variableNames.size(); yulAssert(numVariables >= 1, ""); - std::set variables; + std::set variables; for (auto const& _variableName: _assignment.variableNames) if (!variables.insert(_variableName.name).second) m_errorReporter.declarationError( @@ -220,7 +220,7 @@ void AsmAnalyzer::operator()(Assignment const& _assignment) " occurs multiple times on the left-hand side of the assignment." ); - std::vector types = std::visit(*this, *_assignment.value); + std::vector types = std::visit(*this, *_assignment.value); if (types.size() != numVariables) m_errorReporter.declarationError( @@ -259,7 +259,7 @@ void AsmAnalyzer::operator()(VariableDeclaration const& _varDecl) if (_varDecl.value) { - std::vector types = std::visit(*this, *_varDecl.value); + std::vector types = std::visit(*this, *_varDecl.value); if (types.size() != numVariables) m_errorReporter.declarationError( 3812_error, @@ -275,7 +275,7 @@ void AsmAnalyzer::operator()(VariableDeclaration const& _varDecl) for (size_t i = 0; i < _varDecl.variables.size(); ++i) { - YulString givenType = m_dialect.defaultType; + YulName givenType = m_dialect.defaultType; if (i < types.size()) givenType = types[i]; TypedName const& variable = _varDecl.variables[i]; @@ -311,17 +311,17 @@ void AsmAnalyzer::operator()(FunctionDefinition const& _funDef) (*this)(_funDef.body); } -std::vector AsmAnalyzer::operator()(FunctionCall const& _funCall) +std::vector AsmAnalyzer::operator()(FunctionCall const& _funCall) { yulAssert(!_funCall.functionName.name.empty(), ""); auto watcher = m_errorReporter.errorWatcher(); - std::vector const* parameterTypes = nullptr; - std::vector const* returnTypes = nullptr; + std::vector const* parameterTypes = nullptr; + std::vector const* returnTypes = nullptr; std::vector> const* literalArguments = nullptr; if (BuiltinFunction const* f = m_dialect.builtin(_funCall.functionName.name)) { - if (_funCall.functionName.name == "selfdestruct"_yulstring) + if (_funCall.functionName.name == "selfdestruct"_yulname) m_errorReporter.warning( 1699_error, nativeLocationOf(_funCall.functionName), @@ -334,7 +334,7 @@ std::vector AsmAnalyzer::operator()(FunctionCall const& _funCall) ); else if ( m_evmVersion.supportsTransientStorage() && - _funCall.functionName.name == "tstore"_yulstring && + _funCall.functionName.name == "tstore"_yulname && !m_errorReporter.hasError({2394}) ) m_errorReporter.warning( @@ -400,7 +400,7 @@ std::vector AsmAnalyzer::operator()(FunctionCall const& _funCall) std::to_string(_funCall.arguments.size()) + "." ); - std::vector argTypes; + std::vector argTypes; for (size_t i = _funCall.arguments.size(); i > 0; i--) { Expression const& arg = _funCall.arguments[i - 1]; @@ -465,7 +465,7 @@ std::vector AsmAnalyzer::operator()(FunctionCall const& _funCall) return *returnTypes; } else if (returnTypes) - return std::vector(returnTypes->size(), m_dialect.defaultType); + return std::vector(returnTypes->size(), m_dialect.defaultType); else return {}; } @@ -488,7 +488,7 @@ void AsmAnalyzer::operator()(Switch const& _switch) "\"switch\" statement with only a default case." ); - YulString valueType = expectExpression(*_switch.expression); + YulName valueType = expectExpression(*_switch.expression); std::set cases; for (auto const& _case: _switch.cases) @@ -553,9 +553,9 @@ void AsmAnalyzer::operator()(Block const& _block) m_currentScope = previousScope; } -YulString AsmAnalyzer::expectExpression(Expression const& _expr) +YulName AsmAnalyzer::expectExpression(Expression const& _expr) { - std::vector types = std::visit(*this, _expr); + std::vector types = std::visit(*this, _expr); if (types.size() != 1) m_errorReporter.typeError( 3950_error, @@ -567,7 +567,7 @@ YulString AsmAnalyzer::expectExpression(Expression const& _expr) return types.empty() ? m_dialect.defaultType : types.front(); } -YulString AsmAnalyzer::expectUnlimitedStringLiteral(Literal const& _literal) +YulName AsmAnalyzer::expectUnlimitedStringLiteral(Literal const& _literal) { yulAssert(_literal.kind == LiteralKind::String); yulAssert(m_dialect.validTypeForLiteral(LiteralKind::String, _literal.value, _literal.type)); @@ -578,7 +578,7 @@ YulString AsmAnalyzer::expectUnlimitedStringLiteral(Literal const& _literal) void AsmAnalyzer::expectBoolExpression(Expression const& _expr) { - YulString type = expectExpression(_expr); + YulName type = expectExpression(_expr); if (type != m_dialect.boolType) m_errorReporter.typeError( 1733_error, @@ -591,11 +591,11 @@ void AsmAnalyzer::expectBoolExpression(Expression const& _expr) ); } -void AsmAnalyzer::checkAssignment(Identifier const& _variable, YulString _valueType) +void AsmAnalyzer::checkAssignment(Identifier const& _variable, YulName _valueType) { yulAssert(!_variable.name.empty(), ""); auto watcher = m_errorReporter.errorWatcher(); - YulString const* variableType = nullptr; + YulName const* variableType = nullptr; bool found = false; if (Scope::Identifier const* var = m_currentScope->lookup(_variable.name)) { @@ -654,7 +654,7 @@ Scope& AsmAnalyzer::scope(Block const* _block) return *scopePtr; } -void AsmAnalyzer::expectValidIdentifier(YulString _identifier, SourceLocation const& _location) +void AsmAnalyzer::expectValidIdentifier(YulName _identifier, SourceLocation const& _location) { // NOTE: the leading dot case is handled by the parser not allowing it. if (boost::ends_with(_identifier.str(), ".")) @@ -679,7 +679,7 @@ void AsmAnalyzer::expectValidIdentifier(YulString _identifier, SourceLocation co ); } -void AsmAnalyzer::expectValidType(YulString _type, SourceLocation const& _location) +void AsmAnalyzer::expectValidType(YulName _type, SourceLocation const& _location) { if (!m_dialect.types.count(_type)) m_errorReporter.typeError( @@ -689,7 +689,7 @@ void AsmAnalyzer::expectValidType(YulString _type, SourceLocation const& _locati ); } -void AsmAnalyzer::expectType(YulString _expectedType, YulString _givenType, SourceLocation const& _location) +void AsmAnalyzer::expectType(YulName _expectedType, YulName _givenType, SourceLocation const& _location) { if (_expectedType != _givenType) m_errorReporter.typeError( @@ -702,7 +702,7 @@ void AsmAnalyzer::expectType(YulString _expectedType, YulString _givenType, Sour bool AsmAnalyzer::validateInstructions(std::string const& _instructionIdentifier, langutil::SourceLocation const& _location) { // NOTE: This function uses the default EVM version instead of the currently selected one. - auto const builtin = EVMDialect::strictAssemblyForEVM(EVMVersion{}).builtin(YulString(_instructionIdentifier)); + auto const builtin = EVMDialect::strictAssemblyForEVM(EVMVersion{}).builtin(YulName(_instructionIdentifier)); if (builtin && builtin->instruction.has_value()) return validateInstructions(builtin->instruction.value(), _location); else diff --git a/libyul/AsmAnalysis.h b/libyul/AsmAnalysis.h index 9dd4b2292383..5aa7fe4968f6 100644 --- a/libyul/AsmAnalysis.h +++ b/libyul/AsmAnalysis.h @@ -79,13 +79,13 @@ class AsmAnalyzer /// Asserts on failure. static AsmAnalysisInfo analyzeStrictAssertCorrect(Dialect const& _dialect, Object const& _object); - std::vector operator()(Literal const& _literal); - std::vector operator()(Identifier const&); + std::vector operator()(Literal const& _literal); + std::vector operator()(Identifier const&); void operator()(ExpressionStatement const&); void operator()(Assignment const& _assignment); void operator()(VariableDeclaration const& _variableDeclaration); void operator()(FunctionDefinition const& _functionDefinition); - std::vector operator()(FunctionCall const& _functionCall); + std::vector operator()(FunctionCall const& _functionCall); void operator()(If const& _if); void operator()(Switch const& _switch); void operator()(ForLoop const& _forLoop); @@ -99,20 +99,20 @@ class AsmAnalyzer private: /// Visits the expression, expects that it evaluates to exactly one value and /// returns the type. Reports errors on errors and returns the default type. - YulString expectExpression(Expression const& _expr); - YulString expectUnlimitedStringLiteral(Literal const& _literal); + YulName expectExpression(Expression const& _expr); + YulName expectUnlimitedStringLiteral(Literal const& _literal); /// Visits the expression and expects it to return a single boolean value. /// Reports an error otherwise. void expectBoolExpression(Expression const& _expr); /// Verifies that a variable to be assigned to exists, can be assigned to /// and has the same type as the value. - void checkAssignment(Identifier const& _variable, YulString _valueType); + void checkAssignment(Identifier const& _variable, YulName _valueType); Scope& scope(Block const* _block); - void expectValidIdentifier(YulString _identifier, langutil::SourceLocation const& _location); - void expectValidType(YulString _type, langutil::SourceLocation const& _location); - void expectType(YulString _expectedType, YulString _givenType, langutil::SourceLocation const& _location); + void expectValidIdentifier(YulName _identifier, langutil::SourceLocation const& _location); + void expectValidType(YulName _type, langutil::SourceLocation const& _location); + void expectType(YulName _expectedType, YulName _givenType, langutil::SourceLocation const& _location); bool validateInstructions(evmasm::Instruction _instr, langutil::SourceLocation const& _location); bool validateInstructions(std::string const& _instrIdentifier, langutil::SourceLocation const& _location); diff --git a/libyul/AsmJsonImporter.cpp b/libyul/AsmJsonImporter.cpp index 63b1d65d26ec..8f211f31b435 100644 --- a/libyul/AsmJsonImporter.cpp +++ b/libyul/AsmJsonImporter.cpp @@ -72,8 +72,8 @@ Json AsmJsonImporter::member(Json const& _node, std::string const& _name) TypedName AsmJsonImporter::createTypedName(Json const& _node) { auto typedName = createAsmNode(_node); - typedName.type = YulString{member(_node, "type").get()}; - typedName.name = YulString{member(_node, "name").get()}; + typedName.type = YulName{member(_node, "type").get()}; + typedName.name = YulName{member(_node, "name").get()}; return typedName; } @@ -171,7 +171,7 @@ Literal AsmJsonImporter::createLiteral(Json const& _node) value = util::asString(util::fromHex(member(_node, "hexValue").get())); else value = member(_node, "value").get(); - lit.type = YulString{member(_node, "type").get()}; + lit.type = YulName{member(_node, "type").get()}; if (kind == "number") { langutil::CharStream charStream(value, ""); @@ -219,7 +219,7 @@ Leave AsmJsonImporter::createLeave(Json const& _node) Identifier AsmJsonImporter::createIdentifier(Json const& _node) { auto identifier = createAsmNode(_node); - identifier.name = YulString(member(_node, "name").get()); + identifier.name = YulName(member(_node, "name").get()); return identifier; } @@ -269,7 +269,7 @@ VariableDeclaration AsmJsonImporter::createVariableDeclaration(Json const& _node FunctionDefinition AsmJsonImporter::createFunctionDefinition(Json const& _node) { auto funcDef = createAsmNode(_node); - funcDef.name = YulString{member(_node, "name").get()}; + funcDef.name = YulName{member(_node, "name").get()}; if (_node.contains("parameters")) for (auto const& var: member(_node, "parameters")) diff --git a/libyul/AsmParser.cpp b/libyul/AsmParser.cpp index 2ae4dd805bc1..41bef57fe0f1 100644 --- a/libyul/AsmParser.cpp +++ b/libyul/AsmParser.cpp @@ -537,7 +537,7 @@ std::variant Parser::parseLiteralOrIdentifier(bool _unlimit { case Token::Identifier: { - Identifier identifier{createDebugData(), YulString{currentLiteral()}}; + Identifier identifier{createDebugData(), YulName{currentLiteral()}}; advance(); return identifier; } @@ -712,9 +712,9 @@ TypedName Parser::parseTypedName() return typedName; } -YulString Parser::expectAsmIdentifier() +YulName Parser::expectAsmIdentifier() { - YulString name{currentLiteral()}; + YulName name{currentLiteral()}; if (currentToken() == Token::Identifier && m_dialect.builtin(name)) fatalParserError(5568_error, "Cannot use builtin function name \"" + name.str() + "\" as identifier name."); // NOTE: We keep the expectation here to ensure the correct source location for the error above. diff --git a/libyul/AsmParser.h b/libyul/AsmParser.h index 3348904091f2..408c8029cf58 100644 --- a/libyul/AsmParser.h +++ b/libyul/AsmParser.h @@ -146,7 +146,7 @@ class Parser: public langutil::ParserBase FunctionDefinition parseFunctionDefinition(); FunctionCall parseCall(std::variant&& _initialOp); TypedName parseTypedName(); - YulString expectAsmIdentifier(); + YulName expectAsmIdentifier(); /// Reports an error if we are currently not inside the body part of a for loop. void checkBreakContinuePosition(std::string const& _which); diff --git a/libyul/AsmPrinter.cpp b/libyul/AsmPrinter.cpp index 191fc5d2d6a1..054f83a91398 100644 --- a/libyul/AsmPrinter.cpp +++ b/libyul/AsmPrinter.cpp @@ -243,7 +243,7 @@ std::string AsmPrinter::formatTypedName(TypedName _variable) return formatDebugData(_variable) + _variable.name.str() + appendTypeName(_variable.type); } -std::string AsmPrinter::appendTypeName(YulString _type, bool _isBoolLiteral) const +std::string AsmPrinter::appendTypeName(YulName _type, bool _isBoolLiteral) const { if (m_dialect && !_type.empty()) { diff --git a/libyul/AsmPrinter.h b/libyul/AsmPrinter.h index d3f80b9a09d5..36ea06c76769 100644 --- a/libyul/AsmPrinter.h +++ b/libyul/AsmPrinter.h @@ -24,7 +24,7 @@ #pragma once #include -#include +#include #include @@ -92,7 +92,7 @@ class AsmPrinter private: std::string formatTypedName(TypedName _variable); - std::string appendTypeName(YulString _type, bool _isBoolLiteral = false) const; + std::string appendTypeName(YulName _type, bool _isBoolLiteral = false) const; std::string formatDebugData(langutil::DebugData::ConstPtr const& _debugData, bool _statement); template std::string formatDebugData(T const& _node) diff --git a/libyul/CMakeLists.txt b/libyul/CMakeLists.txt index 92b03facfe93..ee78d525dfc7 100644 --- a/libyul/CMakeLists.txt +++ b/libyul/CMakeLists.txt @@ -37,6 +37,7 @@ add_library(yul ScopeFiller.h Utilities.cpp Utilities.h + YulName.h YulString.h backends/evm/AbstractAssembly.h backends/evm/AsmCodeGen.cpp diff --git a/libyul/CompilabilityChecker.h b/libyul/CompilabilityChecker.h index c046df94ffb9..89bb7aa7c993 100644 --- a/libyul/CompilabilityChecker.h +++ b/libyul/CompilabilityChecker.h @@ -45,8 +45,8 @@ namespace solidity::yul struct CompilabilityChecker { CompilabilityChecker(Dialect const& _dialect, Object const& _object, bool _optimizeStackAllocation); - std::map> unreachableVariables; - std::map stackDeficit; + std::map> unreachableVariables; + std::map stackDeficit; }; } diff --git a/libyul/ControlFlowSideEffectsCollector.cpp b/libyul/ControlFlowSideEffectsCollector.cpp index c657fa17cba2..471a164e523b 100644 --- a/libyul/ControlFlowSideEffectsCollector.cpp +++ b/libyul/ControlFlowSideEffectsCollector.cpp @@ -229,9 +229,9 @@ ControlFlowSideEffectsCollector::ControlFlowSideEffectsCollector( } } -std::map ControlFlowSideEffectsCollector::functionSideEffectsNamed() const +std::map ControlFlowSideEffectsCollector::functionSideEffectsNamed() const { - std::map result; + std::map result; for (auto&& [function, sideEffects]: m_functionSideEffects) yulAssert(result.insert({function->name, sideEffects}).second); return result; diff --git a/libyul/ControlFlowSideEffectsCollector.h b/libyul/ControlFlowSideEffectsCollector.h index a4ab2bfae770..5a1c76297012 100644 --- a/libyul/ControlFlowSideEffectsCollector.h +++ b/libyul/ControlFlowSideEffectsCollector.h @@ -101,7 +101,7 @@ class ControlFlowSideEffectsCollector return m_functionSideEffects; } /// Returns the side effects by function name, requires unique function names. - std::map functionSideEffectsNamed() const; + std::map functionSideEffectsNamed() const; private: /// @returns false if nothing could be processed. diff --git a/libyul/Dialect.cpp b/libyul/Dialect.cpp index 69ca1e9dc68d..f4f59ec26aa7 100644 --- a/libyul/Dialect.cpp +++ b/libyul/Dialect.cpp @@ -25,7 +25,7 @@ using namespace solidity::yul; using namespace solidity::langutil; -Literal Dialect::zeroLiteralForType(solidity::yul::YulString _type) const +Literal Dialect::zeroLiteralForType(solidity::yul::YulName _type) const { if (_type == boolType && _type != defaultType) return {DebugData::create(), LiteralKind::Boolean, LiteralValue(false), _type}; @@ -41,7 +41,7 @@ Literal Dialect::trueLiteral() const return {DebugData::create(), LiteralKind::Number, LiteralValue(1), defaultType}; } -bool Dialect::validTypeForLiteral(LiteralKind _kind, LiteralValue const&, YulString _type) const +bool Dialect::validTypeForLiteral(LiteralKind _kind, LiteralValue const&, YulName _type) const { if (_kind == LiteralKind::Boolean) return _type == boolType; @@ -58,21 +58,20 @@ Dialect const& Dialect::yulDeprecated() { // TODO will probably change, especially the list of types. dialect = std::make_unique(); - dialect->defaultType = "u256"_yulstring; - dialect->boolType = "bool"_yulstring; + dialect->defaultType = "u256"_yulname; + dialect->boolType = "bool"_yulname; dialect->types = { - "bool"_yulstring, - "u8"_yulstring, - "s8"_yulstring, - "u32"_yulstring, - "s32"_yulstring, - "u64"_yulstring, - "s64"_yulstring, - "u128"_yulstring, - "s128"_yulstring, - "u256"_yulstring, - "s256"_yulstring - }; + "bool"_yulname, + "u8"_yulname, + "s8"_yulname, + "u32"_yulname, + "s32"_yulname, + "u64"_yulname, + "s64"_yulname, + "u128"_yulname, + "s128"_yulname, + "u256"_yulname, + "s256"_yulname}; }; return *dialect; diff --git a/libyul/Dialect.h b/libyul/Dialect.h index e3f270357f91..3362246a063a 100644 --- a/libyul/Dialect.h +++ b/libyul/Dialect.h @@ -21,7 +21,7 @@ #pragma once -#include +#include #include #include @@ -32,15 +32,14 @@ namespace solidity::yul { -class YulString; -using Type = YulString; +using Type = YulName; enum class LiteralKind; class LiteralValue; struct Literal; struct BuiltinFunction { - YulString name; + YulName name; std::vector parameters; std::vector returns; SideEffects sideEffects; @@ -63,35 +62,35 @@ struct Dialect Dialect& operator=(Dialect const&) = delete; /// Default type, can be omitted. - YulString defaultType; + YulName defaultType; /// Type used for the literals "true" and "false". - YulString boolType; - std::set types = {{}}; + YulName boolType; + std::set types = {{}}; /// @returns the builtin function of the given name or a nullptr if it is not a builtin function. - virtual BuiltinFunction const* builtin(YulString /*_name*/) const { return nullptr; } + virtual BuiltinFunction const* builtin(YulName /*_name*/) const { return nullptr; } /// @returns true if the identifier is reserved. This includes the builtins too. - virtual bool reservedIdentifier(YulString _name) const { return builtin(_name) != nullptr; } + virtual bool reservedIdentifier(YulName _name) const { return builtin(_name) != nullptr; } - virtual BuiltinFunction const* discardFunction(YulString /* _type */) const { return nullptr; } - virtual BuiltinFunction const* equalityFunction(YulString /* _type */) const { return nullptr; } + virtual BuiltinFunction const* discardFunction(YulName /* _type */) const { return nullptr; } + virtual BuiltinFunction const* equalityFunction(YulName /* _type */) const { return nullptr; } virtual BuiltinFunction const* booleanNegationFunction() const { return nullptr; } - virtual BuiltinFunction const* memoryStoreFunction(YulString /* _type */) const { return nullptr; } - virtual BuiltinFunction const* memoryLoadFunction(YulString /* _type */) const { return nullptr; } - virtual BuiltinFunction const* storageStoreFunction(YulString /* _type */) const { return nullptr; } - virtual BuiltinFunction const* storageLoadFunction(YulString /* _type */) const { return nullptr; } - virtual YulString hashFunction(YulString /* _type */ ) const { return YulString{}; } + virtual BuiltinFunction const* memoryStoreFunction(YulName /* _type */) const { return nullptr; } + virtual BuiltinFunction const* memoryLoadFunction(YulName /* _type */) const { return nullptr; } + virtual BuiltinFunction const* storageStoreFunction(YulName /* _type */) const { return nullptr; } + virtual BuiltinFunction const* storageLoadFunction(YulName /* _type */) const { return nullptr; } + virtual YulName hashFunction(YulName /* _type */ ) const { return YulName{}; } /// Check whether the given type is legal for the given literal value. /// Should only be called if the type exists in the dialect at all. - virtual bool validTypeForLiteral(LiteralKind _kind, LiteralValue const& _value, YulString _type) const; + virtual bool validTypeForLiteral(LiteralKind _kind, LiteralValue const& _value, YulName _type) const; - virtual Literal zeroLiteralForType(YulString _type) const; + virtual Literal zeroLiteralForType(YulName _type) const; virtual Literal trueLiteral() const; - virtual std::set fixedFunctionNames() const { return {}; } + virtual std::set fixedFunctionNames() const { return {}; } Dialect() = default; virtual ~Dialect() = default; diff --git a/libyul/Exceptions.h b/libyul/Exceptions.h index 45c681a5d6e5..f92268180971 100644 --- a/libyul/Exceptions.h +++ b/libyul/Exceptions.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include @@ -40,18 +40,18 @@ struct YulAssertion: virtual YulException {}; struct StackTooDeepError: virtual YulException { - StackTooDeepError(YulString _variable, int _depth, std::string const& _message): + StackTooDeepError(YulName _variable, int _depth, std::string const& _message): variable(_variable), depth(_depth) { *this << util::errinfo_comment(_message); } - StackTooDeepError(YulString _functionName, YulString _variable, int _depth, std::string const& _message): + StackTooDeepError(YulName _functionName, YulName _variable, int _depth, std::string const& _message): functionName(_functionName), variable(_variable), depth(_depth) { *this << util::errinfo_comment(_message); } - YulString functionName; - YulString variable; + YulName functionName; + YulName variable; int depth; }; diff --git a/libyul/FunctionReferenceResolver.h b/libyul/FunctionReferenceResolver.h index 8c1385adb6c7..dcc5f50e5b76 100644 --- a/libyul/FunctionReferenceResolver.h +++ b/libyul/FunctionReferenceResolver.h @@ -41,7 +41,7 @@ class FunctionReferenceResolver: private ASTWalker void operator()(Block const& _block) override; std::map m_functionReferences; - std::vector> m_scopes; + std::vector> m_scopes; }; diff --git a/libyul/Object.h b/libyul/Object.h index c1ca9244d98d..af354005b66b 100644 --- a/libyul/Object.h +++ b/libyul/Object.h @@ -22,7 +22,6 @@ #pragma once #include -#include #include #include diff --git a/libyul/ObjectParser.h b/libyul/ObjectParser.h index 08a852991203..a8f75d373c9b 100644 --- a/libyul/ObjectParser.h +++ b/libyul/ObjectParser.h @@ -21,7 +21,6 @@ #pragma once -#include #include #include diff --git a/libyul/Scope.cpp b/libyul/Scope.cpp index 4471aa53130d..89bdfc674c56 100644 --- a/libyul/Scope.cpp +++ b/libyul/Scope.cpp @@ -25,7 +25,7 @@ using namespace solidity; using namespace solidity::yul; using namespace solidity::util; -bool Scope::registerVariable(YulString _name, YulType const& _type) +bool Scope::registerVariable(YulName _name, YulType const& _type) { if (exists(_name)) return false; @@ -36,7 +36,7 @@ bool Scope::registerVariable(YulString _name, YulType const& _type) return true; } -bool Scope::registerFunction(YulString _name, std::vector _arguments, std::vector _returns) +bool Scope::registerFunction(YulName _name, std::vector _arguments, std::vector _returns) { if (exists(_name)) return false; @@ -44,7 +44,7 @@ bool Scope::registerFunction(YulString _name, std::vector _arguments, s return true; } -Scope::Identifier* Scope::lookup(YulString _name) +Scope::Identifier* Scope::lookup(YulName _name) { bool crossedFunctionBoundary = false; for (Scope* s = this; s; s = s->superScope) @@ -64,7 +64,7 @@ Scope::Identifier* Scope::lookup(YulString _name) return nullptr; } -bool Scope::exists(YulString _name) const +bool Scope::exists(YulName _name) const { if (identifiers.count(_name)) return true; diff --git a/libyul/Scope.h b/libyul/Scope.h index f9ac3830a295..027597290063 100644 --- a/libyul/Scope.h +++ b/libyul/Scope.h @@ -23,7 +23,7 @@ #include -#include +#include #include #include @@ -35,25 +35,25 @@ namespace solidity::yul struct Scope { - using YulType = YulString; + using YulType = YulName; struct Variable { YulType type; - YulString name; + YulName name; }; struct Function { std::vector arguments; std::vector returns; - YulString name; + YulName name; }; using Identifier = std::variant; - bool registerVariable(YulString _name, YulType const& _type); + bool registerVariable(YulName _name, YulType const& _type); bool registerFunction( - YulString _name, + YulName _name, std::vector _arguments, std::vector _returns ); @@ -63,12 +63,12 @@ struct Scope /// will any lookups across assembly boundaries. /// The pointer will be invalidated if the scope is modified. /// @param _crossedFunction if true, we already crossed a function boundary during recursive lookup - Identifier* lookup(YulString _name); + Identifier* lookup(YulName _name); /// Looks up the identifier in this and super scopes (will not find variables across function /// boundaries and generally stops at assembly boundaries) and calls the visitor, returns /// false if not found. template - bool lookup(YulString _name, V const& _visitor) + bool lookup(YulName _name, V const& _visitor) { if (Identifier* id = lookup(_name)) { @@ -80,7 +80,7 @@ struct Scope } /// @returns true if the name exists in this scope or in super scopes (also searches /// across function and assembly boundaries). - bool exists(YulString _name) const; + bool exists(YulName _name) const; /// @returns the number of variables directly registered inside the scope. size_t numberOfVariables() const; @@ -91,7 +91,7 @@ struct Scope /// If true, variables from the super scope are not visible here (other identifiers are), /// but they are still taken into account to prevent shadowing. bool functionScope = false; - std::map identifiers; + std::map identifiers; }; } diff --git a/libyul/YulName.h b/libyul/YulName.h new file mode 100644 index 000000000000..34fd6a5a26b0 --- /dev/null +++ b/libyul/YulName.h @@ -0,0 +1,26 @@ +/* + 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 . +*/ +// SPDX-License-Identifier: GPL-3.0 + +#pragma once + +#include + +namespace solidity::yul +{ +using YulName = YulString; +} diff --git a/libyul/YulString.h b/libyul/YulString.h index 7dbaf1b84a03..89d35b123cab 100644 --- a/libyul/YulString.h +++ b/libyul/YulString.h @@ -162,7 +162,7 @@ class YulString YulStringRepository::Handle m_handle{ 0, YulStringRepository::emptyHash() }; }; -inline YulString operator "" _yulstring(char const* _string, std::size_t _size) +inline YulString operator "" _yulname(char const* _string, std::size_t _size) { return YulString(std::string(_string, _size)); } diff --git a/libyul/backends/evm/ConstantOptimiser.cpp b/libyul/backends/evm/ConstantOptimiser.cpp index 7b17f7d89012..2ab77f84e92d 100644 --- a/libyul/backends/evm/ConstantOptimiser.cpp +++ b/libyul/backends/evm/ConstantOptimiser.cpp @@ -129,7 +129,7 @@ Representation const& RepresentationFinder::findRepresentation(u256 const& _valu if (numberEncodingSize(~_value) < numberEncodingSize(_value)) // Negated is shorter to represent - routine = min(std::move(routine), represent("not"_yulstring, findRepresentation(~_value))); + routine = min(std::move(routine), represent("not"_yulname, findRepresentation(~_value))); // Decompose value into a * 2**k + b where abs(b) << 2**k for (unsigned bits = 255; bits > 8 && m_maxSteps > 0; --bits) @@ -152,21 +152,21 @@ Representation const& RepresentationFinder::findRepresentation(u256 const& _valu continue; Representation newRoutine; if (m_dialect.evmVersion().hasBitwiseShifting()) - newRoutine = represent("shl"_yulstring, represent(bits), findRepresentation(upperPart)); + newRoutine = represent("shl"_yulname, represent(bits), findRepresentation(upperPart)); else { - newRoutine = represent("exp"_yulstring, represent(2), represent(bits)); + newRoutine = represent("exp"_yulname, represent(2), represent(bits)); if (upperPart != 1) - newRoutine = represent("mul"_yulstring, findRepresentation(upperPart), newRoutine); + newRoutine = represent("mul"_yulname, findRepresentation(upperPart), newRoutine); } if (newRoutine.cost >= routine.cost) continue; if (lowerPart > 0) - newRoutine = represent("add"_yulstring, newRoutine, findRepresentation(u256(abs(lowerPart)))); + newRoutine = represent("add"_yulname, newRoutine, findRepresentation(u256(abs(lowerPart)))); else if (lowerPart < 0) - newRoutine = represent("sub"_yulstring, newRoutine, findRepresentation(u256(abs(lowerPart)))); + newRoutine = represent("sub"_yulname, newRoutine, findRepresentation(u256(abs(lowerPart)))); if (m_maxSteps > 0) m_maxSteps--; @@ -185,7 +185,7 @@ Representation RepresentationFinder::represent(u256 const& _value) const } Representation RepresentationFinder::represent( - YulString _instruction, + YulName _instruction, Representation const& _argument ) const { @@ -200,7 +200,7 @@ Representation RepresentationFinder::represent( } Representation RepresentationFinder::represent( - YulString _instruction, + YulName _instruction, Representation const& _arg1, Representation const& _arg2 ) const diff --git a/libyul/backends/evm/ConstantOptimiser.h b/libyul/backends/evm/ConstantOptimiser.h index 280f50bf9b97..35d7dfa43254 100644 --- a/libyul/backends/evm/ConstantOptimiser.h +++ b/libyul/backends/evm/ConstantOptimiser.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include #include #include @@ -93,8 +93,8 @@ class RepresentationFinder Representation const& findRepresentation(u256 const& _value); Representation represent(u256 const& _value) const; - Representation represent(YulString _instruction, Representation const& _arg) const; - Representation represent(YulString _instruction, Representation const& _arg1, Representation const& _arg2) const; + Representation represent(YulName _instruction, Representation const& _arg) const; + Representation represent(YulName _instruction, Representation const& _arg1, Representation const& _arg2) const; Representation min(Representation _a, Representation _b); diff --git a/libyul/backends/evm/ControlFlowGraphBuilder.cpp b/libyul/backends/evm/ControlFlowGraphBuilder.cpp index a5e9613b5887..b4d1cdf15c3a 100644 --- a/libyul/backends/evm/ControlFlowGraphBuilder.cpp +++ b/libyul/backends/evm/ControlFlowGraphBuilder.cpp @@ -336,8 +336,8 @@ void ControlFlowGraphBuilder::operator()(Switch const& _switch) langutil::DebugData::ConstPtr preSwitchDebugData = debugDataOf(_switch); auto ghostVariableId = m_graph.ghostVariables.size(); - YulString ghostVariableName("GHOST[" + std::to_string(ghostVariableId) + "]"); - auto& ghostVar = m_graph.ghostVariables.emplace_back(Scope::Variable{""_yulstring, ghostVariableName}); + YulName ghostVariableName("GHOST[" + std::to_string(ghostVariableId) + "]"); + auto& ghostVar = m_graph.ghostVariables.emplace_back(Scope::Variable{""_yulname, ghostVariableName}); // Artificially generate: // let := @@ -357,7 +357,7 @@ void ControlFlowGraphBuilder::operator()(Switch const& _switch) auto makeValueCompare = [&](Case const& _case) { yul::FunctionCall const& ghostCall = m_graph.ghostCalls.emplace_back(yul::FunctionCall{ debugDataOf(_case), - yul::Identifier{{}, "eq"_yulstring}, + yul::Identifier{{}, "eq"_yulname}, {*_case.value, Identifier{{}, ghostVariableName}} }); CFG::Operation& operation = m_currentBlock->operations.emplace_back(CFG::Operation{ @@ -578,7 +578,7 @@ Stack ControlFlowGraphBuilder::visitAssignmentRightHandSide(Expression const& _e }, _expression); } -Scope::Function const& ControlFlowGraphBuilder::lookupFunction(YulString _name) const +Scope::Function const& ControlFlowGraphBuilder::lookupFunction(YulName _name) const { Scope::Function const* function = nullptr; yulAssert(m_scope->lookup(_name, util::GenericVisitor{ @@ -589,7 +589,7 @@ Scope::Function const& ControlFlowGraphBuilder::lookupFunction(YulString _name) return *function; } -Scope::Variable const& ControlFlowGraphBuilder::lookupVariable(YulString _name) const +Scope::Variable const& ControlFlowGraphBuilder::lookupVariable(YulName _name) const { yulAssert(m_scope, ""); Scope::Variable const* var = nullptr; diff --git a/libyul/backends/evm/ControlFlowGraphBuilder.h b/libyul/backends/evm/ControlFlowGraphBuilder.h index 5007d361089b..77feaea7b469 100644 --- a/libyul/backends/evm/ControlFlowGraphBuilder.h +++ b/libyul/backends/evm/ControlFlowGraphBuilder.h @@ -63,8 +63,8 @@ class ControlFlowGraphBuilder Stack const& visitFunctionCall(FunctionCall const&); Stack visitAssignmentRightHandSide(Expression const& _expression, size_t _expectedSlotCount); - Scope::Function const& lookupFunction(YulString _name) const; - Scope::Variable const& lookupVariable(YulString _name) const; + Scope::Function const& lookupFunction(YulName _name) const; + Scope::Variable const& lookupVariable(YulName _name) const; /// Resets m_currentBlock to enforce a subsequent explicit reassignment. void makeConditionalJump( langutil::DebugData::ConstPtr _debugData, diff --git a/libyul/backends/evm/EVMCodeTransform.cpp b/libyul/backends/evm/EVMCodeTransform.cpp index bdce395ef89f..21124723003b 100644 --- a/libyul/backends/evm/EVMCodeTransform.cpp +++ b/libyul/backends/evm/EVMCodeTransform.cpp @@ -79,7 +79,7 @@ CodeTransform::CodeTransform( } } -void CodeTransform::decreaseReference(YulString, Scope::Variable const& _var) +void CodeTransform::decreaseReference(YulName, Scope::Variable const& _var) { if (!m_allowStackOpt) return; @@ -158,7 +158,7 @@ void CodeTransform::operator()(VariableDeclaration const& _varDecl) for (size_t varIndex = 0; varIndex < numVariables; ++varIndex) { size_t varIndexReverse = numVariables - 1 - varIndex; - YulString varName = _varDecl.variables[varIndexReverse].name; + YulName varName = _varDecl.variables[varIndexReverse].name; auto& var = std::get(m_scope->identifiers.at(varName)); m_context->variableStackHeights[&var] = heightAtStart + varIndexReverse; if (!m_allowStackOpt) @@ -457,7 +457,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function) { StackTooDeepError error( _function.name, - YulString{}, + YulName{}, static_cast(stackLayout.size()) - 17, "The function " + _function.name.str() + @@ -667,7 +667,7 @@ bool statementNeedsReturnVariableSetup(Statement const& _statement, std::vector< std::holds_alternative(_statement) ) { - std::map references = VariableReferencesCounter::countReferences(_statement); + std::map references = VariableReferencesCounter::countReferences(_statement); auto isReferenced = [&references](TypedName const& _returnVariable) { return references.count(_returnVariable.name); }; @@ -771,7 +771,7 @@ void CodeTransform::generateAssignment(Identifier const& _variableName) } } -size_t CodeTransform::variableHeightDiff(Scope::Variable const& _var, YulString _varName, bool _forSwap) +size_t CodeTransform::variableHeightDiff(Scope::Variable const& _var, YulName _varName, bool _forSwap) { yulAssert(m_context->variableStackHeights.count(&_var), ""); size_t heightDiff = static_cast(m_assembly.stackHeight()) - m_context->variableStackHeights[&_var]; @@ -795,7 +795,7 @@ size_t CodeTransform::variableHeightDiff(Scope::Variable const& _var, YulString return heightDiff; } -int CodeTransform::variableStackHeight(YulString _name) const +int CodeTransform::variableStackHeight(YulName _name) const { Scope::Variable const* var = std::get_if(m_scope->lookup(_name)); yulAssert(var, ""); diff --git a/libyul/backends/evm/EVMCodeTransform.h b/libyul/backends/evm/EVMCodeTransform.h index bad9a357ff29..0e6a9d8be1db 100644 --- a/libyul/backends/evm/EVMCodeTransform.h +++ b/libyul/backends/evm/EVMCodeTransform.h @@ -118,7 +118,7 @@ class CodeTransform std::optional _functionExitLabel ); - void decreaseReference(YulString _name, Scope::Variable const& _var); + void decreaseReference(YulName _name, Scope::Variable const& _var); bool unreferenced(Scope::Variable const& _var) const; /// Marks slots of variables that are not used anymore /// and were defined in the current scope for reuse. @@ -165,10 +165,10 @@ class CodeTransform /// the (positive) stack height difference otherwise. /// @param _forSwap if true, produces stack error if the difference is invalid for a swap /// opcode, otherwise checks for validity for a dup opcode. - size_t variableHeightDiff(Scope::Variable const& _var, YulString _name, bool _forSwap); + size_t variableHeightDiff(Scope::Variable const& _var, YulName _name, bool _forSwap); /// Determines the stack height of the given variable. Throws if the variable is not in scope. - int variableStackHeight(YulString _name) const; + int variableStackHeight(YulName _name) const; void expectDeposit(int _deposit, int _oldHeight) const; @@ -198,7 +198,7 @@ class CodeTransform BuiltinContext& m_builtinContext; bool const m_allowStackOpt = true; UseNamedLabels const m_useNamedLabelsForFunctions = UseNamedLabels::Never; - std::set m_assignedNamedLabels; + std::set m_assignedNamedLabels; ExternalIdentifierAccess::CodeGenerator m_identifierAccessCodeGen; std::shared_ptr m_context; diff --git a/libyul/backends/evm/EVMDialect.cpp b/libyul/backends/evm/EVMDialect.cpp index d3b9c34bcb5a..50ede8c760f0 100644 --- a/libyul/backends/evm/EVMDialect.cpp +++ b/libyul/backends/evm/EVMDialect.cpp @@ -46,7 +46,7 @@ using namespace solidity::util; namespace { -std::pair createEVMFunction( +std::pair createEVMFunction( langutil::EVMVersion _evmVersion, std::string const& _name, evmasm::Instruction _instruction @@ -54,7 +54,7 @@ std::pair createEVMFunction( { evmasm::InstructionInfo info = evmasm::instructionInfo(_instruction, _evmVersion); BuiltinFunctionForEVM f; - f.name = YulString{_name}; + f.name = YulName{_name}; f.parameters.resize(static_cast(info.args)); f.returns.resize(static_cast(info.ret)); f.sideEffects = EVMDialect::sideEffectsOfInstruction(_instruction); @@ -83,11 +83,11 @@ std::pair createEVMFunction( _assembly.appendInstruction(_instruction); }; - YulString name = f.name; + YulName name = f.name; return {name, std::move(f)}; } -std::pair createFunction( +std::pair createFunction( std::string _name, size_t _params, size_t _returns, @@ -98,7 +98,7 @@ std::pair createFunction( { yulAssert(_literalArguments.size() == _params || _literalArguments.empty(), ""); - YulString name{std::move(_name)}; + YulName name{std::move(_name)}; BuiltinFunctionForEVM f; f.name = name; f.parameters.resize(_params); @@ -111,7 +111,7 @@ std::pair createFunction( return {name, f}; } -std::set createReservedIdentifiers(langutil::EVMVersion _evmVersion) +std::set createReservedIdentifiers(langutil::EVMVersion _evmVersion) { // TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name // basefee for VMs before london. @@ -157,7 +157,7 @@ std::set createReservedIdentifiers(langutil::EVMVersion _evmVersion) (_instr == evmasm::Instruction::TSTORE || _instr == evmasm::Instruction::TLOAD); }; - std::set reserved; + std::set reserved; for (auto const& instr: evmasm::c_instructions) { std::string name = toLower(instr.first); @@ -171,18 +171,18 @@ std::set createReservedIdentifiers(langutil::EVMVersion _evmVersion) ) reserved.emplace(name); } - reserved += std::vector{ - "linkersymbol"_yulstring, - "datasize"_yulstring, - "dataoffset"_yulstring, - "datacopy"_yulstring, - "setimmutable"_yulstring, - "loadimmutable"_yulstring, + reserved += std::vector{ + "linkersymbol"_yulname, + "datasize"_yulname, + "dataoffset"_yulname, + "datacopy"_yulname, + "setimmutable"_yulname, + "loadimmutable"_yulname, }; return reserved; } -std::map createBuiltins(langutil::EVMVersion _evmVersion, bool _objectAccess) +std::map createBuiltins(langutil::EVMVersion _evmVersion, bool _objectAccess) { // Exclude prevrandao as builtin for VMs before paris and difficulty for VMs after paris. @@ -191,7 +191,7 @@ std::map createBuiltins(langutil::EVMVersion _ return (_instrName == "prevrandao" && _evmVersion < langutil::EVMVersion::paris()) || (_instrName == "difficulty" && _evmVersion >= langutil::EVMVersion::paris()); }; - std::map builtins; + std::map builtins; for (auto const& instr: evmasm::c_instructions) { std::string name = toLower(instr.first); @@ -248,7 +248,7 @@ std::map createBuiltins(langutil::EVMVersion _ yulAssert(_context.currentObject, "No object available."); yulAssert(_call.arguments.size() == 1, ""); Expression const& arg = _call.arguments.front(); - YulString const dataName (formatLiteral(std::get(arg))); + YulName const dataName (formatLiteral(std::get(arg))); if (_context.currentObject->name == dataName.str()) _assembly.appendAssemblySize(); else @@ -269,7 +269,7 @@ std::map createBuiltins(langutil::EVMVersion _ yulAssert(_context.currentObject, "No object available."); yulAssert(_call.arguments.size() == 1, ""); Expression const& arg = _call.arguments.front(); - YulString const dataName (formatLiteral(std::get(arg))); + YulName const dataName (formatLiteral(std::get(arg))); if (_context.currentObject->name == dataName.str()) _assembly.appendConstant(0); else @@ -368,7 +368,7 @@ EVMDialect::EVMDialect(langutil::EVMVersion _evmVersion, bool _objectAccess): { } -BuiltinFunctionForEVM const* EVMDialect::builtin(YulString _name) const +BuiltinFunctionForEVM const* EVMDialect::builtin(YulName _name) const { if (m_objectAccess) { @@ -383,7 +383,7 @@ BuiltinFunctionForEVM const* EVMDialect::builtin(YulString _name) const return nullptr; } -bool EVMDialect::reservedIdentifier(YulString _name) const +bool EVMDialect::reservedIdentifier(YulName _name) const { if (m_objectAccess) if (_name.str().substr(0, "verbatim"s.size()) == "verbatim") @@ -465,8 +465,8 @@ BuiltinFunctionForEVM const* EVMDialect::verbatimFunction(size_t _arguments, siz EVMDialectTyped::EVMDialectTyped(langutil::EVMVersion _evmVersion, bool _objectAccess): EVMDialect(_evmVersion, _objectAccess) { - defaultType = "u256"_yulstring; - boolType = "bool"_yulstring; + defaultType = "u256"_yulname; + boolType = "bool"_yulname; types = {defaultType, boolType}; // Set all types to ``defaultType`` @@ -478,43 +478,43 @@ EVMDialectTyped::EVMDialectTyped(langutil::EVMVersion _evmVersion, bool _objectA r = defaultType; } - m_functions["lt"_yulstring].returns = {"bool"_yulstring}; - m_functions["gt"_yulstring].returns = {"bool"_yulstring}; - m_functions["slt"_yulstring].returns = {"bool"_yulstring}; - m_functions["sgt"_yulstring].returns = {"bool"_yulstring}; - m_functions["eq"_yulstring].returns = {"bool"_yulstring}; + m_functions["lt"_yulname].returns = {"bool"_yulname}; + m_functions["gt"_yulname].returns = {"bool"_yulname}; + m_functions["slt"_yulname].returns = {"bool"_yulname}; + m_functions["sgt"_yulname].returns = {"bool"_yulname}; + m_functions["eq"_yulname].returns = {"bool"_yulname}; // "not" and "bitnot" replace "iszero" and "not" - m_functions["bitnot"_yulstring] = m_functions["not"_yulstring]; - m_functions["bitnot"_yulstring].name = "bitnot"_yulstring; - m_functions["not"_yulstring] = m_functions["iszero"_yulstring]; - m_functions["not"_yulstring].name = "not"_yulstring; - m_functions["not"_yulstring].returns = {"bool"_yulstring}; - m_functions["not"_yulstring].parameters = {"bool"_yulstring}; - m_functions.erase("iszero"_yulstring); - - m_functions["bitand"_yulstring] = m_functions["and"_yulstring]; - m_functions["bitand"_yulstring].name = "bitand"_yulstring; - m_functions["bitor"_yulstring] = m_functions["or"_yulstring]; - m_functions["bitor"_yulstring].name = "bitor"_yulstring; - m_functions["bitxor"_yulstring] = m_functions["xor"_yulstring]; - m_functions["bitxor"_yulstring].name = "bitxor"_yulstring; - m_functions["and"_yulstring].parameters = {"bool"_yulstring, "bool"_yulstring}; - m_functions["and"_yulstring].returns = {"bool"_yulstring}; - m_functions["or"_yulstring].parameters = {"bool"_yulstring, "bool"_yulstring}; - m_functions["or"_yulstring].returns = {"bool"_yulstring}; - m_functions["xor"_yulstring].parameters = {"bool"_yulstring, "bool"_yulstring}; - m_functions["xor"_yulstring].returns = {"bool"_yulstring}; - m_functions["popbool"_yulstring] = m_functions["pop"_yulstring]; - m_functions["popbool"_yulstring].name = "popbool"_yulstring; - m_functions["popbool"_yulstring].parameters = {"bool"_yulstring}; + m_functions["bitnot"_yulname] = m_functions["not"_yulname]; + m_functions["bitnot"_yulname].name = "bitnot"_yulname; + m_functions["not"_yulname] = m_functions["iszero"_yulname]; + m_functions["not"_yulname].name = "not"_yulname; + m_functions["not"_yulname].returns = {"bool"_yulname}; + m_functions["not"_yulname].parameters = {"bool"_yulname}; + m_functions.erase("iszero"_yulname); + + m_functions["bitand"_yulname] = m_functions["and"_yulname]; + m_functions["bitand"_yulname].name = "bitand"_yulname; + m_functions["bitor"_yulname] = m_functions["or"_yulname]; + m_functions["bitor"_yulname].name = "bitor"_yulname; + m_functions["bitxor"_yulname] = m_functions["xor"_yulname]; + m_functions["bitxor"_yulname].name = "bitxor"_yulname; + m_functions["and"_yulname].parameters = {"bool"_yulname, "bool"_yulname}; + m_functions["and"_yulname].returns = {"bool"_yulname}; + m_functions["or"_yulname].parameters = {"bool"_yulname, "bool"_yulname}; + m_functions["or"_yulname].returns = {"bool"_yulname}; + m_functions["xor"_yulname].parameters = {"bool"_yulname, "bool"_yulname}; + m_functions["xor"_yulname].returns = {"bool"_yulname}; + m_functions["popbool"_yulname] = m_functions["pop"_yulname]; + m_functions["popbool"_yulname].name = "popbool"_yulname; + m_functions["popbool"_yulname].parameters = {"bool"_yulname}; m_functions.insert(createFunction("bool_to_u256", 1, 1, {}, {}, []( FunctionCall const&, AbstractAssembly&, BuiltinContext& ) {})); - m_functions["bool_to_u256"_yulstring].parameters = {"bool"_yulstring}; - m_functions["bool_to_u256"_yulstring].returns = {"u256"_yulstring}; + m_functions["bool_to_u256"_yulname].parameters = {"bool"_yulname}; + m_functions["bool_to_u256"_yulname].returns = {"u256"_yulname}; m_functions.insert(createFunction("u256_to_bool", 1, 1, {}, {}, []( FunctionCall const&, AbstractAssembly& _assembly, @@ -530,29 +530,29 @@ EVMDialectTyped::EVMDialectTyped(langutil::EVMVersion _evmVersion, bool _objectA _assembly.appendInstruction(evmasm::Instruction::INVALID); _assembly.appendLabel(inRange); })); - m_functions["u256_to_bool"_yulstring].parameters = {"u256"_yulstring}; - m_functions["u256_to_bool"_yulstring].returns = {"bool"_yulstring}; + m_functions["u256_to_bool"_yulname].parameters = {"u256"_yulname}; + m_functions["u256_to_bool"_yulname].returns = {"bool"_yulname}; } -BuiltinFunctionForEVM const* EVMDialectTyped::discardFunction(YulString _type) const +BuiltinFunctionForEVM const* EVMDialectTyped::discardFunction(YulName _type) const { - if (_type == "bool"_yulstring) - return builtin("popbool"_yulstring); + if (_type == "bool"_yulname) + return builtin("popbool"_yulname); else { yulAssert(_type == defaultType, ""); - return builtin("pop"_yulstring); + return builtin("pop"_yulname); } } -BuiltinFunctionForEVM const* EVMDialectTyped::equalityFunction(YulString _type) const +BuiltinFunctionForEVM const* EVMDialectTyped::equalityFunction(YulName _type) const { - if (_type == "bool"_yulstring) + if (_type == "bool"_yulname) return nullptr; else { yulAssert(_type == defaultType, ""); - return builtin("eq"_yulstring); + return builtin("eq"_yulname); } } diff --git a/libyul/backends/evm/EVMDialect.h b/libyul/backends/evm/EVMDialect.h index f0455a8e4240..7db1ec09d32b 100644 --- a/libyul/backends/evm/EVMDialect.h +++ b/libyul/backends/evm/EVMDialect.h @@ -33,8 +33,7 @@ namespace solidity::yul { -class YulString; -using Type = YulString; +using Type = YulName; struct FunctionCall; struct Object; @@ -70,19 +69,19 @@ struct EVMDialect: public Dialect EVMDialect(langutil::EVMVersion _evmVersion, bool _objectAccess); /// @returns the builtin function of the given name or a nullptr if it is not a builtin function. - BuiltinFunctionForEVM const* builtin(YulString _name) const override; + BuiltinFunctionForEVM const* builtin(YulName _name) const override; /// @returns true if the identifier is reserved. This includes the builtins too. - bool reservedIdentifier(YulString _name) const override; + bool reservedIdentifier(YulName _name) const override; - BuiltinFunctionForEVM const* discardFunction(YulString /*_type*/) const override { return builtin("pop"_yulstring); } - BuiltinFunctionForEVM const* equalityFunction(YulString /*_type*/) const override { return builtin("eq"_yulstring); } - BuiltinFunctionForEVM const* booleanNegationFunction() const override { return builtin("iszero"_yulstring); } - BuiltinFunctionForEVM const* memoryStoreFunction(YulString /*_type*/) const override { return builtin("mstore"_yulstring); } - BuiltinFunctionForEVM const* memoryLoadFunction(YulString /*_type*/) const override { return builtin("mload"_yulstring); } - BuiltinFunctionForEVM const* storageStoreFunction(YulString /*_type*/) const override { return builtin("sstore"_yulstring); } - BuiltinFunctionForEVM const* storageLoadFunction(YulString /*_type*/) const override { return builtin("sload"_yulstring); } - YulString hashFunction(YulString /*_type*/) const override { return "keccak256"_yulstring; } + BuiltinFunctionForEVM const* discardFunction(YulName /*_type*/) const override { return builtin("pop"_yulname); } + BuiltinFunctionForEVM const* equalityFunction(YulName /*_type*/) const override { return builtin("eq"_yulname); } + BuiltinFunctionForEVM const* booleanNegationFunction() const override { return builtin("iszero"_yulname); } + BuiltinFunctionForEVM const* memoryStoreFunction(YulName /*_type*/) const override { return builtin("mstore"_yulname); } + BuiltinFunctionForEVM const* memoryLoadFunction(YulName /*_type*/) const override { return builtin("mload"_yulname); } + BuiltinFunctionForEVM const* storageStoreFunction(YulName /*_type*/) const override { return builtin("sstore"_yulname); } + BuiltinFunctionForEVM const* storageLoadFunction(YulName /*_type*/) const override { return builtin("sload"_yulname); } + YulName hashFunction(YulName /*_type*/) const override { return "keccak256"_yulname; } static EVMDialect const& strictAssemblyForEVM(langutil::EVMVersion _version); static EVMDialect const& strictAssemblyForEVMObjects(langutil::EVMVersion _version); @@ -98,9 +97,9 @@ struct EVMDialect: public Dialect bool const m_objectAccess; langutil::EVMVersion const m_evmVersion; - std::map m_functions; + std::map m_functions; std::map, std::shared_ptr> mutable m_verbatimFunctions; - std::set m_reserved; + std::set m_reserved; }; /** @@ -118,9 +117,9 @@ struct EVMDialectTyped: public EVMDialect /// Constructor, should only be used internally. Use the factory function below. EVMDialectTyped(langutil::EVMVersion _evmVersion, bool _objectAccess); - BuiltinFunctionForEVM const* discardFunction(YulString _type) const override; - BuiltinFunctionForEVM const* equalityFunction(YulString _type) const override; - BuiltinFunctionForEVM const* booleanNegationFunction() const override { return builtin("not"_yulstring); } + BuiltinFunctionForEVM const* discardFunction(YulName _type) const override; + BuiltinFunctionForEVM const* equalityFunction(YulName _type) const override; + BuiltinFunctionForEVM const* booleanNegationFunction() const override { return builtin("not"_yulname); } static EVMDialectTyped const& instance(langutil::EVMVersion _version); }; diff --git a/libyul/backends/evm/EVMObjectCompiler.cpp b/libyul/backends/evm/EVMObjectCompiler.cpp index 81a345f90889..422c08bf96aa 100644 --- a/libyul/backends/evm/EVMObjectCompiler.cpp +++ b/libyul/backends/evm/EVMObjectCompiler.cpp @@ -92,7 +92,7 @@ void EVMObjectCompiler::run(Object& _object, bool _optimize) { std::vector memoryGuardCalls = findFunctionCalls( std::as_const(*_object.code), - "memoryguard"_yulstring + "memoryguard"_yulname ); auto stackError = stackErrors.front(); std::string msg = stackError.comment() ? *stackError.comment() : ""; diff --git a/libyul/backends/evm/OptimizedEVMCodeTransform.cpp b/libyul/backends/evm/OptimizedEVMCodeTransform.cpp index 047014e3dc43..a6b867aba167 100644 --- a/libyul/backends/evm/OptimizedEVMCodeTransform.cpp +++ b/libyul/backends/evm/OptimizedEVMCodeTransform.cpp @@ -185,7 +185,7 @@ OptimizedEVMCodeTransform::OptimizedEVMCodeTransform( m_stackLayout(_stackLayout), m_functionLabels([&](){ std::map functionLabels; - std::set assignedFunctionNames; + std::set assignedFunctionNames; for (Scope::Function const* function: m_dfg.functions) { CFG::FunctionInfo const& functionInfo = m_dfg.functionInfo.at(function); @@ -242,7 +242,7 @@ void OptimizedEVMCodeTransform::createStackLayout(langutil::DebugData::ConstPtr static constexpr auto slotVariableName = [](StackSlot const& _slot) { return std::visit(util::GenericVisitor{ [](VariableSlot const& _var) { return _var.variable.get().name; }, - [](auto const&) { return YulString{}; } + [](auto const&) { return YulName{}; } }, _slot); }; @@ -264,14 +264,14 @@ void OptimizedEVMCodeTransform::createStackLayout(langutil::DebugData::ConstPtr { int deficit = static_cast(_i) - 16; StackSlot const& deepSlot = m_stack.at(m_stack.size() - _i - 1); - YulString varNameDeep = slotVariableName(deepSlot); - YulString varNameTop = slotVariableName(m_stack.back()); + YulName varNameDeep = slotVariableName(deepSlot); + YulName varNameTop = slotVariableName(m_stack.back()); std::string msg = "Cannot swap " + (varNameDeep.empty() ? "Slot " + stackSlotToString(deepSlot) : "Variable " + varNameDeep.str()) + " with " + (varNameTop.empty() ? "Slot " + stackSlotToString(m_stack.back()) : "Variable " + varNameTop.str()) + ": too deep in the stack by " + std::to_string(deficit) + " slots in " + stackToString(m_stack); m_stackErrors.emplace_back(StackTooDeepError( - m_currentFunctionInfo ? m_currentFunctionInfo->function.name : YulString{}, + m_currentFunctionInfo ? m_currentFunctionInfo->function.name : YulName{}, varNameDeep.empty() ? varNameTop : varNameDeep, deficit, msg @@ -295,12 +295,12 @@ void OptimizedEVMCodeTransform::createStackLayout(langutil::DebugData::ConstPtr else if (!canBeFreelyGenerated(_slot)) { int deficit = static_cast(*depth - 15); - YulString varName = slotVariableName(_slot); + YulName varName = slotVariableName(_slot); std::string msg = (varName.empty() ? "Slot " + stackSlotToString(_slot) : "Variable " + varName.str()) + " is " + std::to_string(*depth - 15) + " too deep in the stack " + stackToString(m_stack); m_stackErrors.emplace_back(StackTooDeepError( - m_currentFunctionInfo ? m_currentFunctionInfo->function.name : YulString{}, + m_currentFunctionInfo ? m_currentFunctionInfo->function.name : YulName{}, varName, deficit, msg diff --git a/libyul/backends/evm/StackLayoutGenerator.cpp b/libyul/backends/evm/StackLayoutGenerator.cpp index 954c9f2af7af..c781d7c1b813 100644 --- a/libyul/backends/evm/StackLayoutGenerator.cpp +++ b/libyul/backends/evm/StackLayoutGenerator.cpp @@ -58,17 +58,17 @@ StackLayout StackLayoutGenerator::run(CFG const& _cfg) return stackLayout; } -std::map> StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg) +std::map> StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg) { - std::map> stackTooDeepErrors; - stackTooDeepErrors[YulString{}] = reportStackTooDeep(_cfg, YulString{}); + std::map> stackTooDeepErrors; + stackTooDeepErrors[YulName{}] = reportStackTooDeep(_cfg, YulName{}); for (auto const& function: _cfg.functions) if (auto errors = reportStackTooDeep(_cfg, function->name); !errors.empty()) stackTooDeepErrors[function->name] = std::move(errors); return stackTooDeepErrors; } -std::vector StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg, YulString _functionName) +std::vector StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg, YulName _functionName) { StackLayout stackLayout; CFG::FunctionInfo const* functionInfo = nullptr; @@ -102,7 +102,7 @@ std::vector findStackTooDeep(Stack const& _s Stack currentStack = _source; std::vector stackTooDeepErrors; auto getVariableChoices = [](auto&& _range) { - std::vector result; + std::vector result; for (auto const& slot: _range) if (auto const* variableSlot = std::get_if(&slot)) if (!util::contains(result, variableSlot->variable.get().name)) diff --git a/libyul/backends/evm/StackLayoutGenerator.h b/libyul/backends/evm/StackLayoutGenerator.h index d04b80bdc02a..fc846a9deced 100644 --- a/libyul/backends/evm/StackLayoutGenerator.h +++ b/libyul/backends/evm/StackLayoutGenerator.h @@ -52,18 +52,18 @@ class StackLayoutGenerator /// Number of slots that need to be saved. size_t deficit = 0; /// Set of variables, eliminating which would decrease the stack deficit. - std::vector variableChoices; + std::vector variableChoices; }; static StackLayout run(CFG const& _cfg); /// @returns a map from function names to the stack too deep errors occurring in that function. /// Requires @a _cfg to be a control flow graph generated from disambiguated Yul. /// The empty string is mapped to the stack too deep errors of the main entry point. - static std::map> reportStackTooDeep(CFG const& _cfg); + static std::map> reportStackTooDeep(CFG const& _cfg); /// @returns all stack too deep errors in the function named @a _functionName. /// Requires @a _cfg to be a control flow graph generated from disambiguated Yul. /// If @a _functionName is empty, the stack too deep errors of the main entry point are reported instead. - static std::vector reportStackTooDeep(CFG const& _cfg, YulString _functionName); + static std::vector reportStackTooDeep(CFG const& _cfg, YulName _functionName); private: StackLayoutGenerator(StackLayout& _context, CFG::FunctionInfo const* _functionInfo); diff --git a/libyul/backends/evm/VariableReferenceCounter.cpp b/libyul/backends/evm/VariableReferenceCounter.cpp index c2afb399d28f..9f4857887754 100644 --- a/libyul/backends/evm/VariableReferenceCounter.cpp +++ b/libyul/backends/evm/VariableReferenceCounter.cpp @@ -71,7 +71,7 @@ void VariableReferenceCounter::operator()(Block const& _block) m_scope = originalScope; } -void VariableReferenceCounter::increaseRefIfFound(YulString _variableName) +void VariableReferenceCounter::increaseRefIfFound(YulName _variableName) { m_scope->lookup(_variableName, util::GenericVisitor{ [&](Scope::Variable const& _var) diff --git a/libyul/backends/evm/VariableReferenceCounter.h b/libyul/backends/evm/VariableReferenceCounter.h index ba6404b17180..75552279359b 100644 --- a/libyul/backends/evm/VariableReferenceCounter.h +++ b/libyul/backends/evm/VariableReferenceCounter.h @@ -58,7 +58,7 @@ struct VariableReferenceCounter: public yul::ASTWalker ): m_info(_assemblyInfo) {} - void increaseRefIfFound(YulString _variableName); + void increaseRefIfFound(YulName _variableName); AsmAnalysisInfo const& m_info; Scope* m_scope = nullptr; diff --git a/libyul/optimiser/ASTCopier.cpp b/libyul/optimiser/ASTCopier.cpp index 9f41079418b2..8efe29613e93 100644 --- a/libyul/optimiser/ASTCopier.cpp +++ b/libyul/optimiser/ASTCopier.cpp @@ -83,7 +83,7 @@ Statement ASTCopier::operator()(Switch const& _switch) Statement ASTCopier::operator()(FunctionDefinition const& _function) { - YulString translatedName = translateIdentifier(_function.name); + YulName translatedName = translateIdentifier(_function.name); enterFunction(_function); ScopeGuard g([&]() { this->leaveFunction(_function); }); @@ -168,7 +168,7 @@ TypedName ASTCopier::translate(TypedName const& _typedName) return TypedName{_typedName.debugData, translateIdentifier(_typedName.name), _typedName.type}; } -YulString FunctionCopier::translateIdentifier(YulString _name) +YulName FunctionCopier::translateIdentifier(YulName _name) { if (m_translations.count(_name)) return m_translations.at(_name); diff --git a/libyul/optimiser/ASTCopier.h b/libyul/optimiser/ASTCopier.h index db9d72af35ec..88d2a34510ad 100644 --- a/libyul/optimiser/ASTCopier.h +++ b/libyul/optimiser/ASTCopier.h @@ -23,7 +23,7 @@ #include -#include +#include #include #include @@ -106,7 +106,7 @@ class ASTCopier: public ExpressionCopier, public StatementCopier virtual void leaveScope(Block const&) { } virtual void enterFunction(FunctionDefinition const&) { } virtual void leaveFunction(FunctionDefinition const&) { } - virtual YulString translateIdentifier(YulString _name) { return _name; } + virtual YulName translateIdentifier(YulName _name) { return _name; } }; template @@ -124,16 +124,16 @@ class FunctionCopier: public ASTCopier { public: FunctionCopier( - std::map const& _translations + std::map const& _translations ): m_translations(_translations) {} using ASTCopier::operator(); - YulString translateIdentifier(YulString _name) override; + YulName translateIdentifier(YulName _name) override; private: /// A mapping between old and new names. We replace the names of variable declarations contained /// in the mapping with their new names. - std::map const& m_translations; + std::map const& m_translations; }; } diff --git a/libyul/optimiser/ASTWalker.h b/libyul/optimiser/ASTWalker.h index b937f7eae423..0c23a836e624 100644 --- a/libyul/optimiser/ASTWalker.h +++ b/libyul/optimiser/ASTWalker.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include diff --git a/libyul/optimiser/BlockHasher.h b/libyul/optimiser/BlockHasher.h index 2b9a71f101ac..427161b3c784 100644 --- a/libyul/optimiser/BlockHasher.h +++ b/libyul/optimiser/BlockHasher.h @@ -22,7 +22,7 @@ #include #include -#include +#include namespace solidity::yul { @@ -112,8 +112,8 @@ class BlockHasher: public ASTWalker, public ASTHasherBase size_t id = 0; bool isExternal = false; }; - std::map m_variableReferences; - std::vector m_externalReferences; + std::map m_variableReferences; + std::vector m_externalReferences; size_t m_externalIdentifierCount = 0; size_t m_internalIdentifierCount = 0; }; diff --git a/libyul/optimiser/CallGraphGenerator.cpp b/libyul/optimiser/CallGraphGenerator.cpp index 87035e68a0e7..f457f55838d3 100644 --- a/libyul/optimiser/CallGraphGenerator.cpp +++ b/libyul/optimiser/CallGraphGenerator.cpp @@ -35,11 +35,11 @@ namespace struct CallGraphCycleFinder { CallGraph const& callGraph; - std::set containedInCycle{}; - std::set visited{}; - std::vector currentPath{}; + std::set containedInCycle{}; + std::set visited{}; + std::vector currentPath{}; - void visit(YulString _function) + void visit(YulName _function) { if (visited.count(_function)) return; @@ -61,7 +61,7 @@ struct CallGraphCycleFinder }; } -std::set CallGraph::recursiveFunctions() const +std::set CallGraph::recursiveFunctions() const { CallGraphCycleFinder cycleFinder{*this}; // Visiting the root only is not enough, since there may be disconnected recursive functions. @@ -93,7 +93,7 @@ void CallGraphGenerator::operator()(ForLoop const& _forLoop) void CallGraphGenerator::operator()(FunctionDefinition const& _functionDefinition) { - YulString previousFunction = m_currentFunction; + YulName previousFunction = m_currentFunction; m_currentFunction = _functionDefinition.name; yulAssert(m_callGraph.functionCalls.count(m_currentFunction) == 0, ""); m_callGraph.functionCalls[m_currentFunction] = {}; @@ -103,6 +103,6 @@ void CallGraphGenerator::operator()(FunctionDefinition const& _functionDefinitio CallGraphGenerator::CallGraphGenerator() { - m_callGraph.functionCalls[YulString{}] = {}; + m_callGraph.functionCalls[YulName{}] = {}; } diff --git a/libyul/optimiser/CallGraphGenerator.h b/libyul/optimiser/CallGraphGenerator.h index ad19878b6892..23e9a2511588 100644 --- a/libyul/optimiser/CallGraphGenerator.h +++ b/libyul/optimiser/CallGraphGenerator.h @@ -32,12 +32,12 @@ namespace solidity::yul struct CallGraph { - std::map> functionCalls; - std::set functionsWithLoops; + std::map> functionCalls; + std::set functionsWithLoops; /// @returns the set of functions contained in cycles in the call graph, i.e. /// functions that are part of a (mutual) recursion. /// Note that this does not include functions that merely call recursive functions. - std::set recursiveFunctions() const; + std::set recursiveFunctions() const; }; /** @@ -62,7 +62,7 @@ class CallGraphGenerator: public ASTWalker CallGraph m_callGraph; /// The name of the function we are currently visiting during traversal. - YulString m_currentFunction; + YulName m_currentFunction; }; } diff --git a/libyul/optimiser/CircularReferencesPruner.cpp b/libyul/optimiser/CircularReferencesPruner.cpp index 824d2be39fb0..a34f3f4e2aa3 100644 --- a/libyul/optimiser/CircularReferencesPruner.cpp +++ b/libyul/optimiser/CircularReferencesPruner.cpp @@ -34,7 +34,7 @@ void CircularReferencesPruner::run(OptimiserStepContext& _context, Block& _ast) void CircularReferencesPruner::operator()(Block& _block) { - std::set functionsToKeep = + std::set functionsToKeep = functionsCalledFromOutermostContext(CallGraphGenerator::callGraph(_block)); for (auto&& statement: _block.statements) @@ -48,13 +48,13 @@ void CircularReferencesPruner::operator()(Block& _block) removeEmptyBlocks(_block); } -std::set CircularReferencesPruner::functionsCalledFromOutermostContext(CallGraph const& _callGraph) +std::set CircularReferencesPruner::functionsCalledFromOutermostContext(CallGraph const& _callGraph) { - std::set verticesToTraverse = m_reservedIdentifiers; - verticesToTraverse.insert(YulString("")); + std::set verticesToTraverse = m_reservedIdentifiers; + verticesToTraverse.insert(YulName("")); - return util::BreadthFirstSearch{{verticesToTraverse.begin(), verticesToTraverse.end()}}.run( - [&_callGraph](YulString _function, auto&& _addChild) { + return util::BreadthFirstSearch{{verticesToTraverse.begin(), verticesToTraverse.end()}}.run( + [&_callGraph](YulName _function, auto&& _addChild) { if (_callGraph.functionCalls.count(_function)) for (auto const& callee: _callGraph.functionCalls.at(_function)) if (_callGraph.functionCalls.count(callee)) diff --git a/libyul/optimiser/CircularReferencesPruner.h b/libyul/optimiser/CircularReferencesPruner.h index 0602445af4ab..090b0617fc8e 100644 --- a/libyul/optimiser/CircularReferencesPruner.h +++ b/libyul/optimiser/CircularReferencesPruner.h @@ -27,6 +27,7 @@ #include #include #include +#include namespace solidity::yul { @@ -44,16 +45,16 @@ class CircularReferencesPruner: public ASTModifier using ASTModifier::operator(); void operator()(Block& _block) override; private: - CircularReferencesPruner(std::set const& _reservedIdentifiers): + CircularReferencesPruner(std::set const& _reservedIdentifiers): m_reservedIdentifiers(_reservedIdentifiers) {} /// Run a breadth-first search starting from the outermost context and /// externally referenced functions to find all the functions that are /// called from there either directly or indirectly. - std::set functionsCalledFromOutermostContext(CallGraph const& _callGraph); + std::set functionsCalledFromOutermostContext(CallGraph const& _callGraph); - std::set const& m_reservedIdentifiers; + std::set const& m_reservedIdentifiers; }; } diff --git a/libyul/optimiser/CommonSubexpressionEliminator.cpp b/libyul/optimiser/CommonSubexpressionEliminator.cpp index 1c7879056d61..073d621cc2cf 100644 --- a/libyul/optimiser/CommonSubexpressionEliminator.cpp +++ b/libyul/optimiser/CommonSubexpressionEliminator.cpp @@ -46,7 +46,7 @@ void CommonSubexpressionEliminator::run(OptimiserStepContext& _context, Block& _ CommonSubexpressionEliminator::CommonSubexpressionEliminator( Dialect const& _dialect, - std::map _functionSideEffects + std::map _functionSideEffects ): DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore, std::move(_functionSideEffects)) { @@ -95,7 +95,7 @@ void CommonSubexpressionEliminator::visit(Expression& _e) if (Identifier const* identifier = std::get_if(&_e)) { - YulString identifierName = identifier->name; + YulName identifierName = identifier->name; if (AssignedValue const* assignedValue = variableValue(identifierName)) { assertThrow(assignedValue->value, OptimizerException, ""); @@ -126,7 +126,7 @@ void CommonSubexpressionEliminator::visit(Expression& _e) } } -void CommonSubexpressionEliminator::assignValue(YulString _variable, Expression const* _value) +void CommonSubexpressionEliminator::assignValue(YulName _variable, Expression const* _value) { if (_value) m_replacementCandidates[*_value].insert(_variable); diff --git a/libyul/optimiser/CommonSubexpressionEliminator.h b/libyul/optimiser/CommonSubexpressionEliminator.h index 163c9df994e4..d7dc42596ca4 100644 --- a/libyul/optimiser/CommonSubexpressionEliminator.h +++ b/libyul/optimiser/CommonSubexpressionEliminator.h @@ -53,19 +53,19 @@ class CommonSubexpressionEliminator: public DataFlowAnalyzer private: CommonSubexpressionEliminator( Dialect const& _dialect, - std::map _functionSideEffects + std::map _functionSideEffects ); protected: using ASTModifier::visit; void visit(Expression& _e) override; - void assignValue(YulString _variable, Expression const* _value) override; + void assignValue(YulName _variable, Expression const* _value) override; private: - std::set m_returnVariables; + std::set m_returnVariables; std::unordered_map< std::reference_wrapper, - std::set, + std::set, ExpressionHash, SyntacticallyEqualExpression > m_replacementCandidates; diff --git a/libyul/optimiser/ConditionalSimplifier.cpp b/libyul/optimiser/ConditionalSimplifier.cpp index 7119091257d3..a2656fed390e 100644 --- a/libyul/optimiser/ConditionalSimplifier.cpp +++ b/libyul/optimiser/ConditionalSimplifier.cpp @@ -42,7 +42,7 @@ void ConditionalSimplifier::operator()(Switch& _switch) ASTModifier::operator()(_switch); return; } - YulString expr = std::get(*_switch.expression).name; + YulName expr = std::get(*_switch.expression).name; for (auto& _case: _switch.cases) { if (_case.value) @@ -77,7 +77,7 @@ void ConditionalSimplifier::operator()(Block& _block) TerminationFinder::ControlFlow::FlowOut ) { - YulString condition = std::get(*_if.condition).name; + YulName condition = std::get(*_if.condition).name; langutil::DebugData::ConstPtr debugData = _if.debugData; return make_vector( std::move(_s), diff --git a/libyul/optimiser/ConditionalSimplifier.h b/libyul/optimiser/ConditionalSimplifier.h index e558a1c6cf5c..c78052126f5f 100644 --- a/libyul/optimiser/ConditionalSimplifier.h +++ b/libyul/optimiser/ConditionalSimplifier.h @@ -62,12 +62,12 @@ class ConditionalSimplifier: public ASTModifier private: explicit ConditionalSimplifier( Dialect const& _dialect, - std::map _sideEffects + std::map _sideEffects ): m_dialect(_dialect), m_functionSideEffects(std::move(_sideEffects)) {} Dialect const& m_dialect; - std::map m_functionSideEffects; + std::map m_functionSideEffects; }; } diff --git a/libyul/optimiser/ConditionalUnsimplifier.cpp b/libyul/optimiser/ConditionalUnsimplifier.cpp index 104ec1e4f095..06348e9977a1 100644 --- a/libyul/optimiser/ConditionalUnsimplifier.cpp +++ b/libyul/optimiser/ConditionalUnsimplifier.cpp @@ -43,7 +43,7 @@ void ConditionalUnsimplifier::operator()(Switch& _switch) ASTModifier::operator()(_switch); return; } - YulString expr = std::get(*_switch.expression).name; + YulName expr = std::get(*_switch.expression).name; for (auto& _case: _switch.cases) { if (_case.value) @@ -83,7 +83,7 @@ void ConditionalUnsimplifier::operator()(Block& _block) !_if.body.statements.empty() ) { - YulString condition = std::get(*_if.condition).name; + YulName condition = std::get(*_if.condition).name; if ( std::holds_alternative(_stmt2) && TerminationFinder(m_dialect, &m_functionSideEffects).controlFlowKind(_if.body.statements.back()) != diff --git a/libyul/optimiser/ConditionalUnsimplifier.h b/libyul/optimiser/ConditionalUnsimplifier.h index 8025b661b96b..dc1c6e24544e 100644 --- a/libyul/optimiser/ConditionalUnsimplifier.h +++ b/libyul/optimiser/ConditionalUnsimplifier.h @@ -42,12 +42,12 @@ class ConditionalUnsimplifier: public ASTModifier private: explicit ConditionalUnsimplifier( Dialect const& _dialect, - std::map const& _sideEffects + std::map const& _sideEffects ): m_dialect(_dialect), m_functionSideEffects(_sideEffects) {} Dialect const& m_dialect; - std::map const& m_functionSideEffects; + std::map const& m_functionSideEffects; }; } diff --git a/libyul/optimiser/ControlFlowSimplifier.cpp b/libyul/optimiser/ControlFlowSimplifier.cpp index 10f479a421b4..9d56583a0611 100644 --- a/libyul/optimiser/ControlFlowSimplifier.cpp +++ b/libyul/optimiser/ControlFlowSimplifier.cpp @@ -197,7 +197,7 @@ OptionalStatements ControlFlowSimplifier::reduceSingleCaseSwitch(Switch& _switch auto& switchCase = _switchStmt.cases.front(); langutil::DebugData::ConstPtr debugData = debugDataOf(*_switchStmt.expression); - YulString type = m_typeInfo.typeOf(*_switchStmt.expression); + YulName type = m_typeInfo.typeOf(*_switchStmt.expression); if (switchCase.value) { if (!m_dialect.equalityFunction(type)) diff --git a/libyul/optimiser/DataFlowAnalyzer.cpp b/libyul/optimiser/DataFlowAnalyzer.cpp index 5ec3cf248df9..a51ca912399d 100644 --- a/libyul/optimiser/DataFlowAnalyzer.cpp +++ b/libyul/optimiser/DataFlowAnalyzer.cpp @@ -45,22 +45,22 @@ using namespace solidity::yul; DataFlowAnalyzer::DataFlowAnalyzer( Dialect const& _dialect, MemoryAndStorage _analyzeStores, - std::map _functionSideEffects + std::map _functionSideEffects ): m_dialect(_dialect), m_functionSideEffects(std::move(_functionSideEffects)), - m_knowledgeBase([this](YulString _var) { return variableValue(_var); }), + m_knowledgeBase([this](YulName _var) { return variableValue(_var); }), m_analyzeStores(_analyzeStores == MemoryAndStorage::Analyze) { if (m_analyzeStores) { - if (auto const* builtin = _dialect.memoryStoreFunction(YulString{})) + if (auto const* builtin = _dialect.memoryStoreFunction(YulName{})) m_storeFunctionName[static_cast(StoreLoadLocation::Memory)] = builtin->name; - if (auto const* builtin = _dialect.memoryLoadFunction(YulString{})) + if (auto const* builtin = _dialect.memoryLoadFunction(YulName{})) m_loadFunctionName[static_cast(StoreLoadLocation::Memory)] = builtin->name; - if (auto const* builtin = _dialect.storageStoreFunction(YulString{})) + if (auto const* builtin = _dialect.storageStoreFunction(YulName{})) m_storeFunctionName[static_cast(StoreLoadLocation::Storage)] = builtin->name; - if (auto const* builtin = _dialect.storageLoadFunction(YulString{})) + if (auto const* builtin = _dialect.storageLoadFunction(YulName{})) m_loadFunctionName[static_cast(StoreLoadLocation::Storage)] = builtin->name; } } @@ -98,7 +98,7 @@ void DataFlowAnalyzer::operator()(ExpressionStatement& _statement) void DataFlowAnalyzer::operator()(Assignment& _assignment) { - std::set names; + std::set names; for (auto const& var: _assignment.variableNames) names.emplace(var.name); assertThrow(_assignment.value, OptimizerException, ""); @@ -109,7 +109,7 @@ void DataFlowAnalyzer::operator()(Assignment& _assignment) void DataFlowAnalyzer::operator()(VariableDeclaration& _varDecl) { - std::set names; + std::set names; for (auto const& var: _varDecl.variables) names.emplace(var.name); m_variableScopes.back().variables += names; @@ -138,14 +138,14 @@ void DataFlowAnalyzer::operator()(Switch& _switch) { clearKnowledgeIfInvalidated(*_switch.expression); visit(*_switch.expression); - std::set assignedVariables; + std::set assignedVariables; for (auto& _case: _switch.cases) { Environment preEnvironment = m_state.environment; (*this)(_case.body); joinKnowledge(preEnvironment); - std::set variables = assignedVariableNames(_case.body); + std::set variables = assignedVariableNames(_case.body); assignedVariables += variables; // This is a little too destructive, we could retain the old values. clearValues(variables); @@ -191,7 +191,7 @@ void DataFlowAnalyzer::operator()(ForLoop& _for) AssignmentsSinceContinue assignmentsSinceCont; assignmentsSinceCont(_for.body); - std::set assignedVariables = + std::set assignedVariables = assignedVariableNames(_for.body) + assignedVariableNames(_for.post); clearValues(assignedVariables); @@ -222,31 +222,31 @@ void DataFlowAnalyzer::operator()(Block& _block) assertThrow(numScopes == m_variableScopes.size(), OptimizerException, ""); } -std::optional DataFlowAnalyzer::storageValue(YulString _key) const +std::optional DataFlowAnalyzer::storageValue(YulName _key) const { - if (YulString const* value = valueOrNullptr(m_state.environment.storage, _key)) + if (YulName const* value = valueOrNullptr(m_state.environment.storage, _key)) return *value; else return std::nullopt; } -std::optional DataFlowAnalyzer::memoryValue(YulString _key) const +std::optional DataFlowAnalyzer::memoryValue(YulName _key) const { - if (YulString const* value = valueOrNullptr(m_state.environment.memory, _key)) + if (YulName const* value = valueOrNullptr(m_state.environment.memory, _key)) return *value; else return std::nullopt; } -std::optional DataFlowAnalyzer::keccakValue(YulString _start, YulString _length) const +std::optional DataFlowAnalyzer::keccakValue(YulName _start, YulName _length) const { - if (YulString const* value = valueOrNullptr(m_state.environment.keccak, std::make_pair(_start, _length))) + if (YulName const* value = valueOrNullptr(m_state.environment.keccak, std::make_pair(_start, _length))) return *value; else return std::nullopt; } -void DataFlowAnalyzer::handleAssignment(std::set const& _variables, Expression* _value, bool _isDeclaration) +void DataFlowAnalyzer::handleAssignment(std::set const& _variables, Expression* _value, bool _isDeclaration) { if (!_isDeclaration) clearValues(_variables); @@ -260,7 +260,7 @@ void DataFlowAnalyzer::handleAssignment(std::set const& _variables, E if (_value && _variables.size() == 1) { - YulString name = *_variables.begin(); + YulName name = *_variables.begin(); // Expression has to be movable and cannot contain a reference // to the variable that will be assigned to. if (movableChecker.movable() && !movableChecker.referencedVariables().count(name)) @@ -289,7 +289,7 @@ void DataFlowAnalyzer::handleAssignment(std::set const& _variables, E if (_value && _variables.size() == 1) { - YulString variable = *_variables.begin(); + YulName variable = *_variables.begin(); if (!movableChecker.referencedVariables().count(variable)) { // This might erase additional knowledge about the slot. @@ -320,7 +320,7 @@ void DataFlowAnalyzer::popScope() m_variableScopes.pop_back(); } -void DataFlowAnalyzer::clearValues(std::set _variables) +void DataFlowAnalyzer::clearValues(std::set _variables) { // All variables that reference variables to be cleared also have to be // cleared, but not recursively, since only the value of the original @@ -351,7 +351,7 @@ void DataFlowAnalyzer::clearValues(std::set _variables) }); // Also clear variables that reference variables to be cleared. - std::set referencingVariables; + std::set referencingVariables; for (auto const& variableToClear: _variables) for (auto const& [ref, names]: m_state.references) if (names.count(variableToClear)) @@ -365,7 +365,7 @@ void DataFlowAnalyzer::clearValues(std::set _variables) } } -void DataFlowAnalyzer::assignValue(YulString _variable, Expression const* _value) +void DataFlowAnalyzer::assignValue(YulName _variable, Expression const* _value) { m_state.value[_variable] = {_value, m_loopDepth}; } @@ -398,7 +398,7 @@ void DataFlowAnalyzer::clearKnowledgeIfInvalidated(Expression const& _expr) } } -bool DataFlowAnalyzer::inScope(YulString _variableName) const +bool DataFlowAnalyzer::inScope(YulName _variableName) const { for (auto const& scope: m_variableScopes | ranges::views::reverse) { @@ -410,7 +410,7 @@ bool DataFlowAnalyzer::inScope(YulString _variableName) const return false; } -std::optional DataFlowAnalyzer::valueOfIdentifier(YulString const& _name) const +std::optional DataFlowAnalyzer::valueOfIdentifier(YulName const& _name) const { if (AssignedValue const* value = variableValue(_name)) if (Literal const* literal = std::get_if(value->value)) @@ -418,7 +418,7 @@ std::optional DataFlowAnalyzer::valueOfIdentifier(YulString const& _name) return std::nullopt; } -std::optional> DataFlowAnalyzer::isSimpleStore( +std::optional> DataFlowAnalyzer::isSimpleStore( StoreLoadLocation _location, ExpressionStatement const& _statement ) const @@ -431,7 +431,7 @@ std::optional> DataFlowAnalyzer::isSimpleStore( return {}; } -std::optional DataFlowAnalyzer::isSimpleLoad( +std::optional DataFlowAnalyzer::isSimpleLoad( StoreLoadLocation _location, Expression const& _expression ) const @@ -443,7 +443,7 @@ std::optional DataFlowAnalyzer::isSimpleLoad( return {}; } -std::optional> DataFlowAnalyzer::isKeccak(Expression const& _expression) const +std::optional> DataFlowAnalyzer::isKeccak(Expression const& _expression) const { if (FunctionCall const* funCall = std::get_if(&_expression)) if (funCall->functionName.name == m_dialect.hashFunction({})) @@ -460,14 +460,14 @@ void DataFlowAnalyzer::joinKnowledge(Environment const& _olderEnvironment) joinKnowledgeHelper(m_state.environment.storage, _olderEnvironment.storage); joinKnowledgeHelper(m_state.environment.memory, _olderEnvironment.memory); cxx20::erase_if(m_state.environment.keccak, mapTuple([&_olderEnvironment](auto&& key, auto&& currentValue) { - YulString const* oldValue = valueOrNullptr(_olderEnvironment.keccak, key); + YulName const* oldValue = valueOrNullptr(_olderEnvironment.keccak, key); return !oldValue || *oldValue != currentValue; })); } void DataFlowAnalyzer::joinKnowledgeHelper( - std::unordered_map& _this, - std::unordered_map const& _older + std::unordered_map& _this, + std::unordered_map const& _older ) { // We clear if the key does not exist in the older map or if the value is different. @@ -475,7 +475,7 @@ void DataFlowAnalyzer::joinKnowledgeHelper( // of m_state.environment.memory and thus any overlapping write would have cleared the keys // that are not known to be different inside m_state.environment.memory already. cxx20::erase_if(_this, mapTuple([&_older](auto&& key, auto&& currentValue){ - YulString const* oldValue = valueOrNullptr(_older, key); + YulName const* oldValue = valueOrNullptr(_older, key); return !oldValue || *oldValue != currentValue; })); } diff --git a/libyul/optimiser/DataFlowAnalyzer.h b/libyul/optimiser/DataFlowAnalyzer.h index e41620b15f27..6b23a86b9c9d 100644 --- a/libyul/optimiser/DataFlowAnalyzer.h +++ b/libyul/optimiser/DataFlowAnalyzer.h @@ -25,7 +25,7 @@ #include #include -#include +#include #include // Needed for m_zero below. #include @@ -89,7 +89,7 @@ class DataFlowAnalyzer: public ASTModifier explicit DataFlowAnalyzer( Dialect const& _dialect, MemoryAndStorage _analyzeStores, - std::map _functionSideEffects = {} + std::map _functionSideEffects = {} ); using ASTModifier::operator(); @@ -103,16 +103,16 @@ class DataFlowAnalyzer: public ASTModifier void operator()(Block& _block) override; /// @returns the current value of the given variable, if known - always movable. - AssignedValue const* variableValue(YulString _variable) const { return util::valueOrNullptr(m_state.value, _variable); } - std::set const* references(YulString _variable) const { return util::valueOrNullptr(m_state.references, _variable); } - std::map const& allValues() const { return m_state.value; } - std::optional storageValue(YulString _key) const; - std::optional memoryValue(YulString _key) const; - std::optional keccakValue(YulString _start, YulString _length) const; + AssignedValue const* variableValue(YulName _variable) const { return util::valueOrNullptr(m_state.value, _variable); } + std::set const* references(YulName _variable) const { return util::valueOrNullptr(m_state.references, _variable); } + std::map const& allValues() const { return m_state.value; } + std::optional storageValue(YulName _key) const; + std::optional memoryValue(YulName _key) const; + std::optional keccakValue(YulName _start, YulName _length) const; protected: /// Registers the assignment. - void handleAssignment(std::set const& _names, Expression* _value, bool _isDeclaration); + void handleAssignment(std::set const& _names, Expression* _value, bool _isDeclaration); /// Creates a new inner scope. void pushScope(bool _functionScope); @@ -122,9 +122,9 @@ class DataFlowAnalyzer: public ASTModifier /// Clears information about the values assigned to the given variables, /// for example at points where control flow is merged. - void clearValues(std::set _names); + void clearValues(std::set _names); - virtual void assignValue(YulString _variable, Expression const* _value); + virtual void assignValue(YulName _variable, Expression const* _value); /// Clears knowledge about storage or memory if they may be modified inside the block. void clearKnowledgeIfInvalidated(Block const& _block); @@ -133,10 +133,10 @@ class DataFlowAnalyzer: public ASTModifier void clearKnowledgeIfInvalidated(Expression const& _expression); /// Returns true iff the variable is in scope. - bool inScope(YulString _variableName) const; + bool inScope(YulName _variableName) const; /// Returns the literal value of the identifier, if it exists. - std::optional valueOfIdentifier(YulString const& _name) const; + std::optional valueOfIdentifier(YulName const& _name) const; enum class StoreLoadLocation { Memory = 0, @@ -146,41 +146,41 @@ class DataFlowAnalyzer: public ASTModifier /// Checks if the statement is sstore(a, b) / mstore(a, b) /// where a and b are variables and returns these variables in that case. - std::optional> isSimpleStore( + std::optional> isSimpleStore( StoreLoadLocation _location, ExpressionStatement const& _statement ) const; /// Checks if the expression is sload(a) / mload(a) /// where a is a variable and returns the variable in that case. - std::optional isSimpleLoad( + std::optional isSimpleLoad( StoreLoadLocation _location, Expression const& _expression ) const; /// Checks if the expression is keccak256(s, l) /// where s and l are variables and returns these variables in that case. - std::optional> isKeccak(Expression const& _expression) const; + std::optional> isKeccak(Expression const& _expression) const; Dialect const& m_dialect; /// Side-effects of user-defined functions. Worst-case side-effects are assumed /// if this is not provided or the function is not found. - std::map m_functionSideEffects; + std::map m_functionSideEffects; private: struct Environment { - std::unordered_map storage; - std::unordered_map memory; + std::unordered_map storage; + std::unordered_map memory; /// If keccak[s, l] = y then y := keccak256(s, l) occurs in the code. - std::map, YulString> keccak; + std::map, YulName> keccak; }; struct State { /// Current values of variables, always movable. - std::map value; + std::map value; /// m_references[a].contains(b) <=> the current expression assigned to a references b - std::unordered_map> references; + std::unordered_map> references; Environment environment; }; @@ -192,8 +192,8 @@ class DataFlowAnalyzer: public ASTModifier void joinKnowledge(Environment const& _olderEnvironment); static void joinKnowledgeHelper( - std::unordered_map& _thisData, - std::unordered_map const& _olderData + std::unordered_map& _thisData, + std::unordered_map const& _olderData ); State m_state; @@ -203,8 +203,8 @@ class DataFlowAnalyzer: public ASTModifier /// If true, analyzes memory and storage content via mload/mstore and sload/sstore. bool m_analyzeStores = true; - YulString m_storeFunctionName[static_cast(StoreLoadLocation::Last) + 1]; - YulString m_loadFunctionName[static_cast(StoreLoadLocation::Last) + 1]; + YulName m_storeFunctionName[static_cast(StoreLoadLocation::Last) + 1]; + YulName m_loadFunctionName[static_cast(StoreLoadLocation::Last) + 1]; /// Current nesting depth of loops. size_t m_loopDepth{0}; @@ -212,11 +212,11 @@ class DataFlowAnalyzer: public ASTModifier struct Scope { explicit Scope(bool _isFunction): isFunction(_isFunction) {} - std::set variables; + std::set variables; bool isFunction; }; /// Special expression whose address will be used in m_value. - /// YulString does not need to be reset because DataFlowAnalyzer is short-lived. + /// YulName does not need to be reset because DataFlowAnalyzer is short-lived. Expression const m_zero{Literal{{}, LiteralKind::Number, LiteralValue{0, "0"}, {}}}; /// List of scopes. std::vector m_variableScopes; diff --git a/libyul/optimiser/DeadCodeEliminator.h b/libyul/optimiser/DeadCodeEliminator.h index ae8c1b2a6a4a..f252536c599e 100644 --- a/libyul/optimiser/DeadCodeEliminator.h +++ b/libyul/optimiser/DeadCodeEliminator.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include #include @@ -62,11 +62,11 @@ class DeadCodeEliminator: public ASTModifier private: DeadCodeEliminator( Dialect const& _dialect, - std::map _sideEffects + std::map _sideEffects ): m_dialect(_dialect), m_functionSideEffects(std::move(_sideEffects)) {} Dialect const& m_dialect; - std::map m_functionSideEffects; + std::map m_functionSideEffects; }; } diff --git a/libyul/optimiser/Disambiguator.cpp b/libyul/optimiser/Disambiguator.cpp index 34e6bc7e6a9b..11325936c7c6 100644 --- a/libyul/optimiser/Disambiguator.cpp +++ b/libyul/optimiser/Disambiguator.cpp @@ -30,7 +30,7 @@ using namespace solidity; using namespace solidity::yul; using namespace solidity::util; -YulString Disambiguator::translateIdentifier(YulString _originalName) +YulName Disambiguator::translateIdentifier(YulName _originalName) { if (m_dialect.builtin(_originalName) || m_externallyUsedIdentifiers.count(_originalName)) return _originalName; diff --git a/libyul/optimiser/Disambiguator.h b/libyul/optimiser/Disambiguator.h index 062173882761..08d8d158f699 100644 --- a/libyul/optimiser/Disambiguator.h +++ b/libyul/optimiser/Disambiguator.h @@ -42,7 +42,7 @@ class Disambiguator: public ASTCopier explicit Disambiguator( Dialect const& _dialect, AsmAnalysisInfo const& _analysisInfo, - std::set const& _externallyUsedIdentifiers = {} + std::set const& _externallyUsedIdentifiers = {} ): m_info(_analysisInfo), m_dialect(_dialect), @@ -56,17 +56,17 @@ class Disambiguator: public ASTCopier void leaveScope(Block const& _block) override; void enterFunction(FunctionDefinition const& _function) override; void leaveFunction(FunctionDefinition const& _function) override; - YulString translateIdentifier(YulString _name) override; + YulName translateIdentifier(YulName _name) override; void enterScopeInternal(Scope& _scope); void leaveScopeInternal(Scope& _scope); AsmAnalysisInfo const& m_info; Dialect const& m_dialect; - std::set const& m_externallyUsedIdentifiers; + std::set const& m_externallyUsedIdentifiers; std::vector m_scopes; - std::map m_translations; + std::map m_translations; NameDispenser m_nameDispenser; }; diff --git a/libyul/optimiser/EqualStoreEliminator.cpp b/libyul/optimiser/EqualStoreEliminator.cpp index 1e894608e9f9..0d7ff9e9c5a4 100644 --- a/libyul/optimiser/EqualStoreEliminator.cpp +++ b/libyul/optimiser/EqualStoreEliminator.cpp @@ -53,13 +53,13 @@ void EqualStoreEliminator::visit(Statement& _statement) { if (auto vars = isSimpleStore(StoreLoadLocation::Storage, *expression)) { - if (std::optional currentValue = storageValue(vars->first)) + if (std::optional currentValue = storageValue(vars->first)) if (*currentValue == vars->second) m_pendingRemovals.insert(&_statement); } else if (auto vars = isSimpleStore(StoreLoadLocation::Memory, *expression)) { - if (std::optional currentValue = memoryValue(vars->first)) + if (std::optional currentValue = memoryValue(vars->first)) if (*currentValue == vars->second) m_pendingRemovals.insert(&_statement); } diff --git a/libyul/optimiser/EqualStoreEliminator.h b/libyul/optimiser/EqualStoreEliminator.h index b8572f4667fd..a0b54c590ff5 100644 --- a/libyul/optimiser/EqualStoreEliminator.h +++ b/libyul/optimiser/EqualStoreEliminator.h @@ -45,7 +45,7 @@ class EqualStoreEliminator: public DataFlowAnalyzer private: EqualStoreEliminator( Dialect const& _dialect, - std::map _functionSideEffects + std::map _functionSideEffects ): DataFlowAnalyzer(_dialect, MemoryAndStorage::Analyze, std::move(_functionSideEffects)) {} diff --git a/libyul/optimiser/EquivalentFunctionCombiner.h b/libyul/optimiser/EquivalentFunctionCombiner.h index 5337f76842d6..627dcb3ff4fd 100644 --- a/libyul/optimiser/EquivalentFunctionCombiner.h +++ b/libyul/optimiser/EquivalentFunctionCombiner.h @@ -46,8 +46,8 @@ class EquivalentFunctionCombiner: public ASTModifier void operator()(FunctionCall& _funCall) override; private: - EquivalentFunctionCombiner(std::map _duplicates): m_duplicates(std::move(_duplicates)) {} - std::map m_duplicates; + EquivalentFunctionCombiner(std::map _duplicates): m_duplicates(std::move(_duplicates)) {} + std::map m_duplicates; }; diff --git a/libyul/optimiser/EquivalentFunctionDetector.h b/libyul/optimiser/EquivalentFunctionDetector.h index d3ddc25f7bdb..7cd161af1a45 100644 --- a/libyul/optimiser/EquivalentFunctionDetector.h +++ b/libyul/optimiser/EquivalentFunctionDetector.h @@ -35,7 +35,7 @@ namespace solidity::yul class EquivalentFunctionDetector: public ASTWalker { public: - static std::map run(Block& _block) + static std::map run(Block& _block) { EquivalentFunctionDetector detector{BlockHasher::run(_block)}; detector(_block); @@ -50,7 +50,7 @@ class EquivalentFunctionDetector: public ASTWalker std::map m_blockHashes; std::map> m_candidates; - std::map m_duplicates; + std::map m_duplicates; }; diff --git a/libyul/optimiser/ExpressionInliner.cpp b/libyul/optimiser/ExpressionInliner.cpp index cacf5843d6b3..ab4bbcfa43a8 100644 --- a/libyul/optimiser/ExpressionInliner.cpp +++ b/libyul/optimiser/ExpressionInliner.cpp @@ -56,11 +56,11 @@ void ExpressionInliner::visit(Expression& _expression) return; FunctionDefinition const& fun = *m_inlinableFunctions.at(funCall.functionName.name); - std::map substitutions; + std::map substitutions; for (size_t i = 0; i < funCall.arguments.size(); i++) { Expression const& arg = funCall.arguments[i]; - YulString paraName = fun.parameters[i].name; + YulName paraName = fun.parameters[i].name; if (!SideEffectsCollector(m_dialect, arg).movable()) return; diff --git a/libyul/optimiser/ExpressionInliner.h b/libyul/optimiser/ExpressionInliner.h index ff7da67b8832..08ff08648428 100644 --- a/libyul/optimiser/ExpressionInliner.h +++ b/libyul/optimiser/ExpressionInliner.h @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -59,16 +60,16 @@ class ExpressionInliner: public ASTModifier private: ExpressionInliner( Dialect const& _dialect, - std::map const& _inlinableFunctions + std::map const& _inlinableFunctions ): m_dialect(_dialect), m_inlinableFunctions(_inlinableFunctions) {} Dialect const& m_dialect; - std::map const& m_inlinableFunctions; + std::map const& m_inlinableFunctions; - std::map m_varReplacements; + std::map m_varReplacements; /// Set of functions we are currently visiting inside. - std::set m_currentFunctions; + std::set m_currentFunctions; }; } diff --git a/libyul/optimiser/ExpressionJoiner.h b/libyul/optimiser/ExpressionJoiner.h index 3a1fdf743579..07f86ddce73a 100644 --- a/libyul/optimiser/ExpressionJoiner.h +++ b/libyul/optimiser/ExpressionJoiner.h @@ -93,7 +93,7 @@ class ExpressionJoiner: public ASTModifier private: Block* m_currentBlock = nullptr; ///< Pointer to current block holding the statement being visited. size_t m_latestStatementInBlock = 0; ///< Offset to m_currentBlock's statements of the last visited statement. - std::map m_references; ///< Holds reference counts to all variable declarations in current block. + std::map m_references; ///< Holds reference counts to all variable declarations in current block. }; } diff --git a/libyul/optimiser/ExpressionSimplifier.cpp b/libyul/optimiser/ExpressionSimplifier.cpp index 6d0a8c9d7409..482ade8f87d5 100644 --- a/libyul/optimiser/ExpressionSimplifier.cpp +++ b/libyul/optimiser/ExpressionSimplifier.cpp @@ -44,7 +44,7 @@ void ExpressionSimplifier::visit(Expression& _expression) while (auto const* match = SimplificationRules::findFirstMatch( _expression, m_dialect, - [this](YulString _var) { return variableValue(_var); } + [this](YulName _var) { return variableValue(_var); } )) _expression = match->action().toExpression(debugDataOf(_expression), evmVersionFromDialect(m_dialect)); diff --git a/libyul/optimiser/ExpressionSplitter.cpp b/libyul/optimiser/ExpressionSplitter.cpp index 6f0834d7760e..acaa40dbf0e1 100644 --- a/libyul/optimiser/ExpressionSplitter.cpp +++ b/libyul/optimiser/ExpressionSplitter.cpp @@ -99,8 +99,8 @@ void ExpressionSplitter::outlineExpression(Expression& _expr) visit(_expr); langutil::DebugData::ConstPtr debugData = debugDataOf(_expr); - YulString var = m_nameDispenser.newName({}); - YulString type = m_typeInfo.typeOf(_expr); + YulName var = m_nameDispenser.newName({}); + YulName type = m_typeInfo.typeOf(_expr); m_statementsToPrefix.emplace_back(VariableDeclaration{ debugData, {{TypedName{debugData, var, type}}}, diff --git a/libyul/optimiser/ForLoopConditionOutOfBody.cpp b/libyul/optimiser/ForLoopConditionOutOfBody.cpp index 83b1e20a8e33..afd005b719d5 100644 --- a/libyul/optimiser/ForLoopConditionOutOfBody.cpp +++ b/libyul/optimiser/ForLoopConditionOutOfBody.cpp @@ -53,7 +53,7 @@ void ForLoopConditionOutOfBody::operator()(ForLoop& _forLoop) if (!SideEffectsCollector(m_dialect, *firstStatement.condition).movable()) return; - YulString iszero = m_dialect.booleanNegationFunction()->name; + YulName iszero = m_dialect.booleanNegationFunction()->name; langutil::DebugData::ConstPtr debugData = debugDataOf(*firstStatement.condition); if ( diff --git a/libyul/optimiser/FullInliner.cpp b/libyul/optimiser/FullInliner.cpp index 3bf00282c04b..5cdde8f0fdd5 100644 --- a/libyul/optimiser/FullInliner.cpp +++ b/libyul/optimiser/FullInliner.cpp @@ -66,8 +66,8 @@ FullInliner::FullInliner(Block& _ast, NameDispenser& _dispenser, Dialect const& m_constants.emplace(ssaValue.first); // Store size of global statements. - m_functionSizes[YulString{}] = CodeSize::codeSize(_ast); - std::map references = ReferencesCounter::countReferences(m_ast); + m_functionSizes[YulName{}] = CodeSize::codeSize(_ast); + std::map references = ReferencesCounter::countReferences(m_ast); for (auto& statement: m_ast.statements) { if (!std::holds_alternative(statement)) @@ -83,10 +83,7 @@ FullInliner::FullInliner(Block& _ast, NameDispenser& _dispenser, Dialect const& } // Check for memory guard. - std::vector memoryGuardCalls = findFunctionCalls( - _ast, - "memoryguard"_yulstring - ); + std::vector memoryGuardCalls = findFunctionCalls(_ast, "memoryguard"_yulname); // We will perform less aggressive inlining, if no ``memoryguard`` call is found. if (!memoryGuardCalls.empty()) m_hasMemoryGuard = true; @@ -104,7 +101,7 @@ void FullInliner::run(Pass _pass) // function name) order. // We use stable_sort below to keep the inlining order of two functions // with the same depth. - std::map depths = callDepths(); + std::map depths = callDepths(); std::vector functions; for (auto& statement: m_ast.statements) if (std::holds_alternative(statement)) @@ -126,10 +123,10 @@ void FullInliner::run(Pass _pass) handleBlock({}, std::get(statement)); } -std::map FullInliner::callDepths() const +std::map FullInliner::callDepths() const { CallGraph cg = CallGraphGenerator::callGraph(m_ast); - cg.functionCalls.erase(""_yulstring); + cg.functionCalls.erase(""_yulname); // Remove calls to builtin functions. for (auto& call: cg.functionCalls) @@ -139,12 +136,12 @@ std::map FullInliner::callDepths() const else ++it; - std::map depths; + std::map depths; size_t currentDepth = 0; while (true) { - std::vector removed; + std::vector removed; for (auto it = cg.functionCalls.begin(); it != cg.functionCalls.end();) { auto const& [fun, callees] = *it; @@ -159,7 +156,7 @@ std::map FullInliner::callDepths() const } for (auto& call: cg.functionCalls) - for (YulString toBeRemoved: removed) + for (YulName toBeRemoved: removed) ranges::actions::remove(call.second, toBeRemoved); currentDepth++; @@ -175,7 +172,7 @@ std::map FullInliner::callDepths() const return depths; } -bool FullInliner::shallInline(FunctionCall const& _funCall, YulString _callSite) +bool FullInliner::shallInline(FunctionCall const& _funCall, YulName _callSite) { // No recursive inlining if (_funCall.functionName.name == _callSite) @@ -237,7 +234,7 @@ bool FullInliner::shallInline(FunctionCall const& _funCall, YulString _callSite) return (size < (aggressiveInlining ? 8u : 6u) || (constantArg && size < (aggressiveInlining ? 16u : 12u))); } -void FullInliner::tentativelyUpdateCodeSize(YulString _function, YulString _callSite) +void FullInliner::tentativelyUpdateCodeSize(YulName _function, YulName _callSite) { m_functionSizes.at(_callSite) += m_functionSizes.at(_function); } @@ -247,14 +244,14 @@ void FullInliner::updateCodeSize(FunctionDefinition const& _fun) m_functionSizes[_fun.name] = CodeSize::codeSize(_fun.body); } -void FullInliner::handleBlock(YulString _currentFunctionName, Block& _block) +void FullInliner::handleBlock(YulName _currentFunctionName, Block& _block) { InlineModifier{*this, m_nameDispenser, _currentFunctionName, m_dialect}(_block); } bool FullInliner::recursive(FunctionDefinition const& _fun) const { - std::map references = ReferencesCounter::countReferences(_fun); + std::map references = ReferencesCounter::countReferences(_fun); return references[_fun.name] > 0; } @@ -292,7 +289,7 @@ std::optional> InlineModifier::tryInlineStatement(Stateme std::vector InlineModifier::performInline(Statement& _statement, FunctionCall& _funCall) { std::vector newStatements; - std::map variableReplacements; + std::map variableReplacements; FunctionDefinition* function = m_driver.function(_funCall.functionName.name); assertThrow(!!function, OptimizerException, "Attempt to inline invalid function."); @@ -302,7 +299,7 @@ std::vector InlineModifier::performInline(Statement& _statement, Func // helper function to create a new variable that is supposed to model // an existing variable. auto newVariable = [&](TypedName const& _existingVariable, Expression* _value) { - YulString newName = m_nameDispenser.newName(_existingVariable.name); + YulName newName = m_nameDispenser.newName(_existingVariable.name); variableReplacements[_existingVariable.name] = newName; VariableDeclaration varDecl{_funCall.debugData, {{_funCall.debugData, newName, _existingVariable.type}}, {}}; if (_value) @@ -364,7 +361,7 @@ Statement BodyCopier::operator()(FunctionDefinition const&) return {}; } -YulString BodyCopier::translateIdentifier(YulString _name) +YulName BodyCopier::translateIdentifier(YulName _name) { if (m_variableReplacements.count(_name)) return m_variableReplacements.at(_name); diff --git a/libyul/optimiser/FullInliner.h b/libyul/optimiser/FullInliner.h index 931315305c57..e939070238e5 100644 --- a/libyul/optimiser/FullInliner.h +++ b/libyul/optimiser/FullInliner.h @@ -75,9 +75,9 @@ class FullInliner: public ASTModifier /// Inlining heuristic. /// @param _callSite the name of the function in which the function call is located. - bool shallInline(FunctionCall const& _funCall, YulString _callSite); + bool shallInline(FunctionCall const& _funCall, YulName _callSite); - FunctionDefinition* function(YulString _name) + FunctionDefinition* function(YulName _name) { auto it = m_functions.find(_name); if (it != m_functions.end()) @@ -88,7 +88,7 @@ class FullInliner: public ASTModifier /// Adds the size of _funCall to the size of _callSite. This is just /// a rough estimate that is done during inlining. The proper size /// should be determined after inlining is completed. - void tentativelyUpdateCodeSize(YulString _function, YulString _callSite); + void tentativelyUpdateCodeSize(YulName _function, YulName _callSite); private: enum Pass { InlineTiny, InlineRest }; @@ -98,28 +98,28 @@ class FullInliner: public ASTModifier /// @returns a map containing the maximum depths of a call chain starting at each /// function. For recursive functions, the value is one larger than for all others. - std::map callDepths() const; + std::map callDepths() const; void updateCodeSize(FunctionDefinition const& _fun); - void handleBlock(YulString _currentFunctionName, Block& _block); + void handleBlock(YulName _currentFunctionName, Block& _block); bool recursive(FunctionDefinition const& _fun) const; Pass m_pass; /// The AST to be modified. The root block itself will not be modified, because /// we store pointers to functions. Block& m_ast; - std::map m_functions; + std::map m_functions; /// Functions not to be inlined (because they contain the ``leave`` statement). - std::set m_noInlineFunctions; + std::set m_noInlineFunctions; /// True, if the code contains a ``memoryguard`` and we can expect to be able to move variables to memory later. bool m_hasMemoryGuard = false; /// Set of recursive functions. - std::set m_recursiveFunctions; + std::set m_recursiveFunctions; /// Names of functions to always inline. - std::set m_singleUse; + std::set m_singleUse; /// Variables that are constants (used for inlining heuristic) - std::set m_constants; - std::map m_functionSizes; + std::set m_constants; + std::map m_functionSizes; NameDispenser& m_nameDispenser; Dialect const& m_dialect; }; @@ -131,7 +131,7 @@ class FullInliner: public ASTModifier class InlineModifier: public ASTModifier { public: - InlineModifier(FullInliner& _driver, NameDispenser& _nameDispenser, YulString _functionName, Dialect const& _dialect): + InlineModifier(FullInliner& _driver, NameDispenser& _nameDispenser, YulName _functionName, Dialect const& _dialect): m_currentFunction(std::move(_functionName)), m_driver(_driver), m_nameDispenser(_nameDispenser), @@ -144,7 +144,7 @@ class InlineModifier: public ASTModifier std::optional> tryInlineStatement(Statement& _statement); std::vector performInline(Statement& _statement, FunctionCall& _funCall); - YulString m_currentFunction; + YulName m_currentFunction; FullInliner& m_driver; NameDispenser& m_nameDispenser; Dialect const& m_dialect; @@ -160,7 +160,7 @@ class BodyCopier: public ASTCopier public: BodyCopier( NameDispenser& _nameDispenser, - std::map _variableReplacements + std::map _variableReplacements ): m_nameDispenser(_nameDispenser), m_variableReplacements(std::move(_variableReplacements)) @@ -171,10 +171,10 @@ class BodyCopier: public ASTCopier Statement operator()(VariableDeclaration const& _varDecl) override; Statement operator()(FunctionDefinition const& _funDef) override; - YulString translateIdentifier(YulString _name) override; + YulName translateIdentifier(YulName _name) override; NameDispenser& m_nameDispenser; - std::map m_variableReplacements; + std::map m_variableReplacements; }; diff --git a/libyul/optimiser/FunctionCallFinder.cpp b/libyul/optimiser/FunctionCallFinder.cpp index 99f171026e9e..aaf8b9f68232 100644 --- a/libyul/optimiser/FunctionCallFinder.cpp +++ b/libyul/optimiser/FunctionCallFinder.cpp @@ -30,14 +30,14 @@ class MaybeConstFunctionCallFinder: Base { public: using MaybeConstBlock = std::conditional_t, Block const, Block>; - static std::vector run(MaybeConstBlock& _block, YulString const _functionName) + static std::vector run(MaybeConstBlock& _block, YulName const _functionName) { MaybeConstFunctionCallFinder functionCallFinder(_functionName); functionCallFinder(_block); return functionCallFinder.m_calls; } private: - explicit MaybeConstFunctionCallFinder(YulString const _functionName): m_functionName(_functionName), m_calls() {} + explicit MaybeConstFunctionCallFinder(YulName const _functionName): m_functionName(_functionName), m_calls() {} using Base::operator(); void operator()(ResultType& _functionCall) override { @@ -45,17 +45,17 @@ class MaybeConstFunctionCallFinder: Base if (_functionCall.functionName.name == m_functionName) m_calls.emplace_back(&_functionCall); } - YulString m_functionName; + YulName m_functionName; std::vector m_calls; }; } -std::vector solidity::yul::findFunctionCalls(Block& _block, YulString _functionName) +std::vector solidity::yul::findFunctionCalls(Block& _block, YulName _functionName) { return MaybeConstFunctionCallFinder::run(_block, _functionName); } -std::vector solidity::yul::findFunctionCalls(Block const& _block, YulString _functionName) +std::vector solidity::yul::findFunctionCalls(Block const& _block, YulName _functionName) { return MaybeConstFunctionCallFinder::run(_block, _functionName); } diff --git a/libyul/optimiser/FunctionCallFinder.h b/libyul/optimiser/FunctionCallFinder.h index a5d4da56e916..41a19fe99fc7 100644 --- a/libyul/optimiser/FunctionCallFinder.h +++ b/libyul/optimiser/FunctionCallFinder.h @@ -21,7 +21,7 @@ #pragma once #include -#include +#include #include @@ -33,13 +33,13 @@ namespace solidity::yul * * Prerequisite: Disambiguator */ -std::vector findFunctionCalls(Block& _block, YulString _functionName); +std::vector findFunctionCalls(Block& _block, YulName _functionName); /** * Finds all calls to a function of a given name using an ASTWalker. * * Prerequisite: Disambiguator */ -std::vector findFunctionCalls(Block const& _block, YulString _functionName); +std::vector findFunctionCalls(Block const& _block, YulName _functionName); } diff --git a/libyul/optimiser/FunctionSpecializer.cpp b/libyul/optimiser/FunctionSpecializer.cpp index 7e6d486327ea..49da50032dfe 100644 --- a/libyul/optimiser/FunctionSpecializer.cpp +++ b/libyul/optimiser/FunctionSpecializer.cpp @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include @@ -64,7 +64,7 @@ void FunctionSpecializer::operator()(FunctionCall& _f) if (ranges::any_of(arguments, [](auto& _a) { return _a.has_value(); })) { - YulString oldName = std::move(_f.functionName.name); + YulName oldName = std::move(_f.functionName.name); auto newName = m_nameDispenser.newName(oldName); m_oldToNewMap[oldName].emplace_back(std::make_pair(newName, arguments)); @@ -79,19 +79,19 @@ void FunctionSpecializer::operator()(FunctionCall& _f) FunctionDefinition FunctionSpecializer::specialize( FunctionDefinition const& _f, - YulString _newName, + YulName _newName, FunctionSpecializer::LiteralArguments _arguments ) { yulAssert(_arguments.size() == _f.parameters.size(), ""); - std::map translatedNames = applyMap( + std::map translatedNames = applyMap( NameCollector{_f, NameCollector::OnlyVariables}.names(), - [&](auto& _name) -> std::pair + [&](auto& _name) -> std::pair { return std::make_pair(_name, m_nameDispenser.newName(_name)); }, - std::map{} + std::map{} ); FunctionDefinition newFunction = std::get(FunctionCopier{translatedNames}(_f)); diff --git a/libyul/optimiser/FunctionSpecializer.h b/libyul/optimiser/FunctionSpecializer.h index b922ece8b09f..784ec4311e0f 100644 --- a/libyul/optimiser/FunctionSpecializer.h +++ b/libyul/optimiser/FunctionSpecializer.h @@ -67,7 +67,7 @@ class FunctionSpecializer: public ASTModifier private: explicit FunctionSpecializer( - std::set _recursiveFunctions, + std::set _recursiveFunctions, NameDispenser& _nameDispenser, Dialect const& _dialect ): @@ -96,15 +96,15 @@ class FunctionSpecializer: public ASTModifier /// FunctionDefinition specialize( FunctionDefinition const& _f, - YulString _newName, + YulName _newName, FunctionSpecializer::LiteralArguments _arguments ); /// A mapping between the old function name and a pair of new function name and its arguments. /// Note that at least one of the argument will have a literal value. - std::map>> m_oldToNewMap; + std::map>> m_oldToNewMap; /// We skip specializing recursive functions. Need backtracking to properly deal with them. - std::set const m_recursiveFunctions; + std::set const m_recursiveFunctions; NameDispenser& m_nameDispenser; Dialect const& m_dialect; diff --git a/libyul/optimiser/InlinableExpressionFunctionFinder.cpp b/libyul/optimiser/InlinableExpressionFunctionFinder.cpp index 0bb4d368d841..d719302dcbc2 100644 --- a/libyul/optimiser/InlinableExpressionFunctionFinder.cpp +++ b/libyul/optimiser/InlinableExpressionFunctionFinder.cpp @@ -43,7 +43,7 @@ void InlinableExpressionFunctionFinder::operator()(FunctionDefinition const& _fu { if (_function.returnVariables.size() == 1 && _function.body.statements.size() == 1) { - YulString retVariable = _function.returnVariables.front().name; + YulName retVariable = _function.returnVariables.front().name; Statement const& bodyStatement = _function.body.statements.front(); if (std::holds_alternative(bodyStatement)) { @@ -56,7 +56,7 @@ void InlinableExpressionFunctionFinder::operator()(FunctionDefinition const& _fu // would not be valid here if we were searching inside a functionally inlinable // function body. assertThrow(m_disallowedIdentifiers.empty() && !m_foundDisallowedIdentifier, OptimizerException, ""); - m_disallowedIdentifiers = std::set{retVariable, _function.name}; + m_disallowedIdentifiers = std::set{retVariable, _function.name}; std::visit(*this, *assignment.value); if (!m_foundDisallowedIdentifier) m_inlinableFunctions[_function.name] = &_function; diff --git a/libyul/optimiser/InlinableExpressionFunctionFinder.h b/libyul/optimiser/InlinableExpressionFunctionFinder.h index 587bdca91172..e7210da69a0a 100644 --- a/libyul/optimiser/InlinableExpressionFunctionFinder.h +++ b/libyul/optimiser/InlinableExpressionFunctionFinder.h @@ -42,7 +42,7 @@ class InlinableExpressionFunctionFinder: public ASTWalker { public: - std::map const& inlinableFunctions() const + std::map const& inlinableFunctions() const { return m_inlinableFunctions; } @@ -53,15 +53,15 @@ class InlinableExpressionFunctionFinder: public ASTWalker void operator()(FunctionDefinition const& _function) override; private: - void checkAllowed(YulString _name) + void checkAllowed(YulName _name) { if (m_disallowedIdentifiers.count(_name)) m_foundDisallowedIdentifier = true; } bool m_foundDisallowedIdentifier = false; - std::set m_disallowedIdentifiers; - std::map m_inlinableFunctions; + std::set m_disallowedIdentifiers; + std::map m_inlinableFunctions; }; } diff --git a/libyul/optimiser/KnowledgeBase.cpp b/libyul/optimiser/KnowledgeBase.cpp index 79eb2b317940..731f4b3b8195 100644 --- a/libyul/optimiser/KnowledgeBase.cpp +++ b/libyul/optimiser/KnowledgeBase.cpp @@ -32,19 +32,19 @@ using namespace solidity; using namespace solidity::yul; -KnowledgeBase::KnowledgeBase(std::map const& _ssaValues): +KnowledgeBase::KnowledgeBase(std::map const& _ssaValues): m_valuesAreSSA(true), - m_variableValues([_ssaValues](YulString _var) { return util::valueOrNullptr(_ssaValues, _var); }) + m_variableValues([_ssaValues](YulName _var) { return util::valueOrNullptr(_ssaValues, _var); }) {} -bool KnowledgeBase::knownToBeDifferent(YulString _a, YulString _b) +bool KnowledgeBase::knownToBeDifferent(YulName _a, YulName _b) { if (std::optional difference = differenceIfKnownConstant(_a, _b)) return difference != 0; return false; } -std::optional KnowledgeBase::differenceIfKnownConstant(YulString _a, YulString _b) +std::optional KnowledgeBase::differenceIfKnownConstant(YulName _a, YulName _b) { VariableOffset offA = explore(_a); VariableOffset offB = explore(_b); @@ -55,7 +55,7 @@ std::optional KnowledgeBase::differenceIfKnownConstant(YulString _a, YulSt } -bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulString _a, YulString _b) +bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulName _a, YulName _b) { if (std::optional difference = differenceIfKnownConstant(_a, _b)) return difference >= 32 && difference <= u256(0) - 32; @@ -63,12 +63,12 @@ bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulString _a, YulString _b) return false; } -bool KnowledgeBase::knownToBeZero(YulString _a) +bool KnowledgeBase::knownToBeZero(YulName _a) { return valueIfKnownConstant(_a) == 0; } -std::optional KnowledgeBase::valueIfKnownConstant(YulString _a) +std::optional KnowledgeBase::valueIfKnownConstant(YulName _a) { return explore(_a).absoluteValue(); } @@ -83,7 +83,7 @@ std::optional KnowledgeBase::valueIfKnownConstant(Expression const& _expre return std::nullopt; } -KnowledgeBase::VariableOffset KnowledgeBase::explore(YulString _var) +KnowledgeBase::VariableOffset KnowledgeBase::explore(YulName _var) { Expression const* value = nullptr; if (m_valuesAreSSA) @@ -113,12 +113,12 @@ KnowledgeBase::VariableOffset KnowledgeBase::explore(YulString _var) std::optional KnowledgeBase::explore(Expression const& _value) { if (Literal const* literal = std::get_if(&_value)) - return VariableOffset{YulString{}, literal->value.value()}; + return VariableOffset{YulName{}, literal->value.value()}; else if (Identifier const* identifier = std::get_if(&_value)) return explore(identifier->name); else if (FunctionCall const* f = std::get_if(&_value)) { - if (f->functionName.name == "add"_yulstring) + if (f->functionName.name == "add"_yulname) { if (std::optional a = explore(f->arguments[0])) if (std::optional b = explore(f->arguments[1])) @@ -132,13 +132,13 @@ std::optional KnowledgeBase::explore(Expression c return VariableOffset{a->reference, offset}; } } - else if (f->functionName.name == "sub"_yulstring) + else if (f->functionName.name == "sub"_yulname) if (std::optional a = explore(f->arguments[0])) if (std::optional b = explore(f->arguments[1])) { u256 offset = a->offset - b->offset; if (a->reference == b->reference) - return VariableOffset{YulString{}, offset}; + return VariableOffset{YulName{}, offset}; else if (b->isAbsolute()) // b is constant return VariableOffset{a->reference, offset}; @@ -148,7 +148,7 @@ std::optional KnowledgeBase::explore(Expression c return std::nullopt; } -Expression const* KnowledgeBase::valueOf(YulString _var) +Expression const* KnowledgeBase::valueOf(YulName _var) { AssignedValue const* assignedValue = m_variableValues(_var); Expression const* currentValue = assignedValue ? assignedValue->value : nullptr; @@ -162,7 +162,7 @@ Expression const* KnowledgeBase::valueOf(YulString _var) return currentValue; } -void KnowledgeBase::reset(YulString _var) +void KnowledgeBase::reset(YulName _var) { yulAssert(!m_valuesAreSSA); @@ -174,16 +174,16 @@ void KnowledgeBase::reset(YulString _var) m_groupMembers[offset->reference].erase(_var); m_offsets.erase(_var); } - if (std::set* group = util::valueOrNullptr(m_groupMembers, _var)) + if (std::set* group = util::valueOrNullptr(m_groupMembers, _var)) { // _var was a representative, we might have to find a new one. if (!group->empty()) { - YulString newRepresentative = *group->begin(); + YulName newRepresentative = *group->begin(); yulAssert(newRepresentative != _var); u256 newOffset = m_offsets[newRepresentative].offset; // newOffset = newRepresentative - _var - for (YulString groupMember: *group) + for (YulName groupMember: *group) { yulAssert(m_offsets[groupMember].reference == _var); m_offsets[groupMember].reference = newRepresentative; @@ -200,7 +200,7 @@ void KnowledgeBase::reset(YulString _var) } } -KnowledgeBase::VariableOffset KnowledgeBase::setOffset(YulString _variable, VariableOffset _value) +KnowledgeBase::VariableOffset KnowledgeBase::setOffset(YulName _variable, VariableOffset _value) { m_offsets[_variable] = _value; // Constants are not tracked in m_groupMembers because diff --git a/libyul/optimiser/KnowledgeBase.h b/libyul/optimiser/KnowledgeBase.h index f83c5ac66105..46ea7b96af66 100644 --- a/libyul/optimiser/KnowledgeBase.h +++ b/libyul/optimiser/KnowledgeBase.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include #include @@ -55,34 +55,34 @@ struct AssignedValue; * representative variable of the group. * * There is a special group which is the constant values. Those use the - * empty YulString as representative "variable". + * empty YulName as representative "variable". */ class KnowledgeBase { public: /// Constructor for arbitrary value callback that allows for variable values /// to change in between calls to functions of this class. - explicit KnowledgeBase(std::function _variableValues): + explicit KnowledgeBase(std::function _variableValues): m_variableValues(std::move(_variableValues)) {} /// Constructor to use if source code is in SSA form and values are constant. - explicit KnowledgeBase(std::map const& _ssaValues); + explicit KnowledgeBase(std::map const& _ssaValues); - bool knownToBeDifferent(YulString _a, YulString _b); - std::optional differenceIfKnownConstant(YulString _a, YulString _b); - bool knownToBeDifferentByAtLeast32(YulString _a, YulString _b); - bool knownToBeZero(YulString _a); - std::optional valueIfKnownConstant(YulString _a); + bool knownToBeDifferent(YulName _a, YulName _b); + std::optional differenceIfKnownConstant(YulName _a, YulName _b); + bool knownToBeDifferentByAtLeast32(YulName _a, YulName _b); + bool knownToBeZero(YulName _a); + std::optional valueIfKnownConstant(YulName _a); std::optional valueIfKnownConstant(Expression const& _expression); private: /** * Constant offset relative to a reference variable, or absolute constant if the - * reference variable is the empty YulString. + * reference variable is the empty YulName. */ struct VariableOffset { - YulString reference; + YulName reference; u256 offset; bool isAbsolute() const @@ -99,30 +99,30 @@ class KnowledgeBase } }; - VariableOffset explore(YulString _var); + VariableOffset explore(YulName _var); std::optional explore(Expression const& _value); /// Retrieves the current value of a variable and potentially resets the variable if it is not up to date. - Expression const* valueOf(YulString _var); + Expression const* valueOf(YulName _var); /// Resets all information about the variable and removes it from its group, /// potentially finding a new representative. - void reset(YulString _var); + void reset(YulName _var); - VariableOffset setOffset(YulString _variable, VariableOffset _value); + VariableOffset setOffset(YulName _variable, VariableOffset _value); /// If true, we can assume that variable values never change and skip some steps. bool m_valuesAreSSA = false; /// Callback to retrieve the current value of a variable. - std::function m_variableValues; + std::function m_variableValues; /// Offsets for each variable to one representative per group. /// The empty string is the representative of the constant value zero. - std::map m_offsets; + std::map m_offsets; /// Last known value of each variable we queried. - std::map m_lastKnownValue; + std::map m_lastKnownValue; /// For each representative, variables that use it to offset from. - std::map> m_groupMembers; + std::map> m_groupMembers; }; } diff --git a/libyul/optimiser/LoadResolver.cpp b/libyul/optimiser/LoadResolver.cpp index 170eefc902b5..a7ee5dd0b92c 100644 --- a/libyul/optimiser/LoadResolver.cpp +++ b/libyul/optimiser/LoadResolver.cpp @@ -87,7 +87,7 @@ void LoadResolver::tryResolve( if (_arguments.empty() || !std::holds_alternative(_arguments.at(0))) return; - YulString key = std::get(_arguments.at(0)).name; + YulName key = std::get(_arguments.at(0)).name; if (_location == StoreLoadLocation::Storage) { if (auto value = storageValue(key)) @@ -137,7 +137,7 @@ void LoadResolver::tryEvaluateKeccak( if (costOfLiteral > costOfKeccak) return; - std::optional value = memoryValue(memoryKey->name); + std::optional value = memoryValue(memoryKey->name); if (value && inScope(*value)) { std::optional memoryContent = valueOfIdentifier(*value); diff --git a/libyul/optimiser/LoadResolver.h b/libyul/optimiser/LoadResolver.h index e56bc6c4a206..b4a496303373 100644 --- a/libyul/optimiser/LoadResolver.h +++ b/libyul/optimiser/LoadResolver.h @@ -49,7 +49,7 @@ class LoadResolver: public DataFlowAnalyzer private: LoadResolver( Dialect const& _dialect, - std::map _functionSideEffects, + std::map _functionSideEffects, bool _containsMSize, std::optional _expectedExecutionsPerDeployment ): diff --git a/libyul/optimiser/LoopInvariantCodeMotion.cpp b/libyul/optimiser/LoopInvariantCodeMotion.cpp index da3c5e3e0a5a..2a196a68f956 100644 --- a/libyul/optimiser/LoopInvariantCodeMotion.cpp +++ b/libyul/optimiser/LoopInvariantCodeMotion.cpp @@ -32,10 +32,10 @@ using namespace solidity::yul; void LoopInvariantCodeMotion::run(OptimiserStepContext& _context, Block& _ast) { - std::map functionSideEffects = + std::map functionSideEffects = SideEffectsPropagator::sideEffects(_context.dialect, CallGraphGenerator::callGraph(_ast)); bool containsMSize = MSizeFinder::containsMSize(_context.dialect, _ast); - std::set ssaVars = SSAValueTracker::ssaVariables(_ast); + std::set ssaVars = SSAValueTracker::ssaVariables(_ast); LoopInvariantCodeMotion{_context.dialect, ssaVars, functionSideEffects, containsMSize}(_ast); } @@ -56,7 +56,7 @@ void LoopInvariantCodeMotion::operator()(Block& _block) bool LoopInvariantCodeMotion::canBePromoted( VariableDeclaration const& _varDecl, - std::set const& _varsDefinedInCurrentScope, + std::set const& _varsDefinedInCurrentScope, SideEffects const& _forLoopSideEffects ) const { @@ -90,7 +90,7 @@ std::optional> LoopInvariantCodeMotion::rewriteLoop(ForLo std::vector replacement; for (Block* block: {&_for.post, &_for.body}) { - std::set varsDefinedInScope; + std::set varsDefinedInScope; util::iterateReplacing( block->statements, [&](Statement& _s) -> std::optional> diff --git a/libyul/optimiser/LoopInvariantCodeMotion.h b/libyul/optimiser/LoopInvariantCodeMotion.h index 1b264792470c..c85b87a01c32 100644 --- a/libyul/optimiser/LoopInvariantCodeMotion.h +++ b/libyul/optimiser/LoopInvariantCodeMotion.h @@ -48,8 +48,8 @@ class LoopInvariantCodeMotion: public ASTModifier private: explicit LoopInvariantCodeMotion( Dialect const& _dialect, - std::set const& _ssaVariables, - std::map const& _functionSideEffects, + std::set const& _ssaVariables, + std::map const& _functionSideEffects, bool _containsMSize ): m_containsMSize(_containsMSize), @@ -61,15 +61,15 @@ class LoopInvariantCodeMotion: public ASTModifier /// @returns true if the given variable declaration can be moved to in front of the loop. bool canBePromoted( VariableDeclaration const& _varDecl, - std::set const& _varsDefinedInCurrentScope, + std::set const& _varsDefinedInCurrentScope, SideEffects const& _forLoopSideEffects ) const; std::optional> rewriteLoop(ForLoop& _for); bool m_containsMSize = true; Dialect const& m_dialect; - std::set const& m_ssaVariables; - std::map const& m_functionSideEffects; + std::set const& m_ssaVariables; + std::map const& m_functionSideEffects; }; } diff --git a/libyul/optimiser/Metrics.cpp b/libyul/optimiser/Metrics.cpp index 2f1dee93eabe..546c465b5c43 100644 --- a/libyul/optimiser/Metrics.cpp +++ b/libyul/optimiser/Metrics.cpp @@ -199,7 +199,7 @@ void AssignmentCounter::operator()(Assignment const& _assignment) ++m_assignmentCounters[variable.name]; } -size_t AssignmentCounter::assignmentCount(YulString _name) const +size_t AssignmentCounter::assignmentCount(YulName _name) const { auto it = m_assignmentCounters.find(_name); return (it == m_assignmentCounters.end()) ? 0 : it->second; diff --git a/libyul/optimiser/Metrics.h b/libyul/optimiser/Metrics.h index f86e3b28dfad..01ab1adbd7e3 100644 --- a/libyul/optimiser/Metrics.h +++ b/libyul/optimiser/Metrics.h @@ -139,9 +139,9 @@ class AssignmentCounter: public ASTWalker public: using ASTWalker::operator(); void operator()(Assignment const& _assignment) override; - std::size_t assignmentCount(YulString _name) const; + std::size_t assignmentCount(YulName _name) const; private: - std::map m_assignmentCounters; + std::map m_assignmentCounters; }; } diff --git a/libyul/optimiser/NameCollector.cpp b/libyul/optimiser/NameCollector.cpp index 7fb0c7ed28e9..d6db837f8485 100644 --- a/libyul/optimiser/NameCollector.cpp +++ b/libyul/optimiser/NameCollector.cpp @@ -59,21 +59,21 @@ void ReferencesCounter::operator()(FunctionCall const& _funCall) ASTWalker::operator()(_funCall); } -std::map ReferencesCounter::countReferences(Block const& _block) +std::map ReferencesCounter::countReferences(Block const& _block) { ReferencesCounter counter; counter(_block); return std::move(counter.m_references); } -std::map ReferencesCounter::countReferences(FunctionDefinition const& _function) +std::map ReferencesCounter::countReferences(FunctionDefinition const& _function) { ReferencesCounter counter; counter(_function); return std::move(counter.m_references); } -std::map ReferencesCounter::countReferences(Expression const& _expression) +std::map ReferencesCounter::countReferences(Expression const& _expression) { ReferencesCounter counter; counter.visit(_expression); @@ -85,28 +85,28 @@ void VariableReferencesCounter::operator()(Identifier const& _identifier) ++m_references[_identifier.name]; } -std::map VariableReferencesCounter::countReferences(Block const& _block) +std::map VariableReferencesCounter::countReferences(Block const& _block) { VariableReferencesCounter counter; counter(_block); return std::move(counter.m_references); } -std::map VariableReferencesCounter::countReferences(FunctionDefinition const& _function) +std::map VariableReferencesCounter::countReferences(FunctionDefinition const& _function) { VariableReferencesCounter counter; counter(_function); return std::move(counter.m_references); } -std::map VariableReferencesCounter::countReferences(Expression const& _expression) +std::map VariableReferencesCounter::countReferences(Expression const& _expression) { VariableReferencesCounter counter; counter.visit(_expression); return std::move(counter.m_references); } -std::map VariableReferencesCounter::countReferences(Statement const& _statement) +std::map VariableReferencesCounter::countReferences(Statement const& _statement) { VariableReferencesCounter counter; counter.visit(_statement); @@ -138,9 +138,9 @@ void AssignmentsSinceContinue::operator()(FunctionDefinition const&) yulAssert(false, ""); } -std::set solidity::yul::assignedVariableNames(Block const& _code) +std::set solidity::yul::assignedVariableNames(Block const& _code) { - std::set names; + std::set names; forEach(_code, [&](Assignment const& _assignment) { for (auto const& var: _assignment.variableNames) names.emplace(var.name); @@ -148,9 +148,9 @@ std::set solidity::yul::assignedVariableNames(Block const& _code) return names; } -std::map solidity::yul::allFunctionDefinitions(Block const& _block) +std::map solidity::yul::allFunctionDefinitions(Block const& _block) { - std::map result; + std::map result; forEach(_block, [&](FunctionDefinition const& _function) { result[_function.name] = &_function; }); diff --git a/libyul/optimiser/NameCollector.h b/libyul/optimiser/NameCollector.h index ad18e1e26bb3..0fc2e311ca50 100644 --- a/libyul/optimiser/NameCollector.h +++ b/libyul/optimiser/NameCollector.h @@ -22,6 +22,7 @@ #pragma once #include +#include #include #include @@ -59,9 +60,9 @@ class NameCollector: public ASTWalker void operator()(VariableDeclaration const& _varDecl) override; void operator()(FunctionDefinition const& _funDef) override; - std::set names() const { return m_names; } + std::set names() const { return m_names; } private: - std::set m_names; + std::set m_names; CollectWhat m_collectWhat = VariablesAndFunctions; }; @@ -75,12 +76,12 @@ class ReferencesCounter: public ASTWalker void operator()(Identifier const& _identifier) override; void operator()(FunctionCall const& _funCall) override; - static std::map countReferences(Block const& _block); - static std::map countReferences(FunctionDefinition const& _function); - static std::map countReferences(Expression const& _expression); + static std::map countReferences(Block const& _block); + static std::map countReferences(FunctionDefinition const& _function); + static std::map countReferences(Expression const& _expression); private: - std::map m_references; + std::map m_references; }; /** @@ -92,13 +93,13 @@ class VariableReferencesCounter: public ASTWalker using ASTWalker::operator (); void operator()(Identifier const& _identifier) override; - static std::map countReferences(Block const& _block); - static std::map countReferences(FunctionDefinition const& _function); - static std::map countReferences(Expression const& _expression); - static std::map countReferences(Statement const& _statement); + static std::map countReferences(Block const& _block); + static std::map countReferences(FunctionDefinition const& _function); + static std::map countReferences(Expression const& _expression); + static std::map countReferences(Statement const& _statement); private: - std::map m_references; + std::map m_references; }; /** @@ -117,21 +118,21 @@ class AssignmentsSinceContinue: public ASTWalker void operator()(Assignment const& _assignment) override; void operator()(FunctionDefinition const& _funDef) override; - std::set const& names() const { return m_names; } + std::set const& names() const { return m_names; } bool empty() const noexcept { return m_names.empty(); } private: size_t m_forLoopDepth = 0; bool m_continueFound = false; - std::set m_names; + std::set m_names; }; /// @returns the names of all variables that are assigned to inside @a _code. /// (ignores variable declarations) -std::set assignedVariableNames(Block const& _code); +std::set assignedVariableNames(Block const& _code); /// @returns all function definitions anywhere in the AST. /// Requires disambiguated source. -std::map allFunctionDefinitions(Block const& _block); +std::map allFunctionDefinitions(Block const& _block); } diff --git a/libyul/optimiser/NameDispenser.cpp b/libyul/optimiser/NameDispenser.cpp index 3a8db5ee449e..c2b6b9847f3c 100644 --- a/libyul/optimiser/NameDispenser.cpp +++ b/libyul/optimiser/NameDispenser.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include @@ -33,31 +32,31 @@ using namespace solidity; using namespace solidity::yul; using namespace solidity::util; -NameDispenser::NameDispenser(Dialect const& _dialect, Block const& _ast, std::set _reservedNames): +NameDispenser::NameDispenser(Dialect const& _dialect, Block const& _ast, std::set _reservedNames): NameDispenser(_dialect, NameCollector(_ast).names() + _reservedNames) { m_reservedNames = std::move(_reservedNames); } -NameDispenser::NameDispenser(Dialect const& _dialect, std::set _usedNames): +NameDispenser::NameDispenser(Dialect const& _dialect, std::set _usedNames): m_dialect(_dialect), m_usedNames(std::move(_usedNames)) { } -YulString NameDispenser::newName(YulString _nameHint) +YulName NameDispenser::newName(YulName _nameHint) { - YulString name = _nameHint; + YulName name = _nameHint; while (illegalName(name)) { m_counter++; - name = YulString(_nameHint.str() + "_" + std::to_string(m_counter)); + name = YulName(_nameHint.str() + "_" + std::to_string(m_counter)); } m_usedNames.emplace(name); return name; } -bool NameDispenser::illegalName(YulString _name) +bool NameDispenser::illegalName(YulName _name) { return isRestrictedIdentifier(m_dialect, _name) || m_usedNames.count(_name); } diff --git a/libyul/optimiser/NameDispenser.h b/libyul/optimiser/NameDispenser.h index 6e655e416b51..3da50359a764 100644 --- a/libyul/optimiser/NameDispenser.h +++ b/libyul/optimiser/NameDispenser.h @@ -22,7 +22,7 @@ #include -#include +#include #include @@ -40,21 +40,21 @@ class NameDispenser { public: /// Initialize the name dispenser with all the names used in the given AST. - explicit NameDispenser(Dialect const& _dialect, Block const& _ast, std::set _reservedNames = {}); + explicit NameDispenser(Dialect const& _dialect, Block const& _ast, std::set _reservedNames = {}); /// Initialize the name dispenser with the given used names. - explicit NameDispenser(Dialect const& _dialect, std::set _usedNames); + explicit NameDispenser(Dialect const& _dialect, std::set _usedNames); /// @returns a currently unused name that should be similar to _nameHint. - YulString newName(YulString _nameHint); + YulName newName(YulName _nameHint); /// Mark @a _name as used, i.e. the dispenser's newName function will not /// return it. - void markUsed(YulString _name) { m_usedNames.insert(_name); } + void markUsed(YulName _name) { m_usedNames.insert(_name); } - std::set const& usedNames() { return m_usedNames; } + std::set const& usedNames() { return m_usedNames; } /// Returns true if `_name` is either used or is a restricted identifier. - bool illegalName(YulString _name); + bool illegalName(YulName _name); /// Resets `m_usedNames` with *only* the names that are used in the AST. Also resets value of /// `m_counter` to zero. @@ -62,8 +62,8 @@ class NameDispenser private: Dialect const& m_dialect; - std::set m_usedNames; - std::set m_reservedNames; + std::set m_usedNames; + std::set m_reservedNames; size_t m_counter = 0; }; diff --git a/libyul/optimiser/NameDisplacer.cpp b/libyul/optimiser/NameDisplacer.cpp index 4d0d217d8619..fd813fbfc2f1 100644 --- a/libyul/optimiser/NameDisplacer.cpp +++ b/libyul/optimiser/NameDisplacer.cpp @@ -69,14 +69,14 @@ void NameDisplacer::operator()(Block& _block) ASTModifier::operator()(_block); } -void NameDisplacer::checkAndReplaceNew(YulString& _name) +void NameDisplacer::checkAndReplaceNew(YulName& _name) { yulAssert(!m_translations.count(_name), ""); if (m_namesToFree.count(_name)) _name = (m_translations[_name] = m_nameDispenser.newName(_name)); } -void NameDisplacer::checkAndReplace(YulString& _name) const +void NameDisplacer::checkAndReplace(YulName& _name) const { if (m_translations.count(_name)) _name = m_translations.at(_name); diff --git a/libyul/optimiser/NameDisplacer.h b/libyul/optimiser/NameDisplacer.h index 336dd04e42de..3312e203d7ae 100644 --- a/libyul/optimiser/NameDisplacer.h +++ b/libyul/optimiser/NameDisplacer.h @@ -44,12 +44,12 @@ class NameDisplacer: public ASTModifier public: explicit NameDisplacer( NameDispenser& _dispenser, - std::set const& _namesToFree + std::set const& _namesToFree ): m_nameDispenser(_dispenser), m_namesToFree(_namesToFree) { - for (YulString n: _namesToFree) + for (YulName n: _namesToFree) m_nameDispenser.markUsed(n); } @@ -60,17 +60,17 @@ class NameDisplacer: public ASTModifier void operator()(FunctionCall& _funCall) override; void operator()(Block& _block) override; - std::map const& translations() const { return m_translations; } + std::map const& translations() const { return m_translations; } protected: /// Check if the newly introduced identifier @a _name has to be replaced. - void checkAndReplaceNew(YulString& _name); + void checkAndReplaceNew(YulName& _name); /// Replace the identifier @a _name if it is in the translation map. - void checkAndReplace(YulString& _name) const; + void checkAndReplace(YulName& _name) const; NameDispenser& m_nameDispenser; - std::set const& m_namesToFree; - std::map m_translations; + std::set const& m_namesToFree; + std::map m_translations; }; } diff --git a/libyul/optimiser/NameSimplifier.cpp b/libyul/optimiser/NameSimplifier.cpp index f7d732547773..f03a448f0d92 100644 --- a/libyul/optimiser/NameSimplifier.cpp +++ b/libyul/optimiser/NameSimplifier.cpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include @@ -32,10 +32,10 @@ using namespace solidity::yul; NameSimplifier::NameSimplifier(OptimiserStepContext& _context, Block const& _ast): m_context(_context) { - for (YulString name: _context.reservedIdentifiers) + for (YulName name: _context.reservedIdentifiers) m_translations[name] = name; - for (YulString const& name: NameCollector(_ast).names()) + for (YulName const& name: NameCollector(_ast).names()) findSimplification(name); } @@ -72,7 +72,7 @@ void NameSimplifier::operator()(FunctionCall& _funCall) ASTModifier::operator()(_funCall); } -void NameSimplifier::findSimplification(YulString const& _name) +void NameSimplifier::findSimplification(YulName const& _name) { if (m_translations.count(_name)) return; @@ -102,19 +102,19 @@ void NameSimplifier::findSimplification(YulString const& _name) for (auto const& [pattern, substitute]: replacements) { std::string candidate = regex_replace(name, pattern, substitute); - if (!candidate.empty() && !m_context.dispenser.illegalName(YulString(candidate))) + if (!candidate.empty() && !m_context.dispenser.illegalName(YulName(candidate))) name = candidate; } if (name != _name.str()) { - YulString newName{name}; + YulName newName{name}; m_context.dispenser.markUsed(newName); m_translations[_name] = std::move(newName); } } -void NameSimplifier::translate(YulString& _name) +void NameSimplifier::translate(YulName& _name) { auto it = m_translations.find(_name); if (it != m_translations.end()) diff --git a/libyul/optimiser/NameSimplifier.h b/libyul/optimiser/NameSimplifier.h index 34cf6945115b..848e61f567ac 100644 --- a/libyul/optimiser/NameSimplifier.h +++ b/libyul/optimiser/NameSimplifier.h @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include @@ -62,11 +62,11 @@ class NameSimplifier: public ASTModifier /// Tries to rename a list of variables. void renameVariables(std::vector& _variables); - void findSimplification(YulString const& _name); - void translate(YulString& _name); + void findSimplification(YulName const& _name); + void translate(YulName& _name); OptimiserStepContext& m_context; - std::map m_translations; + std::map m_translations; }; } diff --git a/libyul/optimiser/OptimiserStep.h b/libyul/optimiser/OptimiserStep.h index e3e5fe4c605d..89bfcef814d0 100644 --- a/libyul/optimiser/OptimiserStep.h +++ b/libyul/optimiser/OptimiserStep.h @@ -29,14 +29,13 @@ namespace solidity::yul struct Dialect; struct Block; -class YulString; class NameDispenser; struct OptimiserStepContext { Dialect const& dialect; NameDispenser& dispenser; - std::set const& reservedIdentifiers; + std::set const& reservedIdentifiers; /// The value nullopt represents creation code std::optional expectedExecutionsPerDeployment; }; diff --git a/libyul/optimiser/OptimizerUtilities.cpp b/libyul/optimiser/OptimizerUtilities.cpp index bfa3d888f19b..19f262060fc0 100644 --- a/libyul/optimiser/OptimizerUtilities.cpp +++ b/libyul/optimiser/OptimizerUtilities.cpp @@ -55,12 +55,12 @@ void yul::removeEmptyBlocks(Block& _block) ranges::actions::remove_if(_block.statements, isEmptyBlock); } -bool yul::isRestrictedIdentifier(Dialect const& _dialect, YulString const& _identifier) +bool yul::isRestrictedIdentifier(Dialect const& _dialect, YulName const& _identifier) { return _identifier.empty() || hasLeadingOrTrailingDot(_identifier.str()) || TokenTraits::isYulKeyword(_identifier.str()) || _dialect.reservedIdentifier(_identifier); } -std::optional yul::toEVMInstruction(Dialect const& _dialect, YulString const& _name) +std::optional yul::toEVMInstruction(Dialect const& _dialect, YulName const& _name) { if (auto const* dialect = dynamic_cast(&_dialect)) if (BuiltinFunctionForEVM const* builtin = dialect->builtin(_name)) diff --git a/libyul/optimiser/OptimizerUtilities.h b/libyul/optimiser/OptimizerUtilities.h index cb07f7a53006..911a1be0a812 100644 --- a/libyul/optimiser/OptimizerUtilities.h +++ b/libyul/optimiser/OptimizerUtilities.h @@ -24,7 +24,7 @@ #include #include #include -#include +#include #include #include @@ -45,10 +45,10 @@ void removeEmptyBlocks(Block& _block); /// Returns true if a given literal can not be used as an identifier. /// This includes Yul keywords and builtins of the given dialect. -bool isRestrictedIdentifier(Dialect const& _dialect, YulString const& _identifier); +bool isRestrictedIdentifier(Dialect const& _dialect, YulName const& _identifier); /// Helper function that returns the instruction, if the `_name` is a BuiltinFunction -std::optional toEVMInstruction(Dialect const& _dialect, YulString const& _name); +std::optional toEVMInstruction(Dialect const& _dialect, YulName const& _name); /// Helper function that returns the EVM version from a dialect. /// It returns the default EVM version if dialect is not an EVMDialect. diff --git a/libyul/optimiser/Rematerialiser.cpp b/libyul/optimiser/Rematerialiser.cpp index db6920f2439b..fe33b10a2245 100644 --- a/libyul/optimiser/Rematerialiser.cpp +++ b/libyul/optimiser/Rematerialiser.cpp @@ -31,7 +31,7 @@ using namespace solidity; using namespace solidity::yul; -void Rematerialiser::run(Dialect const& _dialect, Block& _ast, std::set _varsToAlwaysRematerialize, bool _onlySelectedVariables) +void Rematerialiser::run(Dialect const& _dialect, Block& _ast, std::set _varsToAlwaysRematerialize, bool _onlySelectedVariables) { Rematerialiser{_dialect, _ast, std::move(_varsToAlwaysRematerialize), _onlySelectedVariables}(_ast); } @@ -39,7 +39,7 @@ void Rematerialiser::run(Dialect const& _dialect, Block& _ast, std::set _varsToAlwaysRematerialize, + std::set _varsToAlwaysRematerialize, bool _onlySelectedVariables ): DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore), @@ -54,7 +54,7 @@ void Rematerialiser::visit(Expression& _e) if (std::holds_alternative(_e)) { Identifier& identifier = std::get(_e); - YulString name = identifier.name; + YulName name = identifier.name; if (AssignedValue const* value = variableValue(name)) { assertThrow(value->value, OptimizerException, ""); @@ -93,7 +93,7 @@ void LiteralRematerialiser::visit(Expression& _e) if (std::holds_alternative(_e)) { Identifier& identifier = std::get(_e); - YulString name = identifier.name; + YulName name = identifier.name; if (AssignedValue const* value = variableValue(name)) { assertThrow(value->value, OptimizerException, ""); diff --git a/libyul/optimiser/Rematerialiser.h b/libyul/optimiser/Rematerialiser.h index 9ee5209fdfeb..a482ef53e015 100644 --- a/libyul/optimiser/Rematerialiser.h +++ b/libyul/optimiser/Rematerialiser.h @@ -50,7 +50,7 @@ class Rematerialiser: public DataFlowAnalyzer static void run( Dialect const& _dialect, Block& _ast, - std::set _varsToAlwaysRematerialize = {}, + std::set _varsToAlwaysRematerialize = {}, bool _onlySelectedVariables = false ); @@ -58,7 +58,7 @@ class Rematerialiser: public DataFlowAnalyzer Rematerialiser( Dialect const& _dialect, Block& _ast, - std::set _varsToAlwaysRematerialize = {}, + std::set _varsToAlwaysRematerialize = {}, bool _onlySelectedVariables = false ); @@ -67,8 +67,8 @@ class Rematerialiser: public DataFlowAnalyzer using ASTModifier::visit; void visit(Expression& _e) override; - std::map m_referenceCounts; - std::set m_varsToAlwaysRematerialize; + std::map m_referenceCounts; + std::set m_varsToAlwaysRematerialize; bool m_onlySelectedVariables = false; }; diff --git a/libyul/optimiser/SSATransform.cpp b/libyul/optimiser/SSATransform.cpp index dba2f6f04610..80abdf7e6516 100644 --- a/libyul/optimiser/SSATransform.cpp +++ b/libyul/optimiser/SSATransform.cpp @@ -46,7 +46,7 @@ class IntroduceSSA: public ASTModifier public: explicit IntroduceSSA( NameDispenser& _nameDispenser, - std::set const& _variablesToReplace, + std::set const& _variablesToReplace, TypeInfo& _typeInfo ): m_nameDispenser(_nameDispenser), @@ -58,7 +58,7 @@ class IntroduceSSA: public ASTModifier private: NameDispenser& m_nameDispenser; - std::set const& m_variablesToReplace; + std::set const& m_variablesToReplace; TypeInfo const& m_typeInfo; }; @@ -90,8 +90,8 @@ void IntroduceSSA::operator()(Block& _block) TypedNameList newVariables; for (auto const& var: varDecl.variables) { - YulString oldName = var.name; - YulString newName = m_nameDispenser.newName(oldName); + YulName oldName = var.name; + YulName newName = m_nameDispenser.newName(oldName); newVariables.emplace_back(TypedName{debugData, newName, var.type}); statements.emplace_back(VariableDeclaration{ debugData, @@ -117,8 +117,8 @@ void IntroduceSSA::operator()(Block& _block) TypedNameList newVariables; for (auto const& var: assignment.variableNames) { - YulString oldName = var.name; - YulString newName = m_nameDispenser.newName(oldName); + YulName oldName = var.name; + YulName newName = m_nameDispenser.newName(oldName); newVariables.emplace_back(TypedName{debugData, newName, m_typeInfo.typeOfVariable(oldName) @@ -148,7 +148,7 @@ class IntroduceControlFlowSSA: public ASTModifier public: explicit IntroduceControlFlowSSA( NameDispenser& _nameDispenser, - std::set const& _variablesToReplace, + std::set const& _variablesToReplace, TypeInfo const& _typeInfo ): m_nameDispenser(_nameDispenser), @@ -163,19 +163,19 @@ class IntroduceControlFlowSSA: public ASTModifier private: NameDispenser& m_nameDispenser; - std::set const& m_variablesToReplace; + std::set const& m_variablesToReplace; /// Variables (that are to be replaced) currently in scope. - std::set m_variablesInScope; + std::set m_variablesInScope; /// Variables that do not have a specific value. - util::UniqueVector m_variablesToReassign; + util::UniqueVector m_variablesToReassign; TypeInfo const& m_typeInfo; }; void IntroduceControlFlowSSA::operator()(FunctionDefinition& _function) { - std::set varsInScope; + std::set varsInScope; std::swap(varsInScope, m_variablesInScope); - util::UniqueVector toReassign; + util::UniqueVector toReassign; std::swap(toReassign, m_variablesToReassign); for (auto const& param: _function.parameters) @@ -207,7 +207,7 @@ void IntroduceControlFlowSSA::operator()(Switch& _switch) { yulAssert(m_variablesToReassign.empty(), ""); - util::UniqueVector toReassign; + util::UniqueVector toReassign; for (auto& c: _switch.cases) { (*this)(c.body); @@ -219,17 +219,17 @@ void IntroduceControlFlowSSA::operator()(Switch& _switch) void IntroduceControlFlowSSA::operator()(Block& _block) { - util::UniqueVector variablesDeclaredHere; - util::UniqueVector assignedVariables; + util::UniqueVector variablesDeclaredHere; + util::UniqueVector assignedVariables; util::iterateReplacing( _block.statements, [&](Statement& _s) -> std::optional> { std::vector toPrepend; - for (YulString toReassign: m_variablesToReassign) + for (YulName toReassign: m_variablesToReassign) { - YulString newName = m_nameDispenser.newName(toReassign); + YulName newName = m_nameDispenser.newName(toReassign); toPrepend.emplace_back(VariableDeclaration{ debugDataOf(_s), {TypedName{debugDataOf(_s), newName, m_typeInfo.typeOfVariable(toReassign)}}, @@ -281,7 +281,7 @@ void IntroduceControlFlowSSA::operator()(Block& _block) class PropagateValues: public ASTModifier { public: - explicit PropagateValues(std::set const& _variablesToReplace): + explicit PropagateValues(std::set const& _variablesToReplace): m_variablesToReplace(_variablesToReplace) { } @@ -294,9 +294,9 @@ class PropagateValues: public ASTModifier private: /// This is a set of all variables that are assigned to anywhere in the code. /// Variables that are only declared but never re-assigned are not touched. - std::set const& m_variablesToReplace; - std::map m_currentVariableValues; - std::set m_clearAtEndOfBlock; + std::set const& m_variablesToReplace; + std::map m_currentVariableValues; + std::set m_clearAtEndOfBlock; }; void PropagateValues::operator()(Identifier& _identifier) @@ -312,7 +312,7 @@ void PropagateValues::operator()(VariableDeclaration& _varDecl) if (_varDecl.variables.size() != 1) return; - YulString variable = _varDecl.variables.front().name; + YulName variable = _varDecl.variables.front().name; if (m_variablesToReplace.count(variable)) { // `let a := a_1` - regular declaration of non-SSA variable @@ -323,7 +323,7 @@ void PropagateValues::operator()(VariableDeclaration& _varDecl) else if (_varDecl.value && std::holds_alternative(*_varDecl.value)) { // `let a_1 := a` - assignment to SSA variable after a branch. - YulString value = std::get(*_varDecl.value).name; + YulName value = std::get(*_varDecl.value).name; if (m_variablesToReplace.count(value)) { // This is safe because `a_1` is not a "variable to replace" and thus @@ -341,7 +341,7 @@ void PropagateValues::operator()(Assignment& _assignment) if (_assignment.variableNames.size() != 1) return; - YulString name = _assignment.variableNames.front().name; + YulName name = _assignment.variableNames.front().name; if (!m_variablesToReplace.count(name)) return; @@ -364,7 +364,7 @@ void PropagateValues::operator()(ForLoop& _for) void PropagateValues::operator()(Block& _block) { - std::set clearAtParentBlock = std::move(m_clearAtEndOfBlock); + std::set clearAtParentBlock = std::move(m_clearAtEndOfBlock); m_clearAtEndOfBlock.clear(); ASTModifier::operator()(_block); @@ -380,7 +380,7 @@ void PropagateValues::operator()(Block& _block) void SSATransform::run(OptimiserStepContext& _context, Block& _ast) { TypeInfo typeInfo(_context.dialect, _ast); - std::set assignedVariables = assignedVariableNames(_ast); + std::set assignedVariables = assignedVariableNames(_ast); IntroduceSSA{_context.dispenser, assignedVariables, typeInfo}(_ast); IntroduceControlFlowSSA{_context.dispenser, assignedVariables, typeInfo}(_ast); PropagateValues{assignedVariables}(_ast); diff --git a/libyul/optimiser/SSAValueTracker.cpp b/libyul/optimiser/SSAValueTracker.cpp index 1d25cb54b514..d39ce4b8d263 100644 --- a/libyul/optimiser/SSAValueTracker.cpp +++ b/libyul/optimiser/SSAValueTracker.cpp @@ -49,17 +49,17 @@ void SSAValueTracker::operator()(VariableDeclaration const& _varDecl) setValue(_varDecl.variables.front().name, _varDecl.value.get()); } -std::set SSAValueTracker::ssaVariables(Block const& _ast) +std::set SSAValueTracker::ssaVariables(Block const& _ast) { SSAValueTracker t; t(_ast); - std::set ssaVars; + std::set ssaVars; for (auto const& value: t.values()) ssaVars.insert(value.first); return ssaVars; } -void SSAValueTracker::setValue(YulString _name, Expression const* _value) +void SSAValueTracker::setValue(YulName _name, Expression const* _value) { assertThrow( m_values.count(_name) == 0, diff --git a/libyul/optimiser/SSAValueTracker.h b/libyul/optimiser/SSAValueTracker.h index 5a7eee5124b4..0196ecc40e99 100644 --- a/libyul/optimiser/SSAValueTracker.h +++ b/libyul/optimiser/SSAValueTracker.h @@ -47,18 +47,18 @@ class SSAValueTracker: public ASTWalker void operator()(VariableDeclaration const& _varDecl) override; void operator()(Assignment const& _assignment) override; - std::map const& values() const { return m_values; } - Expression const* value(YulString _name) const { return m_values.at(_name); } + std::map const& values() const { return m_values; } + Expression const* value(YulName _name) const { return m_values.at(_name); } - static std::set ssaVariables(Block const& _ast); + static std::set ssaVariables(Block const& _ast); private: - void setValue(YulString _name, Expression const* _value); + void setValue(YulName _name, Expression const* _value); /// Special expression whose address will be used in m_values. - /// YulString does not need to be reset because SSAValueTracker is short-lived. + /// YulName does not need to be reset because SSAValueTracker is short-lived. Expression const m_zero{Literal{{}, LiteralKind::Number, LiteralValue(u256{0}), {}}}; - std::map m_values; + std::map m_values; }; } diff --git a/libyul/optimiser/Semantics.cpp b/libyul/optimiser/Semantics.cpp index 5d375b1454cb..7dbbb676b43b 100644 --- a/libyul/optimiser/Semantics.cpp +++ b/libyul/optimiser/Semantics.cpp @@ -40,7 +40,7 @@ using namespace solidity::yul; SideEffectsCollector::SideEffectsCollector( Dialect const& _dialect, Expression const& _expression, - std::map const* _functionSideEffects + std::map const* _functionSideEffects ): SideEffectsCollector(_dialect, _functionSideEffects) { @@ -56,7 +56,7 @@ SideEffectsCollector::SideEffectsCollector(Dialect const& _dialect, Statement co SideEffectsCollector::SideEffectsCollector( Dialect const& _dialect, Block const& _ast, - std::map const* _functionSideEffects + std::map const* _functionSideEffects ): SideEffectsCollector(_dialect, _functionSideEffects) { @@ -66,7 +66,7 @@ SideEffectsCollector::SideEffectsCollector( SideEffectsCollector::SideEffectsCollector( Dialect const& _dialect, ForLoop const& _ast, - std::map const* _functionSideEffects + std::map const* _functionSideEffects ): SideEffectsCollector(_dialect, _functionSideEffects) { @@ -77,7 +77,7 @@ void SideEffectsCollector::operator()(FunctionCall const& _functionCall) { ASTWalker::operator()(_functionCall); - YulString functionName = _functionCall.functionName.name; + YulName functionName = _functionCall.functionName.name; if (BuiltinFunction const* f = m_dialect.builtin(functionName)) m_sideEffects += f->sideEffects; else if (m_functionSideEffects && m_functionSideEffects->count(functionName)) @@ -115,7 +115,7 @@ void MSizeFinder::operator()(FunctionCall const& _functionCall) m_msizeFound = true; } -std::map SideEffectsPropagator::sideEffects( +std::map SideEffectsPropagator::sideEffects( Dialect const& _dialect, CallGraph const& _directCallGraph ) @@ -126,7 +126,7 @@ std::map SideEffectsPropagator::sideEffects( // In the future, we should refine that, because the property // is actually a bit different from "not movable". - std::map ret; + std::map ret; for (auto const& function: _directCallGraph.functionsWithLoops + _directCallGraph.recursiveFunctions()) { ret[function].movable = false; @@ -137,9 +137,9 @@ std::map SideEffectsPropagator::sideEffects( for (auto const& call: _directCallGraph.functionCalls) { - YulString funName = call.first; + YulName funName = call.first; SideEffects sideEffects; - auto _visit = [&, visited = std::set{}](YulString _function, auto&& _recurse) mutable { + auto _visit = [&, visited = std::set{}](YulName _function, auto&& _recurse) mutable { if (!visited.insert(_function).second) return; if (sideEffects == SideEffects::worst()) @@ -150,7 +150,7 @@ std::map SideEffectsPropagator::sideEffects( { if (ret.count(_function)) sideEffects += ret[_function]; - for (YulString callee: _directCallGraph.functionCalls.at(_function)) + for (YulName callee: _directCallGraph.functionCalls.at(_function)) _recurse(callee, _recurse); } }; diff --git a/libyul/optimiser/Semantics.h b/libyul/optimiser/Semantics.h index df8ae17a58e1..1d0018897c00 100644 --- a/libyul/optimiser/Semantics.h +++ b/libyul/optimiser/Semantics.h @@ -42,23 +42,23 @@ class SideEffectsCollector: public ASTWalker public: explicit SideEffectsCollector( Dialect const& _dialect, - std::map const* _functionSideEffects = nullptr + std::map const* _functionSideEffects = nullptr ): m_dialect(_dialect), m_functionSideEffects(_functionSideEffects) {} SideEffectsCollector( Dialect const& _dialect, Expression const& _expression, - std::map const* _functionSideEffects = nullptr + std::map const* _functionSideEffects = nullptr ); SideEffectsCollector(Dialect const& _dialect, Statement const& _statement); SideEffectsCollector( Dialect const& _dialect, Block const& _ast, - std::map const* _functionSideEffects = nullptr + std::map const* _functionSideEffects = nullptr ); SideEffectsCollector( Dialect const& _dialect, ForLoop const& _ast, - std::map const* _functionSideEffects = nullptr + std::map const* _functionSideEffects = nullptr ); using ASTWalker::operator(); @@ -117,7 +117,7 @@ class SideEffectsCollector: public ASTWalker private: Dialect const& m_dialect; - std::map const* m_functionSideEffects = nullptr; + std::map const* m_functionSideEffects = nullptr; SideEffects m_sideEffects; }; @@ -130,7 +130,7 @@ class SideEffectsCollector: public ASTWalker class SideEffectsPropagator { public: - static std::map sideEffects( + static std::map sideEffects( Dialect const& _dialect, CallGraph const& _directCallGraph ); @@ -195,7 +195,7 @@ class MovableChecker: public SideEffectsCollector public: explicit MovableChecker( Dialect const& _dialect, - std::map const* _functionSideEffects = nullptr + std::map const* _functionSideEffects = nullptr ): SideEffectsCollector(_dialect, _functionSideEffects) {} MovableChecker(Dialect const& _dialect, Expression const& _expression); @@ -205,11 +205,11 @@ class MovableChecker: public SideEffectsCollector void visit(Statement const&) override; using ASTWalker::visit; - std::set const& referencedVariables() const { return m_variableReferences; } + std::set const& referencedVariables() const { return m_variableReferences; } private: /// Which variables the current expression references. - std::set m_variableReferences; + std::set m_variableReferences; }; struct ControlFlowSideEffects; @@ -231,7 +231,7 @@ class TerminationFinder TerminationFinder( Dialect const& _dialect, - std::map const* _functionSideEffects = nullptr + std::map const* _functionSideEffects = nullptr ): m_dialect(_dialect), m_functionSideEffects(_functionSideEffects) {} /// @returns the index of the first statement in the provided sequence @@ -256,7 +256,7 @@ class TerminationFinder private: Dialect const& m_dialect; - std::map const* m_functionSideEffects; + std::map const* m_functionSideEffects; }; } diff --git a/libyul/optimiser/SimplificationRules.cpp b/libyul/optimiser/SimplificationRules.cpp index e2d46832906e..03e4ccdd0eda 100644 --- a/libyul/optimiser/SimplificationRules.cpp +++ b/libyul/optimiser/SimplificationRules.cpp @@ -40,7 +40,7 @@ using namespace solidity::yul; SimplificationRules::Rule const* SimplificationRules::findFirstMatch( Expression const& _expr, Dialect const& _dialect, - std::function const& _ssaValues + std::function const& _ssaValues ) { auto instruction = instructionAndArguments(_dialect, _expr); @@ -137,7 +137,7 @@ void Pattern::setMatchGroup(unsigned _group, std::map const& _ssaValues + std::function const& _ssaValues ) const { Expression const* expr = &_expr; @@ -146,7 +146,7 @@ bool Pattern::matches( // Do not do it for "Any" because we can check identity better for variables. if (m_kind != PatternKind::Any && std::holds_alternative(_expr)) { - YulString varName = std::get(_expr).name; + YulName varName = std::get(_expr).name; if (AssignedValue const* value = _ssaValues(varName)) if (Expression const* new_expr = value->value) expr = new_expr; @@ -252,7 +252,7 @@ Expression Pattern::toExpression(langutil::DebugData::ConstPtr const& _debugData std::string name = util::toLower(instructionInfo(m_instruction, _evmVersion).name); return FunctionCall{_debugData, - Identifier{_debugData, YulString{name}}, + Identifier{_debugData, YulName{name}}, std::move(arguments) }; } diff --git a/libyul/optimiser/SimplificationRules.h b/libyul/optimiser/SimplificationRules.h index 5e498bd5c9a4..9362ee8557ec 100644 --- a/libyul/optimiser/SimplificationRules.h +++ b/libyul/optimiser/SimplificationRules.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include @@ -64,7 +64,7 @@ class SimplificationRules static Rule const* findFirstMatch( Expression const& _expr, Dialect const& _dialect, - std::function const& _ssaValues + std::function const& _ssaValues ); /// Checks whether the rulelist is non-empty. This is usually enforced @@ -121,7 +121,7 @@ class Pattern bool matches( Expression const& _expr, Dialect const& _dialect, - std::function const& _ssaValues + std::function const& _ssaValues ) const; std::vector arguments() const { return m_arguments; } diff --git a/libyul/optimiser/StackCompressor.cpp b/libyul/optimiser/StackCompressor.cpp index 58552147a608..23d47b6ee554 100644 --- a/libyul/optimiser/StackCompressor.cpp +++ b/libyul/optimiser/StackCompressor.cpp @@ -60,9 +60,9 @@ class RematCandidateSelector: public DataFlowAnalyzer /// @returns a map from function name to rematerialisation costs to a vector of variables to rematerialise /// and variables that occur in their expression. /// While the map is sorted by cost, the contained vectors are sorted by the order of occurrence. - std::map>> candidates() + std::map>> candidates() { - std::map>> cand; + std::map>> cand; for (auto const& [functionName, candidate]: m_candidates) { if (size_t const* cost = util::valueOrNullptr(m_expressionCodeCost, candidate)) @@ -88,7 +88,7 @@ class RematCandidateSelector: public DataFlowAnalyzer DataFlowAnalyzer::operator()(_varDecl); if (_varDecl.variables.size() == 1) { - YulString varName = _varDecl.variables.front().name; + YulName varName = _varDecl.variables.front().name; if (AssignedValue const* value = variableValue(varName)) { yulAssert(!m_expressionCodeCost.count(varName), ""); @@ -111,7 +111,7 @@ class RematCandidateSelector: public DataFlowAnalyzer { if (std::holds_alternative(_e)) { - YulString name = std::get(_e).name; + YulName name = std::get(_e).name; if (m_expressionCodeCost.count(name)) { if (!variableValue(name)) @@ -124,29 +124,29 @@ class RematCandidateSelector: public DataFlowAnalyzer } /// Remove the variable from the candidate set. - void rematImpossible(YulString _variable) + void rematImpossible(YulName _variable) { m_numReferences.erase(_variable); m_expressionCodeCost.erase(_variable); } - YulString m_currentFunctionName = {}; + YulName m_currentFunctionName = {}; /// All candidate variables by function name, in order of occurrence. - std::vector> m_candidates; + std::vector> m_candidates; /// Candidate variables and the code cost of their value. - std::map m_expressionCodeCost; + std::map m_expressionCodeCost; /// Number of references to each candidate variable. - std::map m_numReferences; + std::map m_numReferences; }; /// Selects at most @a _numVariables among @a _candidates. -std::set chooseVarsToEliminate( - std::map> const& _candidates, +std::set chooseVarsToEliminate( + std::map> const& _candidates, size_t _numVariables ) { - std::set varsToEliminate; + std::set varsToEliminate; for (auto&& [cost, candidates]: _candidates) for (auto&& candidate: candidates) { @@ -160,15 +160,15 @@ std::set chooseVarsToEliminate( void eliminateVariables( Dialect const& _dialect, Block& _ast, - std::map const& _numVariables, + std::map const& _numVariables, bool _allowMSizeOptimization ) { RematCandidateSelector selector{_dialect}; selector(_ast); - std::map>> candidates = selector.candidates(); + std::map>> candidates = selector.candidates(); - std::set varsToEliminate; + std::set varsToEliminate; for (auto const& [functionName, numVariables]: _numVariables) { yulAssert(numVariables > 0); @@ -177,14 +177,14 @@ void eliminateVariables( Rematerialiser::run(_dialect, _ast, std::move(varsToEliminate)); // Do not remove functions. - std::set allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names(); + std::set allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names(); UnusedPruner::runUntilStabilised(_dialect, _ast, _allowMSizeOptimization, nullptr, allFunctions); } void eliminateVariablesOptimizedCodegen( Dialect const& _dialect, Block& _ast, - std::map> const& _unreachables, + std::map> const& _unreachables, bool _allowMSizeOptimization ) { @@ -194,19 +194,19 @@ void eliminateVariablesOptimizedCodegen( RematCandidateSelector selector{_dialect}; selector(_ast); - std::map candidates; + std::map candidates; for (auto const& [functionName, candidatesInFunction]: selector.candidates()) for (auto [cost, candidatesWithCost]: candidatesInFunction) for (auto candidate: candidatesWithCost) candidates[candidate] = cost; - std::set varsToEliminate; + std::set varsToEliminate; // TODO: this currently ignores the fact that variables may reference other variables we want to eliminate. for (auto const& [functionName, unreachables]: _unreachables) for (auto const& unreachable: unreachables) { - std::map> suitableCandidates; + std::map> suitableCandidates; size_t neededSlots = unreachable.deficit; for (auto varName: unreachable.variableChoices) { @@ -229,7 +229,7 @@ void eliminateVariablesOptimizedCodegen( } Rematerialiser::run(_dialect, _ast, std::move(varsToEliminate), true); // Do not remove functions. - std::set allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names(); + std::set allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names(); UnusedPruner::runUntilStabilised(_dialect, _ast, _allowMSizeOptimization, nullptr, allFunctions); } @@ -268,7 +268,7 @@ bool StackCompressor::run( else for (size_t iterations = 0; iterations < _maxIterations; iterations++) { - std::map stackSurplus = CompilabilityChecker(_dialect, _object, _optimizeStackAllocation).stackDeficit; + std::map stackSurplus = CompilabilityChecker(_dialect, _object, _optimizeStackAllocation).stackDeficit; if (stackSurplus.empty()) return true; eliminateVariables( diff --git a/libyul/optimiser/StackLimitEvader.cpp b/libyul/optimiser/StackLimitEvader.cpp index 0310858a187b..24712938f03b 100644 --- a/libyul/optimiser/StackLimitEvader.cpp +++ b/libyul/optimiser/StackLimitEvader.cpp @@ -56,7 +56,7 @@ namespace */ struct MemoryOffsetAllocator { - uint64_t run(YulString _function = YulString{}) + uint64_t run(YulName _function = YulName{}) { if (slotsRequiredForFunction.count(_function)) return slotsRequiredForFunction[_function]; @@ -66,7 +66,7 @@ struct MemoryOffsetAllocator uint64_t requiredSlots = 0; if (callGraph.count(_function)) - for (YulString child: callGraph.at(_function)) + for (YulName child: callGraph.at(_function)) requiredSlots = std::max(run(child), requiredSlots); if (auto const* unreachables = util::valueOrNullptr(unreachableVariables, _function)) @@ -84,7 +84,7 @@ struct MemoryOffsetAllocator // Assign slots for all variables that become unreachable in the function body, if the above did not // assign a slot for them already. - for (YulString variable: *unreachables) + for (YulName variable: *unreachables) // The empty case is a function with too many arguments or return values, // which was already handled above. if (!variable.empty() && !slotAllocations.count(variable)) @@ -96,16 +96,16 @@ struct MemoryOffsetAllocator /// Maps function names to the set of unreachable variables in that function. /// An empty variable name means that the function has too many arguments or return variables. - std::map> const& unreachableVariables; + std::map> const& unreachableVariables; /// The graph of immediate function calls of all functions. - std::map> const& callGraph; + std::map> const& callGraph; /// Maps the name of each user-defined function to its definition. - std::map const& functionDefinitions; + std::map const& functionDefinitions; /// Maps variable names to the memory slot the respective variable is assigned. - std::map slotAllocations{}; + std::map slotAllocations{}; /// Maps function names to the number of memory slots the respective function requires. - std::map slotsRequiredForFunction{}; + std::map slotsRequiredForFunction{}; }; u256 literalArgumentValue(FunctionCall const& _call) @@ -145,10 +145,10 @@ void StackLimitEvader::run( void StackLimitEvader::run( OptimiserStepContext& _context, Object& _object, - std::map> const& _stackTooDeepErrors + std::map> const& _stackTooDeepErrors ) { - std::map> unreachableVariables; + std::map> unreachableVariables; for (auto&& [function, stackTooDeepErrors]: _stackTooDeepErrors) { auto& unreachables = unreachableVariables[function]; @@ -164,7 +164,7 @@ void StackLimitEvader::run( void StackLimitEvader::run( OptimiserStepContext& _context, Object& _object, - std::map> const& _unreachableVariables + std::map> const& _unreachableVariables ) { yulAssert(_object.code, ""); @@ -174,10 +174,7 @@ void StackLimitEvader::run( "StackLimitEvader can only be run on objects using the EVMDialect with object access." ); - std::vector memoryGuardCalls = findFunctionCalls( - *_object.code, - "memoryguard"_yulstring - ); + std::vector memoryGuardCalls = findFunctionCalls(*_object.code, "memoryguard"_yulname); // Do not optimise, if no ``memoryguard`` call is found. if (memoryGuardCalls.empty()) return; @@ -193,11 +190,11 @@ void StackLimitEvader::run( CallGraph callGraph = CallGraphGenerator::callGraph(*_object.code); // We cannot move variables in recursive functions to fixed memory offsets. - for (YulString function: callGraph.recursiveFunctions()) + for (YulName function: callGraph.recursiveFunctions()) if (_unreachableVariables.count(function)) return; - std::map functionDefinitions = allFunctionDefinitions(*_object.code); + std::map functionDefinitions = allFunctionDefinitions(*_object.code); MemoryOffsetAllocator memoryOffsetAllocator{_unreachableVariables, callGraph.functionCalls, functionDefinitions}; uint64_t requiredSlots = memoryOffsetAllocator.run(); @@ -206,7 +203,7 @@ void StackLimitEvader::run( StackToMemoryMover::run(_context, reservedMemory, memoryOffsetAllocator.slotAllocations, requiredSlots, *_object.code); reservedMemory += 32 * requiredSlots; - for (FunctionCall* memoryGuardCall: findFunctionCalls(*_object.code, "memoryguard"_yulstring)) + for (FunctionCall* memoryGuardCall: findFunctionCalls(*_object.code, "memoryguard"_yulname)) { Literal* literal = std::get_if(&memoryGuardCall->arguments.front()); yulAssert(literal && literal->kind == LiteralKind::Number, ""); diff --git a/libyul/optimiser/StackLimitEvader.h b/libyul/optimiser/StackLimitEvader.h index 025553200f05..0411f05735bc 100644 --- a/libyul/optimiser/StackLimitEvader.h +++ b/libyul/optimiser/StackLimitEvader.h @@ -60,7 +60,7 @@ class StackLimitEvader static void run( OptimiserStepContext& _context, Object& _object, - std::map> const& _unreachableVariables + std::map> const& _unreachableVariables ); /// @a _stackTooDeepErrors can be determined by the StackLayoutGenerator. /// Can only be run on the EVM dialect with objects. @@ -70,7 +70,7 @@ class StackLimitEvader static void run( OptimiserStepContext& _context, Object& _object, - std::map> const& _stackTooDeepErrors + std::map> const& _stackTooDeepErrors ); /// Determines stack too deep errors using the appropriate code generation backend. /// Can only be run on the EVM dialect with objects. diff --git a/libyul/optimiser/StackToMemoryMover.cpp b/libyul/optimiser/StackToMemoryMover.cpp index dbf3183fb420..7ec57903482f 100644 --- a/libyul/optimiser/StackToMemoryMover.cpp +++ b/libyul/optimiser/StackToMemoryMover.cpp @@ -77,7 +77,7 @@ FunctionCall generateMemoryLoad(Dialect const& _dialect, langutil::DebugData::Co void StackToMemoryMover::run( OptimiserStepContext& _context, u256 _reservedMemory, - std::map const& _memorySlots, + std::map const& _memorySlots, uint64_t _numRequiredSlots, Block& _block ) @@ -88,10 +88,10 @@ void StackToMemoryMover::run( memoryOffsetTracker, util::applyMap( allFunctionDefinitions(_block), - util::mapTuple([](YulString _name, FunctionDefinition const* _funDef) { + util::mapTuple([](YulName _name, FunctionDefinition const* _funDef) { return make_pair(_name, _funDef->returnVariables); }), - std::map{} + std::map{} ) ); stackToMemoryMover(_block); @@ -101,7 +101,7 @@ void StackToMemoryMover::run( StackToMemoryMover::StackToMemoryMover( OptimiserStepContext& _context, VariableMemoryOffsetTracker const& _memoryOffsetTracker, - std::map _functionReturnVariables + std::map _functionReturnVariables ): m_context(_context), m_memoryOffsetTracker(_memoryOffsetTracker), @@ -150,7 +150,7 @@ void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition) std::not_fn(m_memoryOffsetTracker) ) | ranges::to; // Generate new function without return variable and with only the non-moved parameters. - YulString newFunctionName = m_context.dispenser.newName(_functionDefinition.name); + YulName newFunctionName = m_context.dispenser.newName(_functionDefinition.name); m_newFunctionDefinitions.emplace_back(FunctionDefinition{ _functionDefinition.debugData, newFunctionName, @@ -159,7 +159,7 @@ void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition) std::move(_functionDefinition.body) }); // Generate new names for the arguments to maintain disambiguation. - std::map newArgumentNames; + std::map newArgumentNames; for (TypedName const& _var: stackParameters) newArgumentNames[_var.name] = m_context.dispenser.newName(_var.name); for (auto& parameter: _functionDefinition.parameters) @@ -255,7 +255,7 @@ void StackToMemoryMover::operator()(Block& _block) rhs = std::make_unique(generateMemoryLoad(m_context.dialect, debugData, *rhsSlot)); else { - YulString tempVarName = m_nameDispenser.newName(lhsVar.name); + YulName tempVarName = m_nameDispenser.newName(lhsVar.name); tempDecl.variables.emplace_back(TypedName{lhsVar.debugData, tempVarName, {}}); rhs = std::make_unique(Identifier{debugData, tempVarName}); } @@ -309,7 +309,7 @@ void StackToMemoryMover::visit(Expression& _expression) _expression = generateMemoryLoad(m_context.dialect, identifier->debugData, *offset); } -std::optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(YulString const& _variable) const +std::optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(YulName const& _variable) const { if (m_memorySlots.count(_variable)) { diff --git a/libyul/optimiser/StackToMemoryMover.h b/libyul/optimiser/StackToMemoryMover.h index 79c7276ede93..7392660311bf 100644 --- a/libyul/optimiser/StackToMemoryMover.h +++ b/libyul/optimiser/StackToMemoryMover.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -142,7 +143,7 @@ class StackToMemoryMover: ASTModifier static void run( OptimiserStepContext& _context, u256 _reservedMemory, - std::map const& _memorySlots, + std::map const& _memorySlots, uint64_t _numRequiredSlots, Block& _block ); @@ -158,42 +159,42 @@ class StackToMemoryMover: ASTModifier public: VariableMemoryOffsetTracker( u256 _reservedMemory, - std::map const& _memorySlots, + std::map const& _memorySlots, uint64_t _numRequiredSlots ): m_reservedMemory(_reservedMemory), m_memorySlots(_memorySlots), m_numRequiredSlots(_numRequiredSlots) {} - /// @returns a YulString containing the memory offset to be assigned to @a _variable as number literal + /// @returns a YulName containing the memory offset to be assigned to @a _variable as number literal /// or std::nullopt if the variable should not be moved. - std::optional operator()(YulString const& _variable) const; - /// @returns a YulString containing the memory offset to be assigned to @a _variable as number literal + std::optional operator()(YulName const& _variable) const; + /// @returns a YulName containing the memory offset to be assigned to @a _variable as number literal /// or std::nullopt if the variable should not be moved. std::optional operator()(TypedName const& _variable) const; - /// @returns a YulString containing the memory offset to be assigned to @a _variable as number literal + /// @returns a YulName containing the memory offset to be assigned to @a _variable as number literal /// or std::nullopt if the variable should not be moved. std::optional operator()(Identifier const& _variable) const; private: u256 m_reservedMemory; - std::map const& m_memorySlots; + std::map const& m_memorySlots; uint64_t m_numRequiredSlots = 0; }; struct FunctionMoveInfo { - std::vector> returnVariableSlots; + std::vector> returnVariableSlots; }; StackToMemoryMover( OptimiserStepContext& _context, VariableMemoryOffsetTracker const& _memoryOffsetTracker, - std::map> _functionReturnVariables + std::map> _functionReturnVariables ); OptimiserStepContext& m_context; VariableMemoryOffsetTracker const& m_memoryOffsetTracker; NameDispenser& m_nameDispenser; /// Map from function names to the return variables of the function with that name. - std::map> m_functionReturnVariables; + std::map> m_functionReturnVariables; /// List of functions generated while running this step that are to be appended to the code in the end. std::list m_newFunctionDefinitions; }; diff --git a/libyul/optimiser/Substitution.cpp b/libyul/optimiser/Substitution.cpp index b2d4d469e171..5baec51e34a6 100644 --- a/libyul/optimiser/Substitution.cpp +++ b/libyul/optimiser/Substitution.cpp @@ -30,7 +30,7 @@ Expression Substitution::translate(Expression const& _expression) { if (std::holds_alternative(_expression)) { - YulString name = std::get(_expression).name; + YulName name = std::get(_expression).name; if (m_substitutions.count(name)) // No recursive substitution return ASTCopier().translate(*m_substitutions.at(name)); diff --git a/libyul/optimiser/Substitution.h b/libyul/optimiser/Substitution.h index f76dcc72ea47..2d4ccffc0148 100644 --- a/libyul/optimiser/Substitution.h +++ b/libyul/optimiser/Substitution.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include @@ -35,13 +35,13 @@ namespace solidity::yul class Substitution: public ASTCopier { public: - Substitution(std::map const& _substitutions): + Substitution(std::map const& _substitutions): m_substitutions(_substitutions) {} Expression translate(Expression const& _expression) override; private: - std::map const& m_substitutions; + std::map const& m_substitutions; }; } diff --git a/libyul/optimiser/Suite.cpp b/libyul/optimiser/Suite.cpp index 83bc0370092b..c4004948c838 100644 --- a/libyul/optimiser/Suite.cpp +++ b/libyul/optimiser/Suite.cpp @@ -141,7 +141,7 @@ void OptimiserSuite::run( std::string_view _optimisationSequence, std::string_view _optimisationCleanupSequence, std::optional _expectedExecutionsPerDeployment, - std::set const& _externallyUsedIdentifiers + std::set const& _externallyUsedIdentifiers ) { EVMDialect const* evmDialect = dynamic_cast(&_dialect); @@ -150,7 +150,7 @@ void OptimiserSuite::run( evmDialect && evmDialect->evmVersion().canOverchargeGasForCall() && evmDialect->providesObjectAccess(); - std::set reservedIdentifiers = _externallyUsedIdentifiers; + std::set reservedIdentifiers = _externallyUsedIdentifiers; reservedIdentifiers += _dialect.fixedFunctionNames(); *_object.code = std::get(Disambiguator( diff --git a/libyul/optimiser/Suite.h b/libyul/optimiser/Suite.h index 6e3886da3b2d..15a41cb9f3dc 100644 --- a/libyul/optimiser/Suite.h +++ b/libyul/optimiser/Suite.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include #include #include @@ -70,7 +70,7 @@ class OptimiserSuite std::string_view _optimisationSequence, std::string_view _optimisationCleanupSequence, std::optional _expectedExecutionsPerDeployment, - std::set const& _externallyUsedIdentifiers = {} + std::set const& _externallyUsedIdentifiers = {} ); /// Ensures that specified sequence of step abbreviations is well-formed and can be executed. diff --git a/libyul/optimiser/SyntacticalEquality.h b/libyul/optimiser/SyntacticalEquality.h index 5a8d2b49b267..0665a5efbe6e 100644 --- a/libyul/optimiser/SyntacticalEquality.h +++ b/libyul/optimiser/SyntacticalEquality.h @@ -22,7 +22,7 @@ #pragma once #include -#include +#include #include #include @@ -84,8 +84,8 @@ class SyntacticallyEqual } std::size_t m_idsUsed = 0; - std::map m_identifiersLHS; - std::map m_identifiersRHS; + std::map m_identifiersLHS; + std::map m_identifiersRHS; }; /** diff --git a/libyul/optimiser/TypeInfo.cpp b/libyul/optimiser/TypeInfo.cpp index 16ce65496861..754c0bad08f8 100644 --- a/libyul/optimiser/TypeInfo.cpp +++ b/libyul/optimiser/TypeInfo.cpp @@ -62,8 +62,8 @@ class TypeInfo::TypeCollector: public ASTWalker } } - std::map variableTypes; - std::map functionTypes; + std::map variableTypes; + std::map functionTypes; }; @@ -75,12 +75,12 @@ TypeInfo::TypeInfo(Dialect const& _dialect, Block const& _ast): m_variableTypes = std::move(types.variableTypes); } -YulString TypeInfo::typeOf(Expression const& _expression) const +YulName TypeInfo::typeOf(Expression const& _expression) const { return std::visit(GenericVisitor{ [&](FunctionCall const& _funCall) { - YulString name = _funCall.functionName.name; - std::vector const* retTypes = nullptr; + YulName name = _funCall.functionName.name; + std::vector const* retTypes = nullptr; if (BuiltinFunction const* fun = m_dialect.builtin(name)) retTypes = &fun->returns; else @@ -97,7 +97,7 @@ YulString TypeInfo::typeOf(Expression const& _expression) const }, _expression); } -YulString TypeInfo::typeOfVariable(YulString _name) const +YulName TypeInfo::typeOfVariable(YulName _name) const { return m_variableTypes.at(_name); } diff --git a/libyul/optimiser/TypeInfo.h b/libyul/optimiser/TypeInfo.h index 5ed0a0d55c5f..96c43875a638 100644 --- a/libyul/optimiser/TypeInfo.h +++ b/libyul/optimiser/TypeInfo.h @@ -21,7 +21,7 @@ #pragma once #include -#include +#include #include #include @@ -40,26 +40,26 @@ class TypeInfo public: TypeInfo(Dialect const& _dialect, Block const& _ast); - void setVariableType(YulString _name, YulString _type) { m_variableTypes[_name] = _type; } + void setVariableType(YulName _name, YulName _type) { m_variableTypes[_name] = _type; } /// @returns the type of an expression that is assumed to return exactly one value. - YulString typeOf(Expression const& _expression) const; + YulName typeOf(Expression const& _expression) const; /// \returns the type of variable - YulString typeOfVariable(YulString _name) const; + YulName typeOfVariable(YulName _name) const; private: class TypeCollector; struct FunctionType { - std::vector parameters; - std::vector returns; + std::vector parameters; + std::vector returns; }; Dialect const& m_dialect; - std::map m_variableTypes; - std::map m_functionTypes; + std::map m_variableTypes; + std::map m_functionTypes; }; } diff --git a/libyul/optimiser/UnusedAssignEliminator.cpp b/libyul/optimiser/UnusedAssignEliminator.cpp index f3d78288f3ca..13a6ba9ee526 100644 --- a/libyul/optimiser/UnusedAssignEliminator.cpp +++ b/libyul/optimiser/UnusedAssignEliminator.cpp @@ -92,7 +92,7 @@ void UnusedAssignEliminator::operator()(FunctionCall const& _functionCall) void UnusedAssignEliminator::operator()(Leave const&) { - for (YulString name: m_returnVariables) + for (YulName name: m_returnVariables) markUsed(name); m_activeStores.clear(); } @@ -152,7 +152,7 @@ void UnusedAssignEliminator::finalizeFunctionDefinition(FunctionDefinition const markUsed(retParam.name); } -void UnusedAssignEliminator::markUsed(YulString _variable) +void UnusedAssignEliminator::markUsed(YulName _variable) { for (auto& assignment: m_activeStores[_variable]) m_usedStores.insert(assignment); diff --git a/libyul/optimiser/UnusedAssignEliminator.h b/libyul/optimiser/UnusedAssignEliminator.h index 800d626eb840..9c3b1e4bcabf 100644 --- a/libyul/optimiser/UnusedAssignEliminator.h +++ b/libyul/optimiser/UnusedAssignEliminator.h @@ -121,7 +121,7 @@ class UnusedAssignEliminator: public UnusedStoreBase explicit UnusedAssignEliminator( Dialect const& _dialect, - std::map _controlFlowSideEffects + std::map _controlFlowSideEffects ): UnusedStoreBase(_dialect), m_controlFlowSideEffects(_controlFlowSideEffects) @@ -141,10 +141,10 @@ class UnusedAssignEliminator: public UnusedStoreBase void shortcutNestedLoop(ActiveStores const& _beforeLoop) override; void finalizeFunctionDefinition(FunctionDefinition const& _functionDefinition) override; - void markUsed(YulString _variable); + void markUsed(YulName _variable); - std::set m_returnVariables; - std::map m_controlFlowSideEffects; + std::set m_returnVariables; + std::map m_controlFlowSideEffects; }; } diff --git a/libyul/optimiser/UnusedFunctionParameterPruner.cpp b/libyul/optimiser/UnusedFunctionParameterPruner.cpp index 40c2fe80c65d..49c0a9c4d427 100644 --- a/libyul/optimiser/UnusedFunctionParameterPruner.cpp +++ b/libyul/optimiser/UnusedFunctionParameterPruner.cpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include #include @@ -42,7 +42,7 @@ using namespace solidity::yul::unusedFunctionsCommon; void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ast) { - std::map references = VariableReferencesCounter::countReferences(_ast); + std::map references = VariableReferencesCounter::countReferences(_ast); auto used = [&](auto v) -> bool { return references.count(v.name); }; // Function name and a pair of boolean masks, the first corresponds to parameters and the second @@ -54,7 +54,7 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ // Similarly for the second vector in the pair, a value `false` at index `i` indicates that the // return parameter at index `i` in `FunctionDefinition::returnVariables` is unused inside // function body. - std::map, std::vector>> usedParametersAndReturnVariables; + std::map, std::vector>> usedParametersAndReturnVariables; // Step 1 of UnusedFunctionParameterPruner: Find functions whose parameters (both arguments and // return-parameters) are not used in its body. @@ -72,7 +72,7 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ }; } - std::set functionNamesToFree = util::keys(usedParametersAndReturnVariables); + std::set functionNamesToFree = util::keys(usedParametersAndReturnVariables); // Step 2 of UnusedFunctionParameterPruner: Renames the function and replaces all references to // the function, say `f`, by its new name, say `f_1`. @@ -81,7 +81,7 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ // Inverse-Map of the above translations. In the above example, this will store an element with // key `f_1` and value `f`. - std::map newToOriginalNames = invertMap(replace.translations()); + std::map newToOriginalNames = invertMap(replace.translations()); // Step 3 of UnusedFunctionParameterPruner: introduce a new function in the block with body of // the old one. Replace the body of the old one with a function call to the new one with reduced @@ -98,8 +98,8 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ if (newToOriginalNames.count(originalFunction.name)) { - YulString linkingFunctionName = originalFunction.name; - YulString originalFunctionName = newToOriginalNames.at(linkingFunctionName); + YulName linkingFunctionName = originalFunction.name; + YulName originalFunctionName = newToOriginalNames.at(linkingFunctionName); std::pair, std::vector> used = usedParametersAndReturnVariables.at(originalFunctionName); diff --git a/libyul/optimiser/UnusedFunctionsCommon.cpp b/libyul/optimiser/UnusedFunctionsCommon.cpp index ed9d0ba4c371..bd38b33cafd9 100644 --- a/libyul/optimiser/UnusedFunctionsCommon.cpp +++ b/libyul/optimiser/UnusedFunctionsCommon.cpp @@ -30,8 +30,8 @@ using namespace solidity::yul::unusedFunctionsCommon; FunctionDefinition unusedFunctionsCommon::createLinkingFunction( FunctionDefinition const& _original, std::pair, std::vector> const& _usedParametersAndReturns, - YulString const& _originalFunctionName, - YulString const& _linkingFunctionName, + YulName const& _originalFunctionName, + YulName const& _linkingFunctionName, NameDispenser& _nameDispenser ) { diff --git a/libyul/optimiser/UnusedFunctionsCommon.h b/libyul/optimiser/UnusedFunctionsCommon.h index 2b0f3000dfda..5aa231b1e410 100644 --- a/libyul/optimiser/UnusedFunctionsCommon.h +++ b/libyul/optimiser/UnusedFunctionsCommon.h @@ -52,8 +52,8 @@ inline bool tooSimpleToBePruned(FunctionDefinition const& _f) FunctionDefinition createLinkingFunction( FunctionDefinition const& _original, std::pair, std::vector> const& _usedParametersAndReturns, - YulString const& _originalFunctionName, - YulString const& _linkingFunctionName, + YulName const& _originalFunctionName, + YulName const& _linkingFunctionName, NameDispenser& _nameDispenser ); diff --git a/libyul/optimiser/UnusedPruner.cpp b/libyul/optimiser/UnusedPruner.cpp index a64f37ebedeb..9df51cf7f069 100644 --- a/libyul/optimiser/UnusedPruner.cpp +++ b/libyul/optimiser/UnusedPruner.cpp @@ -43,8 +43,8 @@ UnusedPruner::UnusedPruner( Dialect const& _dialect, Block& _ast, bool _allowMSizeOptimization, - std::map const* _functionSideEffects, - std::set const& _externallyUsedFunctions + std::map const* _functionSideEffects, + std::set const& _externallyUsedFunctions ): m_dialect(_dialect), m_allowMSizeOptimization(_allowMSizeOptimization), @@ -59,7 +59,7 @@ UnusedPruner::UnusedPruner( Dialect const& _dialect, FunctionDefinition& _function, bool _allowMSizeOptimization, - std::set const& _externallyUsedFunctions + std::set const& _externallyUsedFunctions ): m_dialect(_dialect), m_allowMSizeOptimization(_allowMSizeOptimization) @@ -135,8 +135,8 @@ void UnusedPruner::runUntilStabilised( Dialect const& _dialect, Block& _ast, bool _allowMSizeOptimization, - std::map const* _functionSideEffects, - std::set const& _externallyUsedFunctions + std::map const* _functionSideEffects, + std::set const& _externallyUsedFunctions ) { while (true) @@ -153,10 +153,10 @@ void UnusedPruner::runUntilStabilised( void UnusedPruner::runUntilStabilisedOnFullAST( Dialect const& _dialect, Block& _ast, - std::set const& _externallyUsedFunctions + std::set const& _externallyUsedFunctions ) { - std::map functionSideEffects = + std::map functionSideEffects = SideEffectsPropagator::sideEffects(_dialect, CallGraphGenerator::callGraph(_ast)); bool allowMSizeOptimization = !MSizeFinder::containsMSize(_dialect, _ast); runUntilStabilised(_dialect, _ast, allowMSizeOptimization, &functionSideEffects, _externallyUsedFunctions); @@ -166,7 +166,7 @@ void UnusedPruner::runUntilStabilised( Dialect const& _dialect, FunctionDefinition& _function, bool _allowMSizeOptimization, - std::set const& _externallyUsedFunctions + std::set const& _externallyUsedFunctions ) { while (true) @@ -178,12 +178,12 @@ void UnusedPruner::runUntilStabilised( } } -bool UnusedPruner::used(YulString _name) const +bool UnusedPruner::used(YulName _name) const { return m_references.count(_name) && m_references.at(_name) > 0; } -void UnusedPruner::subtractReferences(std::map const& _subtrahend) +void UnusedPruner::subtractReferences(std::map const& _subtrahend) { for (auto const& ref: _subtrahend) { diff --git a/libyul/optimiser/UnusedPruner.h b/libyul/optimiser/UnusedPruner.h index e4587d5d725b..b0ba53bce95c 100644 --- a/libyul/optimiser/UnusedPruner.h +++ b/libyul/optimiser/UnusedPruner.h @@ -23,7 +23,7 @@ #include #include -#include +#include #include #include @@ -64,14 +64,14 @@ class UnusedPruner: public ASTModifier Dialect const& _dialect, Block& _ast, bool _allowMSizeOptimization, - std::map const* _functionSideEffects = nullptr, - std::set const& _externallyUsedFunctions = {} + std::map const* _functionSideEffects = nullptr, + std::set const& _externallyUsedFunctions = {} ); static void run( Dialect const& _dialect, Block& _ast, - std::set const& _externallyUsedFunctions = {} + std::set const& _externallyUsedFunctions = {} ) { runUntilStabilisedOnFullAST(_dialect, _ast, _externallyUsedFunctions); @@ -84,7 +84,7 @@ class UnusedPruner: public ASTModifier static void runUntilStabilisedOnFullAST( Dialect const& _dialect, Block& _ast, - std::set const& _externallyUsedFunctions = {} + std::set const& _externallyUsedFunctions = {} ); // Run the pruner until the code does not change anymore. @@ -96,7 +96,7 @@ class UnusedPruner: public ASTModifier Dialect const& _dialect, FunctionDefinition& _functionDefinition, bool _allowMSizeOptimization, - std::set const& _externallyUsedFunctions = {} + std::set const& _externallyUsedFunctions = {} ); private: @@ -104,24 +104,24 @@ class UnusedPruner: public ASTModifier Dialect const& _dialect, Block& _ast, bool _allowMSizeOptimization, - std::map const* _functionSideEffects = nullptr, - std::set const& _externallyUsedFunctions = {} + std::map const* _functionSideEffects = nullptr, + std::set const& _externallyUsedFunctions = {} ); UnusedPruner( Dialect const& _dialect, FunctionDefinition& _function, bool _allowMSizeOptimization, - std::set const& _externallyUsedFunctions = {} + std::set const& _externallyUsedFunctions = {} ); - bool used(YulString _name) const; - void subtractReferences(std::map const& _subtrahend); + bool used(YulName _name) const; + void subtractReferences(std::map const& _subtrahend); Dialect const& m_dialect; bool m_allowMSizeOptimization = false; - std::map const* m_functionSideEffects = nullptr; + std::map const* m_functionSideEffects = nullptr; bool m_shouldRunAgain = false; - std::map m_references; + std::map m_references; }; } diff --git a/libyul/optimiser/UnusedStoreBase.h b/libyul/optimiser/UnusedStoreBase.h index 0d618d8d254f..b6dde8c5511f 100644 --- a/libyul/optimiser/UnusedStoreBase.h +++ b/libyul/optimiser/UnusedStoreBase.h @@ -60,7 +60,7 @@ class UnusedStoreBase: public ASTWalker void operator()(Continue const&) override; protected: - using ActiveStores = std::map>; + using ActiveStores = std::map>; /// This function is called for a loop that is nested too deep to avoid /// horrible runtime and should just resolve the situation in a pragmatic diff --git a/libyul/optimiser/UnusedStoreEliminator.cpp b/libyul/optimiser/UnusedStoreEliminator.cpp index 6a0ab1518d08..d049f59a0262 100644 --- a/libyul/optimiser/UnusedStoreEliminator.cpp +++ b/libyul/optimiser/UnusedStoreEliminator.cpp @@ -51,22 +51,22 @@ static std::string const thirtyTwo{"@ 32"}; void UnusedStoreEliminator::run(OptimiserStepContext& _context, Block& _ast) { - std::map functionSideEffects = SideEffectsPropagator::sideEffects( + std::map functionSideEffects = SideEffectsPropagator::sideEffects( _context.dialect, CallGraphGenerator::callGraph(_ast) ); SSAValueTracker ssaValues; ssaValues(_ast); - std::map values; + std::map values; for (auto const& [name, expression]: ssaValues.values()) values[name] = AssignedValue{expression, {}}; Expression const zeroLiteral{Literal{{}, LiteralKind::Number, LiteralValue(u256{0}), {}}}; Expression const oneLiteral{Literal{{}, LiteralKind::Number, LiteralValue(u256{1}), {}}}; Expression const thirtyTwoLiteral{Literal{{}, LiteralKind::Number, LiteralValue(u256{32}), {}}}; - values[YulString{zero}] = AssignedValue{&zeroLiteral, {}}; - values[YulString{one}] = AssignedValue{&oneLiteral, {}}; - values[YulString{thirtyTwo}] = AssignedValue{&thirtyTwoLiteral, {}}; + values[YulName{zero}] = AssignedValue{&zeroLiteral, {}}; + values[YulName{one}] = AssignedValue{&oneLiteral, {}}; + values[YulName{thirtyTwo}] = AssignedValue{&thirtyTwoLiteral, {}}; bool const ignoreMemory = MSizeFinder::containsMSize(_context.dialect, _ast); UnusedStoreEliminator rse{ @@ -93,9 +93,9 @@ void UnusedStoreEliminator::run(OptimiserStepContext& _context, Block& _ast) UnusedStoreEliminator::UnusedStoreEliminator( Dialect const& _dialect, - std::map const& _functionSideEffects, - std::map _controlFlowSideEffects, - std::map const& _ssaValues, + std::map const& _functionSideEffects, + std::map _controlFlowSideEffects, + std::map const& _ssaValues, bool _ignoreMemory ): UnusedStoreBase(_dialect), @@ -228,7 +228,7 @@ std::vector UnusedStoreEliminator::operationsF { using evmasm::Instruction; - YulString functionName = _functionCall.functionName.name; + YulName functionName = _functionCall.functionName.name; SideEffects sideEffects; if (BuiltinFunction const* f = m_dialect.builtin(functionName)) sideEffects = f->sideEffects; @@ -263,8 +263,8 @@ std::vector UnusedStoreEliminator::operationsF if (_op.lengthConstant) switch (*_op.lengthConstant) { - case 1: ourOp.length = YulString(one); break; - case 32: ourOp.length = YulString(thirtyTwo); break; + case 1: ourOp.length = YulName(one); break; + case 32: ourOp.length = YulName(thirtyTwo); break; default: yulAssert(false); } return ourOp; @@ -435,7 +435,7 @@ void UnusedStoreEliminator::clearActive( activeStorageStores() = {}; } -std::optional UnusedStoreEliminator::identifierNameIfSSA(Expression const& _expression) const +std::optional UnusedStoreEliminator::identifierNameIfSSA(Expression const& _expression) const { if (Identifier const* identifier = std::get_if(&_expression)) if (m_ssaValues.count(identifier->name)) diff --git a/libyul/optimiser/UnusedStoreEliminator.h b/libyul/optimiser/UnusedStoreEliminator.h index 89dbabd78d2c..98023b64cfc6 100644 --- a/libyul/optimiser/UnusedStoreEliminator.h +++ b/libyul/optimiser/UnusedStoreEliminator.h @@ -64,9 +64,9 @@ class UnusedStoreEliminator: public UnusedStoreBase explicit UnusedStoreEliminator( Dialect const& _dialect, - std::map const& _functionSideEffects, - std::map _controlFlowSideEffects, - std::map const& _ssaValues, + std::map const& _functionSideEffects, + std::map _controlFlowSideEffects, + std::map const& _ssaValues, bool _ignoreMemory ); @@ -85,15 +85,15 @@ class UnusedStoreEliminator: public UnusedStoreBase Location location; Effect effect; /// Start of affected area. Unknown if not provided. - std::optional start; + std::optional start; /// Length of affected area, unknown if not provided. /// Unused for storage. - std::optional length; + std::optional length; }; private: - std::set& activeMemoryStores() { return m_activeStores["m"_yulstring]; } - std::set& activeStorageStores() { return m_activeStores["s"_yulstring]; } + std::set& activeMemoryStores() { return m_activeStores["m"_yulname]; } + std::set& activeStorageStores() { return m_activeStores["s"_yulname]; } void shortcutNestedLoop(ActiveStores const&) override { @@ -113,12 +113,12 @@ class UnusedStoreEliminator: public UnusedStoreBase void markActiveAsUsed(std::optional _onlyLocation = std::nullopt); void clearActive(std::optional _onlyLocation = std::nullopt); - std::optional identifierNameIfSSA(Expression const& _expression) const; + std::optional identifierNameIfSSA(Expression const& _expression) const; bool const m_ignoreMemory; - std::map const& m_functionSideEffects; - std::map m_controlFlowSideEffects; - std::map const& m_ssaValues; + std::map const& m_functionSideEffects; + std::map m_controlFlowSideEffects; + std::map const& m_ssaValues; std::map m_storeOperations; diff --git a/libyul/optimiser/VarNameCleaner.cpp b/libyul/optimiser/VarNameCleaner.cpp index b13dc8e6b49b..041ebdeaab23 100644 --- a/libyul/optimiser/VarNameCleaner.cpp +++ b/libyul/optimiser/VarNameCleaner.cpp @@ -34,7 +34,7 @@ using namespace solidity::yul; VarNameCleaner::VarNameCleaner( Block const& _ast, Dialect const& _dialect, - std::set _namesToKeep + std::set _namesToKeep ): m_dialect{_dialect}, m_namesToKeep{std::move(_namesToKeep)}, @@ -51,9 +51,9 @@ void VarNameCleaner::operator()(FunctionDefinition& _funDef) yulAssert(!m_insideFunction, ""); m_insideFunction = true; - std::set globalUsedNames = std::move(m_usedNames); + std::set globalUsedNames = std::move(m_usedNames); m_usedNames = m_namesToKeep; - std::map globalTranslatedNames; + std::map globalTranslatedNames; swap(globalTranslatedNames, m_translatedNames); renameVariables(_funDef.parameters); @@ -93,7 +93,7 @@ void VarNameCleaner::operator()(Identifier& _identifier) _identifier.name = name->second; } -YulString VarNameCleaner::findCleanName(YulString const& _name) const +YulName VarNameCleaner::findCleanName(YulName const& _name) const { auto newName = stripSuffix(_name); if (!isUsedName(newName)) @@ -102,24 +102,24 @@ YulString VarNameCleaner::findCleanName(YulString const& _name) const // create new name with suffix (by finding a free identifier) for (size_t i = 1; i < std::numeric_limits::max(); ++i) { - YulString newNameSuffixed = YulString{newName.str() + "_" + std::to_string(i)}; + YulName newNameSuffixed = YulName{newName.str() + "_" + std::to_string(i)}; if (!isUsedName(newNameSuffixed)) return newNameSuffixed; } yulAssert(false, "Exhausted by attempting to find an available suffix."); } -bool VarNameCleaner::isUsedName(YulString const& _name) const +bool VarNameCleaner::isUsedName(YulName const& _name) const { return isRestrictedIdentifier(m_dialect, _name) || m_usedNames.count(_name); } -YulString VarNameCleaner::stripSuffix(YulString const& _name) const +YulName VarNameCleaner::stripSuffix(YulName const& _name) const { static std::regex const suffixRegex("(_+[0-9]+)+$"); std::smatch suffixMatch; if (regex_search(_name.str(), suffixMatch, suffixRegex)) - return {YulString{suffixMatch.prefix().str()}}; + return {YulName{suffixMatch.prefix().str()}}; return _name; } diff --git a/libyul/optimiser/VarNameCleaner.h b/libyul/optimiser/VarNameCleaner.h index 7823e5716c28..bfb6cfb53369 100644 --- a/libyul/optimiser/VarNameCleaner.h +++ b/libyul/optimiser/VarNameCleaner.h @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include @@ -64,33 +64,33 @@ class VarNameCleaner: public ASTModifier VarNameCleaner( Block const& _ast, Dialect const& _dialect, - std::set _namesToKeep = {} + std::set _namesToKeep = {} ); /// Tries to rename a list of variables. void renameVariables(std::vector& _variables); /// @returns suffix-stripped name, if a suffix was detected, none otherwise. - YulString stripSuffix(YulString const& _name) const; + YulName stripSuffix(YulName const& _name) const; /// Looks out for a "clean name" the given @p name could be trimmed down to. /// @returns a trimmed down and "clean name" in case it found one, none otherwise. - YulString findCleanName(YulString const& name) const; + YulName findCleanName(YulName const& name) const; /// Tests whether a given name was already used within this pass /// or was set to be kept. - bool isUsedName(YulString const& _name) const; + bool isUsedName(YulName const& _name) const; Dialect const& m_dialect; /// These names will not be modified. - std::set m_namesToKeep; + std::set m_namesToKeep; /// Set of names that are in use. - std::set m_usedNames; + std::set m_usedNames; /// Maps old to new names. - std::map m_translatedNames; + std::map m_translatedNames; /// Whether the traverse is inside a function definition. /// Used to assert that a function definition cannot be inside another. diff --git a/test/libsolidity/MemoryGuardTest.cpp b/test/libsolidity/MemoryGuardTest.cpp index 6e44afccf4f7..77274200bbb3 100644 --- a/test/libsolidity/MemoryGuardTest.cpp +++ b/test/libsolidity/MemoryGuardTest.cpp @@ -75,7 +75,7 @@ TestCase::TestResult MemoryGuardTest::run(std::ostream& _stream, std::string con auto handleObject = [&](std::string const& _kind, Object const& _object) { m_obtainedResult += contractName + "(" + _kind + ") " + (findFunctionCalls( *_object.code, - "memoryguard"_yulstring + "memoryguard"_yulname ).empty() ? "false" : "true") + "\n"; }; handleObject("creation", *object); diff --git a/test/libyul/FunctionSideEffects.cpp b/test/libyul/FunctionSideEffects.cpp index a57ec9807843..f1bd0ea379d1 100644 --- a/test/libyul/FunctionSideEffects.cpp +++ b/test/libyul/FunctionSideEffects.cpp @@ -87,7 +87,7 @@ TestCase::TestResult FunctionSideEffects::run(std::ostream& _stream, std::string if (!obj.code) BOOST_THROW_EXCEPTION(std::runtime_error("Parsing input failed.")); - std::map functionSideEffects = SideEffectsPropagator::sideEffects( + std::map functionSideEffects = SideEffectsPropagator::sideEffects( EVMDialect::strictAssemblyForEVMObjects(langutil::EVMVersion()), CallGraphGenerator::callGraph(*obj.code) ); diff --git a/test/libyul/KnowledgeBaseTest.cpp b/test/libyul/KnowledgeBaseTest.cpp index b1dd0e6d19c5..6a9d3e6da8be 100644 --- a/test/libyul/KnowledgeBaseTest.cpp +++ b/test/libyul/KnowledgeBaseTest.cpp @@ -49,7 +49,7 @@ class KnowledgeBaseTest BOOST_REQUIRE(m_object && errorList.empty() && m_object->code); NameDispenser dispenser(m_dialect, *m_object->code); - std::set reserved; + std::set reserved; OptimiserStepContext context{m_dialect, dispenser, reserved, 0}; CommonSubexpressionEliminator::run(context, *m_object->code); @@ -57,13 +57,13 @@ class KnowledgeBaseTest for (auto const& [name, expression]: m_ssaValues.values()) m_values[name].value = expression; - return KnowledgeBase([this](YulString _var) { return util::valueOrNullptr(m_values, _var); }); + return KnowledgeBase([this](YulName _var) { return util::valueOrNullptr(m_values, _var); }); } EVMDialect m_dialect{EVMVersion{}, true}; std::shared_ptr m_object; SSAValueTracker m_ssaValues; - std::map m_values; + std::map m_values; }; BOOST_FIXTURE_TEST_SUITE(KnowledgeBase, KnowledgeBaseTest) @@ -79,14 +79,14 @@ BOOST_AUTO_TEST_CASE(basic) let e := sub(a, b) })"); - BOOST_CHECK(!kb.knownToBeDifferent("a"_yulstring, "b"_yulstring)); + BOOST_CHECK(!kb.knownToBeDifferent("a"_yulname, "b"_yulname)); // This only works if the variable names are the same. // It assumes that SSA+CSE+Simplifier actually replaces the variables. - BOOST_CHECK(!kb.valueIfKnownConstant("a"_yulstring)); - BOOST_CHECK(kb.valueIfKnownConstant("zero"_yulstring) == u256(0)); - BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulstring, "b"_yulstring) == u256(0)); - BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulstring, "c"_yulstring) == u256(0)); - BOOST_CHECK(kb.valueIfKnownConstant("e"_yulstring) == u256(0)); + BOOST_CHECK(!kb.valueIfKnownConstant("a"_yulname)); + BOOST_CHECK(kb.valueIfKnownConstant("zero"_yulname) == u256(0)); + BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulname, "b"_yulname) == u256(0)); + BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulname, "c"_yulname) == u256(0)); + BOOST_CHECK(kb.valueIfKnownConstant("e"_yulname) == u256(0)); } BOOST_AUTO_TEST_CASE(difference) @@ -99,31 +99,21 @@ BOOST_AUTO_TEST_CASE(difference) let e := sub(c, 12) })"); - BOOST_CHECK( - kb.differenceIfKnownConstant("c"_yulstring, "b"_yulstring) == + BOOST_CHECK(kb.differenceIfKnownConstant("c"_yulname, "b"_yulname) == u256(20) ); - BOOST_CHECK( - kb.differenceIfKnownConstant("b"_yulstring, "c"_yulstring) == + BOOST_CHECK(kb.differenceIfKnownConstant("b"_yulname, "c"_yulname) == u256(-20) ); - BOOST_CHECK(!kb.knownToBeDifferentByAtLeast32("b"_yulstring, "c"_yulstring)); - BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulstring, "d"_yulstring)); - BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("a"_yulstring, "b"_yulstring)); - BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulstring, "a"_yulstring)); - - BOOST_CHECK( - kb.differenceIfKnownConstant("e"_yulstring, "a"_yulstring) == u256(208) - ); - BOOST_CHECK( - kb.differenceIfKnownConstant("e"_yulstring, "b"_yulstring) == u256(8) - ); - BOOST_CHECK( - kb.differenceIfKnownConstant("a"_yulstring, "e"_yulstring) == u256(-208) - ); - BOOST_CHECK( - kb.differenceIfKnownConstant("b"_yulstring, "e"_yulstring) == u256(-8) - ); + BOOST_CHECK(!kb.knownToBeDifferentByAtLeast32("b"_yulname, "c"_yulname)); + BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulname, "d"_yulname)); + BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("a"_yulname, "b"_yulname)); + BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulname, "a"_yulname)); + + BOOST_CHECK(kb.differenceIfKnownConstant("e"_yulname, "a"_yulname) == u256(208)); + BOOST_CHECK(kb.differenceIfKnownConstant("e"_yulname, "b"_yulname) == u256(8)); + BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulname, "e"_yulname) == u256(-208)); + BOOST_CHECK(kb.differenceIfKnownConstant("b"_yulname, "e"_yulname) == u256(-8)); } diff --git a/test/libyul/Parser.cpp b/test/libyul/Parser.cpp index ca8784ddb6ef..faa6c6105f2d 100644 --- a/test/libyul/Parser.cpp +++ b/test/libyul/Parser.cpp @@ -135,11 +135,11 @@ BOOST_AUTO_TEST_CASE(builtins_analysis) { struct SimpleDialect: public Dialect { - BuiltinFunction const* builtin(YulString _name) const override + BuiltinFunction const* builtin(YulName _name) const override { - return _name == "builtin"_yulstring ? &f : nullptr; + return _name == "builtin"_yulname ? &f : nullptr; } - BuiltinFunction f{"builtin"_yulstring, std::vector(2), std::vector(3), {}, {}, false, {}}; + BuiltinFunction f{"builtin"_yulname, std::vector(2), std::vector(3), {}, {}, false, {}}; }; SimpleDialect dialect; diff --git a/test/libyul/StackShufflingTest.cpp b/test/libyul/StackShufflingTest.cpp index e53eeafbb03c..2da445dd4557 100644 --- a/test/libyul/StackShufflingTest.cpp +++ b/test/libyul/StackShufflingTest.cpp @@ -56,7 +56,7 @@ bool StackShufflingTest::parse(std::string const& _source) scanner.next(); std::string functionName = scanner.currentLiteral(); auto call = yul::FunctionCall{ - {}, yul::Identifier{{}, YulString(functionName)}, {} + {}, yul::Identifier{{}, YulName(functionName)}, {} }; stack.emplace_back(FunctionCallReturnLabelSlot{ m_functions.insert( @@ -78,7 +78,7 @@ bool StackShufflingTest::parse(std::string const& _source) scanner.next(); std::string functionName = scanner.currentLiteral(); auto call = yul::FunctionCall{ - {}, yul::Identifier{{}, YulString(functionName)}, {} + {}, yul::Identifier{{}, YulName(functionName)}, {} }; expectToken(Token::Comma); scanner.next(); @@ -102,7 +102,7 @@ bool StackShufflingTest::parse(std::string const& _source) expectToken(Token::LBrack); scanner.next(); // read number of ghost variables as ghostVariableId std::string ghostVariableId = scanner.currentLiteral(); - Scope::Variable ghostVar = Scope::Variable{""_yulstring, YulString(literal + "[" + ghostVariableId + "]")}; + Scope::Variable ghostVar = Scope::Variable{""_yulname, YulName(literal + "[" + ghostVariableId + "]")}; stack.emplace_back(VariableSlot{ m_variables.insert(std::make_pair(ghostVar.name, ghostVar)).first->second }); @@ -110,7 +110,7 @@ bool StackShufflingTest::parse(std::string const& _source) } else { - Scope::Variable var = Scope::Variable{""_yulstring, YulString(literal)}; + Scope::Variable var = Scope::Variable{""_yulname, YulName(literal)}; stack.emplace_back(VariableSlot{ m_variables.insert( make_pair(literal, var) diff --git a/test/libyul/StackShufflingTest.h b/test/libyul/StackShufflingTest.h index 75715d25b90f..2e2dd12ad325 100644 --- a/test/libyul/StackShufflingTest.h +++ b/test/libyul/StackShufflingTest.h @@ -41,7 +41,7 @@ class StackShufflingTest: public TestCase Stack m_sourceStack; Stack m_targetStack; - std::map m_functions; - std::map m_variables; + std::map m_functions; + std::map m_variables; }; } diff --git a/test/libyul/YulOptimizerTestCommon.cpp b/test/libyul/YulOptimizerTestCommon.cpp index 091a9a0b6cff..80746c93ba9f 100644 --- a/test/libyul/YulOptimizerTestCommon.cpp +++ b/test/libyul/YulOptimizerTestCommon.cpp @@ -89,7 +89,7 @@ YulOptimizerTestCommon::YulOptimizerTestCommon( disambiguate(); NameDisplacer{ *m_nameDispenser, - {"illegal1"_yulstring, "illegal2"_yulstring, "illegal3"_yulstring, "illegal4"_yulstring, "illegal5"_yulstring} + {"illegal1"_yulname, "illegal2"_yulname, "illegal3"_yulname, "illegal4"_yulname, "illegal5"_yulname} }(*m_ast); }}, {"blockFlattener", [&]() { @@ -348,11 +348,11 @@ YulOptimizerTestCommon::YulOptimizerTestCommon( // Mark all variables with a name starting with "$" for escalation to memory. struct FakeUnreachableGenerator: ASTWalker { - std::map> fakeUnreachables; + std::map> fakeUnreachables; using ASTWalker::operator(); void operator()(FunctionDefinition const& _function) override { - YulString originalFunctionName = m_currentFunction; + YulName originalFunctionName = m_currentFunction; m_currentFunction = _function.name; for (TypedName const& _argument: _function.parameters) visitVariableName(_argument.name); @@ -361,7 +361,7 @@ YulOptimizerTestCommon::YulOptimizerTestCommon( ASTWalker::operator()(_function); m_currentFunction = originalFunctionName; } - void visitVariableName(YulString _var) + void visitVariableName(YulName _var) { if (!_var.empty() && _var.str().front() == '$') if (!util::contains(fakeUnreachables[m_currentFunction], _var)) @@ -378,7 +378,7 @@ YulOptimizerTestCommon::YulOptimizerTestCommon( visitVariableName(_identifier.name); ASTWalker::operator()(_identifier); } - YulString m_currentFunction = YulString{}; + YulName m_currentFunction = YulName{}; }; FakeUnreachableGenerator fakeUnreachableGenerator; fakeUnreachableGenerator(*m_ast); diff --git a/test/libyul/YulOptimizerTestCommon.h b/test/libyul/YulOptimizerTestCommon.h index 3dce998c56cc..0a5d63320d6d 100644 --- a/test/libyul/YulOptimizerTestCommon.h +++ b/test/libyul/YulOptimizerTestCommon.h @@ -21,7 +21,7 @@ #include #include -#include +#include #include #include @@ -63,7 +63,7 @@ class YulOptimizerTestCommon std::string m_optimizerStep; Dialect const* m_dialect = nullptr; - std::set m_reservedIdentifiers; + std::set m_reservedIdentifiers; std::unique_ptr m_nameDispenser; std::unique_ptr m_context; diff --git a/test/tools/yulInterpreter/Inspector.h b/test/tools/yulInterpreter/Inspector.h index f4518c7087d3..903ebc1142ea 100644 --- a/test/tools/yulInterpreter/Inspector.h +++ b/test/tools/yulInterpreter/Inspector.h @@ -53,13 +53,13 @@ class Inspector * @returns NodeAction::RunNode if the current AST node (and all children nodes!) should be * processed without stopping, else NodeAction::StepThroughNode. */ - NodeAction queryUser(langutil::DebugData const& _data, std::map const& _variables); + NodeAction queryUser(langutil::DebugData const& _data, std::map const& _variables); void stepMode(NodeAction _action) { m_stepMode = _action; } std::string const& source() const { return m_source; } - void interactiveVisit(langutil::DebugData const& _debugData, std::map const& _variables, std::function _visitNode) + void interactiveVisit(langutil::DebugData const& _debugData, std::map const& _variables, std::function _visitNode) { Inspector::NodeAction action = queryUser(_debugData, _variables); @@ -116,7 +116,7 @@ class InspectedInterpreter: public Interpreter Scope& _scope, bool _disableExternalCalls, bool _disableMemoryTracing, - std::map _variables = {} + std::map _variables = {} ): Interpreter(_state, _dialect, _scope, _disableExternalCalls, _disableMemoryTracing, _variables), m_inspector(_inspector) @@ -160,7 +160,7 @@ class InspectedExpressionEvaluator: public ExpressionEvaluator InterpreterState& _state, Dialect const& _dialect, Scope& _scope, - std::map const& _variables, + std::map const& _variables, bool _disableExternalCalls, bool _disableMemoryTrace ): @@ -180,7 +180,7 @@ class InspectedExpressionEvaluator: public ExpressionEvaluator void operator()(Identifier const& _node) override { helper(_node); } void operator()(FunctionCall const& _node) override { helper(_node); } protected: - std::unique_ptr makeInterpreterCopy(std::map _variables = {}) const override + std::unique_ptr makeInterpreterCopy(std::map _variables = {}) const override { return std::make_unique( m_inspector, diff --git a/test/tools/yulInterpreter/Interpreter.cpp b/test/tools/yulInterpreter/Interpreter.cpp index 6a0f3a9997ef..21e97f0769c8 100644 --- a/test/tools/yulInterpreter/Interpreter.cpp +++ b/test/tools/yulInterpreter/Interpreter.cpp @@ -131,7 +131,7 @@ void Interpreter::operator()(Assignment const& _assignment) solAssert(values.size() == _assignment.variableNames.size(), ""); for (size_t i = 0; i < values.size(); ++i) { - YulString varName = _assignment.variableNames.at(i).name; + YulName varName = _assignment.variableNames.at(i).name; solAssert(m_variables.count(varName), ""); m_variables[varName] = values.at(i); } @@ -146,7 +146,7 @@ void Interpreter::operator()(VariableDeclaration const& _declaration) solAssert(values.size() == _declaration.variables.size(), ""); for (size_t i = 0; i < values.size(); ++i) { - YulString varName = _declaration.variables.at(i).name; + YulName varName = _declaration.variables.at(i).name; solAssert(!m_variables.count(varName), ""); m_variables[varName] = values.at(i); m_scope->names.emplace(varName, nullptr); @@ -343,7 +343,7 @@ void ExpressionEvaluator::operator()(FunctionCall const& _funCall) FunctionDefinition const* fun = scope->names.at(_funCall.functionName.name); yulAssert(fun, "Function not found."); yulAssert(m_values.size() == fun->parameters.size(), ""); - std::map variables; + std::map variables; for (size_t i = 0; i < fun->parameters.size(); ++i) variables[fun->parameters.at(i).name] = m_values.at(i); for (size_t i = 0; i < fun->returnVariables.size(); ++i) diff --git a/test/tools/yulInterpreter/Interpreter.h b/test/tools/yulInterpreter/Interpreter.h index 23a98ca5c350..356a190709a7 100644 --- a/test/tools/yulInterpreter/Interpreter.h +++ b/test/tools/yulInterpreter/Interpreter.h @@ -145,7 +145,7 @@ struct InterpreterState struct Scope { /// Used for variables and functions. Value is nullptr for variables. - std::map names; + std::map names; std::map> subScopes; Scope* parent = nullptr; }; @@ -174,7 +174,7 @@ class Interpreter: public ASTWalker Scope& _scope, bool _disableExternalCalls, bool _disableMemoryTracing, - std::map _variables = {} + std::map _variables = {} ): m_dialect(_dialect), m_state(_state), @@ -200,7 +200,7 @@ class Interpreter: public ASTWalker bytes returnData() const { return m_state.returndata; } std::vector const& trace() const { return m_state.trace; } - u256 valueOfVariable(YulString _name) const { return m_variables.at(_name); } + u256 valueOfVariable(YulName _name) const { return m_variables.at(_name); } protected: /// Asserts that the expression evaluates to exactly one value and returns it. @@ -218,7 +218,7 @@ class Interpreter: public ASTWalker Dialect const& m_dialect; InterpreterState& m_state; /// Values of variables. - std::map m_variables; + std::map m_variables; Scope* m_scope; /// If not set, external calls (e.g. using `call()`) to the same contract /// are evaluated in a new parser instance. @@ -236,7 +236,7 @@ class ExpressionEvaluator: public ASTWalker InterpreterState& _state, Dialect const& _dialect, Scope& _scope, - std::map const& _variables, + std::map const& _variables, bool _disableExternalCalls, bool _disableMemoryTrace ): @@ -259,7 +259,7 @@ class ExpressionEvaluator: public ASTWalker protected: void runExternalCall(evmasm::Instruction _instruction); - virtual std::unique_ptr makeInterpreterCopy(std::map _variables = {}) const + virtual std::unique_ptr makeInterpreterCopy(std::map _variables = {}) const { return std::make_unique( m_state, @@ -298,7 +298,7 @@ class ExpressionEvaluator: public ASTWalker InterpreterState& m_state; Dialect const& m_dialect; /// Values of variables. - std::map const& m_variables; + std::map const& m_variables; Scope& m_scope; /// Current value of the expression std::vector m_values; diff --git a/test/tools/yulopti.cpp b/test/tools/yulopti.cpp index d16b1da1969b..7e81cbf7e34e 100644 --- a/test/tools/yulopti.cpp +++ b/test/tools/yulopti.cpp @@ -245,7 +245,7 @@ class YulOpti std::shared_ptr m_ast; Dialect const& m_dialect{EVMDialect::strictAssemblyForEVMObjects(EVMVersion{})}; std::unique_ptr m_analysisInfo; - std::set const m_reservedIdentifiers = {}; + std::set const m_reservedIdentifiers = {}; NameDispenser m_nameDispenser{m_dialect, m_reservedIdentifiers}; OptimiserStepContext m_context{ m_dialect, diff --git a/tools/yulPhaser/Program.cpp b/tools/yulPhaser/Program.cpp index 1586f602064b..0cb22242d0fe 100644 --- a/tools/yulPhaser/Program.cpp +++ b/tools/yulPhaser/Program.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include #include @@ -175,7 +175,7 @@ std::unique_ptr Program::disambiguateAST( AsmAnalysisInfo const& _analysisInfo ) { - std::set const externallyUsedIdentifiers = {}; + std::set const externallyUsedIdentifiers = {}; Disambiguator disambiguator(_dialect, _analysisInfo, externallyUsedIdentifiers); return std::make_unique(std::get(disambiguator(_ast))); @@ -190,7 +190,7 @@ std::unique_ptr Program::applyOptimisationSteps( { // An empty set of reserved identifiers. It could be a constructor parameter but I don't // think it would be useful in this tool. Other tools (like yulopti) have it empty too. - std::set const externallyUsedIdentifiers = {}; + std::set const externallyUsedIdentifiers = {}; OptimiserStepContext context{ _dialect, _nameDispenser,