From 1ebdab43d88fdf97d47bc6355d21595125d9a1a2 Mon Sep 17 00:00:00 2001 From: Jun Zhang Date: Wed, 23 Aug 2023 10:24:09 +0800 Subject: [PATCH 1/3] Purge using namespace std from libyul/backends Signed-off-by: Jun Zhang --- libyul/backends/evm/AsmCodeGen.cpp | 1 - libyul/backends/evm/ConstantOptimiser.cpp | 15 ++-- .../backends/evm/ControlFlowGraphBuilder.cpp | 47 +++++++------ libyul/backends/evm/EVMCodeTransform.cpp | 51 +++++++------- libyul/backends/evm/EVMDialect.cpp | 68 +++++++++--------- libyul/backends/evm/EVMMetrics.cpp | 5 +- libyul/backends/evm/EVMObjectCompiler.cpp | 5 +- libyul/backends/evm/EthAssemblyAdapter.cpp | 11 ++- libyul/backends/evm/NoOutputAssembly.cpp | 7 +- .../evm/OptimizedEVMCodeTransform.cpp | 33 +++++---- libyul/backends/evm/StackLayoutGenerator.cpp | 69 +++++++++---------- scripts/check_style.sh | 1 + 12 files changed, 152 insertions(+), 161 deletions(-) diff --git a/libyul/backends/evm/AsmCodeGen.cpp b/libyul/backends/evm/AsmCodeGen.cpp index c4d276fa1..645d1fd87 100644 --- a/libyul/backends/evm/AsmCodeGen.cpp +++ b/libyul/backends/evm/AsmCodeGen.cpp @@ -28,7 +28,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; diff --git a/libyul/backends/evm/ConstantOptimiser.cpp b/libyul/backends/evm/ConstantOptimiser.cpp index 59e987b69..c5a33e52f 100644 --- a/libyul/backends/evm/ConstantOptimiser.cpp +++ b/libyul/backends/evm/ConstantOptimiser.cpp @@ -30,7 +30,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -48,9 +47,9 @@ struct MiniEVMInterpreter return std::visit(*this, _expr); } - u256 eval(evmasm::Instruction _instr, vector const& _arguments) + u256 eval(evmasm::Instruction _instr, std::vector const& _arguments) { - vector args; + std::vector args; for (auto const& arg: _arguments) args.emplace_back(eval(arg)); switch (_instr) @@ -92,7 +91,7 @@ struct MiniEVMInterpreter void ConstantOptimiser::visit(Expression& _e) { - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) { Literal const& literal = std::get(_e); if (literal.kind != LiteralKind::Number) @@ -115,7 +114,7 @@ Expression const* RepresentationFinder::tryFindRepresentation(u256 const& _value return nullptr; Representation const& repr = findRepresentation(_value); - if (holds_alternative(*repr.expression)) + if (std::holds_alternative(*repr.expression)) return nullptr; else return repr.expression.get(); @@ -180,7 +179,7 @@ Representation const& RepresentationFinder::findRepresentation(u256 const& _valu Representation RepresentationFinder::represent(u256 const& _value) const { Representation repr; - repr.expression = make_unique(Literal{m_debugData, LiteralKind::Number, YulString{formatNumber(_value)}, {}}); + repr.expression = std::make_unique(Literal{m_debugData, LiteralKind::Number, YulString{formatNumber(_value)}, {}}); repr.cost = m_meter.costs(*repr.expression); return repr; } @@ -191,7 +190,7 @@ Representation RepresentationFinder::represent( ) const { Representation repr; - repr.expression = make_unique(FunctionCall{ + repr.expression = std::make_unique(FunctionCall{ m_debugData, Identifier{m_debugData, _instruction}, {ASTCopier{}.translate(*_argument.expression)} @@ -207,7 +206,7 @@ Representation RepresentationFinder::represent( ) const { Representation repr; - repr.expression = make_unique(FunctionCall{ + repr.expression = std::make_unique(FunctionCall{ m_debugData, Identifier{m_debugData, _instruction}, {ASTCopier{}.translate(*_arg1.expression), ASTCopier{}.translate(*_arg2.expression)} diff --git a/libyul/backends/evm/ControlFlowGraphBuilder.cpp b/libyul/backends/evm/ControlFlowGraphBuilder.cpp index d08dcf16c..9a0a73b35 100644 --- a/libyul/backends/evm/ControlFlowGraphBuilder.cpp +++ b/libyul/backends/evm/ControlFlowGraphBuilder.cpp @@ -45,7 +45,6 @@ using namespace solidity; using namespace solidity::yul; -using namespace std; namespace { @@ -82,15 +81,15 @@ void cleanUnreachable(CFG& _cfg) /// Sets the ``recursive`` member to ``true`` for all recursive function calls. void markRecursiveCalls(CFG& _cfg) { - map> callsPerBlock; + std::map> callsPerBlock; auto const& findCalls = [&](CFG::BasicBlock* _block) { if (auto* calls = util::valueOrNullptr(callsPerBlock, _block)) return *calls; - vector& calls = callsPerBlock[_block]; + std::vector& calls = callsPerBlock[_block]; util::BreadthFirstSearch{{_block}}.run([&](CFG::BasicBlock* _block, auto _addChild) { for (auto& operation: _block->operations) - if (auto* functionCall = get_if(&operation.operation)) + if (auto* functionCall = std::get_if(&operation.operation)) calls.emplace_back(functionCall); std::visit(util::GenericVisitor{ [&](CFG::BasicBlock::MainExit const&) {}, @@ -131,7 +130,7 @@ void markRecursiveCalls(CFG& _cfg) /// Entering such a block means that control flow will never return to a previously visited block. void markStartsOfSubGraphs(CFG& _cfg) { - vector entries; + std::vector entries; entries.emplace_back(_cfg.entry); for (auto&& functionInfo: _cfg.functionInfo | ranges::views::values) entries.emplace_back(functionInfo.entry); @@ -141,17 +140,17 @@ void markStartsOfSubGraphs(CFG& _cfg) * Detect bridges following Algorithm 1 in https://arxiv.org/pdf/2108.07346.pdf * and mark the bridge targets as starts of sub-graphs. */ - set visited; - map disc; - map low; - map parent; + std::set visited; + std::map disc; + std::map low; + std::map parent; size_t time = 0; auto dfs = [&](CFG::BasicBlock* _u, auto _recurse) -> void { visited.insert(_u); disc[_u] = low[_u] = time; time++; - vector children = _u->entries; + std::vector children = _u->entries; visit(util::GenericVisitor{ [&](CFG::BasicBlock::Jump const& _jump) { children.emplace_back(_jump.target); @@ -171,7 +170,7 @@ void markStartsOfSubGraphs(CFG& _cfg) { parent[v] = _u; _recurse(v, _recurse); - low[_u] = min(low[_u], low[v]); + low[_u] = std::min(low[_u], low[v]); if (low[v] > disc[_u]) { // _u <-> v is a cut edge in the undirected graph @@ -186,7 +185,7 @@ void markStartsOfSubGraphs(CFG& _cfg) } } else if (v != parent[_u]) - low[_u] = min(low[_u], disc[v]); + low[_u] = std::min(low[_u], disc[v]); }; dfs(entry, dfs); } @@ -234,7 +233,7 @@ std::unique_ptr ControlFlowGraphBuilder::build( ControlFlowGraphBuilder::ControlFlowGraphBuilder( CFG& _graph, AsmAnalysisInfo const& _analysisInfo, - map const& _functionSideEffects, + std::map const& _functionSideEffects, Dialect const& _dialect ): m_graph(_graph), @@ -271,7 +270,7 @@ void ControlFlowGraphBuilder::operator()(VariableDeclaration const& _varDecl) yulAssert(m_currentBlock, ""); auto declaredVariables = _varDecl.variables | ranges::views::transform([&](TypedName const& _var) { return VariableSlot{lookupVariable(_var.name), _var.debugData}; - }) | ranges::to>; + }) | ranges::to>; Stack input; if (_varDecl.value) input = visitAssignmentRightHandSide(*_varDecl.value, declaredVariables.size()); @@ -287,7 +286,7 @@ void ControlFlowGraphBuilder::operator()(Assignment const& _assignment) { auto assignedVariables = _assignment.variableNames | ranges::views::transform([&](Identifier const& _var) { return VariableSlot{lookupVariable(_var.name), _var.debugData}; - }) | ranges::to>; + }) | ranges::to>; Stack input = visitAssignmentRightHandSide(*_assignment.value, assignedVariables.size()); yulAssert(m_currentBlock); @@ -314,7 +313,7 @@ void ControlFlowGraphBuilder::operator()(Block const& _block) { ScopedSaveAndRestore saveScope(m_scope, m_info.scopes.at(&_block).get()); for (auto const& statement: _block.statements) - if (auto const* function = get_if(&statement)) + if (auto const* function = std::get_if(&statement)) registerFunction(*function); for (auto const& statement: _block.statements) std::visit(*this, statement); @@ -334,10 +333,10 @@ void ControlFlowGraphBuilder::operator()(If const& _if) void ControlFlowGraphBuilder::operator()(Switch const& _switch) { yulAssert(m_currentBlock, ""); - shared_ptr preSwitchDebugData = debugDataOf(_switch); + std::shared_ptr preSwitchDebugData = debugDataOf(_switch); auto ghostVariableId = m_graph.ghostVariables.size(); - YulString ghostVariableName("GHOST[" + to_string(ghostVariableId) + "]"); + YulString ghostVariableName("GHOST[" + std::to_string(ghostVariableId) + "]"); auto& ghostVar = m_graph.ghostVariables.emplace_back(Scope::Variable{""_yulstring, ghostVariableName}); // Artificially generate: @@ -394,12 +393,12 @@ void ControlFlowGraphBuilder::operator()(Switch const& _switch) void ControlFlowGraphBuilder::operator()(ForLoop const& _loop) { - shared_ptr preLoopDebugData = debugDataOf(_loop); + std::shared_ptr preLoopDebugData = debugDataOf(_loop); ScopedSaveAndRestore scopeRestore(m_scope, m_info.scopes.at(&_loop.pre).get()); (*this)(_loop.pre); std::optional constantCondition; - if (auto const* literalCondition = get_if(_loop.condition.get())) + if (auto const* literalCondition = std::get_if(_loop.condition.get())) constantCondition = valueOfLiteral(*literalCondition) != 0; CFG::BasicBlock& loopCondition = m_graph.makeBlock(debugDataOf(*_loop.condition)); @@ -497,13 +496,13 @@ void ControlFlowGraphBuilder::registerFunction(FunctionDefinition const& _functi std::get(virtualFunctionScope->identifiers.at(_param.name)), _param.debugData }; - }) | ranges::to, + }) | ranges::to, _functionDefinition.returnVariables | ranges::views::transform([&](auto const& _retVar) { return VariableSlot{ std::get(virtualFunctionScope->identifiers.at(_retVar.name)), _retVar.debugData }; - }) | ranges::to, + }) | ranges::to, {}, m_functionSideEffects.at(&_functionDefinition).canContinue })).second; @@ -609,7 +608,7 @@ Scope::Variable const& ControlFlowGraphBuilder::lookupVariable(YulString _name) } void ControlFlowGraphBuilder::makeConditionalJump( - shared_ptr _debugData, + std::shared_ptr _debugData, StackSlot _condition, CFG::BasicBlock& _nonZero, CFG::BasicBlock& _zero @@ -628,7 +627,7 @@ void ControlFlowGraphBuilder::makeConditionalJump( } void ControlFlowGraphBuilder::jump( - shared_ptr _debugData, + std::shared_ptr _debugData, CFG::BasicBlock& _target, bool backwards ) diff --git a/libyul/backends/evm/EVMCodeTransform.cpp b/libyul/backends/evm/EVMCodeTransform.cpp index 8a268675c..50e48f768 100644 --- a/libyul/backends/evm/EVMCodeTransform.cpp +++ b/libyul/backends/evm/EVMCodeTransform.cpp @@ -42,7 +42,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -56,9 +55,9 @@ CodeTransform::CodeTransform( BuiltinContext& _builtinContext, ExternalIdentifierAccess::CodeGenerator _identifierAccessCodeGen, UseNamedLabels _useNamedLabelsForFunctions, - shared_ptr _context, - vector _delayedReturnVariables, - optional _functionExitLabel + std::shared_ptr _context, + std::vector _delayedReturnVariables, + std::optional _functionExitLabel ): m_assembly(_assembly), m_info(_analysisInfo), @@ -74,7 +73,7 @@ CodeTransform::CodeTransform( if (!m_context) { // initialize - m_context = make_shared(); + m_context = std::make_shared(); if (m_allowStackOpt) m_context->variableReferences = VariableReferenceCounter::run(m_info, _block); } @@ -103,7 +102,7 @@ void CodeTransform::freeUnusedVariables(bool _popUnusedSlotsAtStackTop) return; for (auto const& identifier: m_scope->identifiers) - if (Scope::Variable const* var = get_if(&identifier.second)) + if (Scope::Variable const* var = std::get_if(&identifier.second)) if (m_variablesScheduledForDeletion.count(var)) deleteVariable(*var); // Directly in a function body block, we can also delete the function arguments, @@ -112,7 +111,7 @@ void CodeTransform::freeUnusedVariables(bool _popUnusedSlotsAtStackTop) // effect, so we only do it before that. if (!returnVariablesAndFunctionExitAreSetup() && !m_scope->functionScope && m_scope->superScope && m_scope->superScope->functionScope) for (auto const& identifier: m_scope->superScope->identifiers) - if (Scope::Variable const* var = get_if(&identifier.second)) + if (Scope::Variable const* var = std::get_if(&identifier.second)) if (m_variablesScheduledForDeletion.count(var)) deleteVariable(*var); @@ -317,7 +316,7 @@ void CodeTransform::operator()(Switch const& _switch) { visitExpression(*_switch.expression); int expressionHeight = m_assembly.stackHeight(); - map caseBodies; + std::map caseBodies; AbstractAssembly::LabelID end = m_assembly.newLabelId(); for (Case const& c: _switch.cases) { @@ -447,7 +446,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function) // This vector holds the desired target positions of all stack slots and is // modified parallel to the actual stack. - vector stackLayout(static_cast(m_assembly.stackHeight()), -1); + std::vector stackLayout(static_cast(m_assembly.stackHeight()), -1); stackLayout[0] = static_cast(_function.returnVariables.size()); // Move return label to the top for (auto&& [n, returnVariable]: ranges::views::enumerate(_function.returnVariables)) stackLayout.at(m_context->variableStackHeights.at( @@ -463,7 +462,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function) "The function " + _function.name.str() + " has " + - to_string(stackLayout.size() - 17) + + std::to_string(stackLayout.size() - 17) + " parameters or return variables too many to fit the stack size." ); stackError(std::move(error), m_assembly.stackHeight() - static_cast(_function.parameters.size())); @@ -479,7 +478,7 @@ void CodeTransform::operator()(FunctionDefinition const& _function) else { m_assembly.appendInstruction(evmasm::swapInstruction(static_cast(stackLayout.size()) - static_cast(stackLayout.back()) - 1u)); - swap(stackLayout[static_cast(stackLayout.back())], stackLayout.back()); + std::swap(stackLayout[static_cast(stackLayout.back())], stackLayout.back()); } for (size_t i = 0; i < stackLayout.size(); ++i) yulAssert(i == static_cast(stackLayout[i]), "Error reshuffling stack."); @@ -571,7 +570,7 @@ void CodeTransform::operator()(Block const& _block) m_scope = m_info.scopes.at(&_block).get(); for (auto const& statement: _block.statements) - if (auto function = get_if(&statement)) + if (auto function = std::get_if(&statement)) createFunctionEntryID(*function); int blockStartStackHeight = m_assembly.stackHeight(); @@ -579,7 +578,7 @@ void CodeTransform::operator()(Block const& _block) bool isOutermostFunctionBodyBlock = m_scope && m_scope->superScope && m_scope->superScope->functionScope; bool performValidation = !m_allowStackOpt || !isOutermostFunctionBodyBlock; - finalizeBlock(_block, performValidation ? make_optional(blockStartStackHeight) : nullopt); + finalizeBlock(_block, performValidation ? std::make_optional(blockStartStackHeight) : std::nullopt); m_scope = originalScope; } @@ -588,7 +587,7 @@ void CodeTransform::createFunctionEntryID(FunctionDefinition const& _function) Scope::Function& scopeFunction = std::get(m_scope->identifiers.at(_function.name)); yulAssert(!m_context->functionEntryIDs.count(&scopeFunction), ""); - optional astID; + std::optional astID; if (_function.debugData) astID = _function.debugData->astID; @@ -659,16 +658,16 @@ void CodeTransform::setupReturnVariablesAndFunctionExit() namespace { -bool statementNeedsReturnVariableSetup(Statement const& _statement, vector const& _returnVariables) +bool statementNeedsReturnVariableSetup(Statement const& _statement, std::vector const& _returnVariables) { - if (holds_alternative(_statement)) + if (std::holds_alternative(_statement)) return true; if ( - holds_alternative(_statement) || - holds_alternative(_statement) + std::holds_alternative(_statement) || + std::holds_alternative(_statement) ) { - map references = VariableReferencesCounter::countReferences(_statement); + std::map references = VariableReferencesCounter::countReferences(_statement); auto isReferenced = [&references](TypedName const& _returnVariable) { return references.count(_returnVariable.name); }; @@ -680,7 +679,7 @@ bool statementNeedsReturnVariableSetup(Statement const& _statement, vector const& _statements) +void CodeTransform::visitStatements(std::vector const& _statements) { std::optional jumpTarget = std::nullopt; @@ -716,7 +715,7 @@ void CodeTransform::visitStatements(vector const& _statements) freeUnusedVariables(); } -void CodeTransform::finalizeBlock(Block const& _block, optional blockStartStackHeight) +void CodeTransform::finalizeBlock(Block const& _block, std::optional blockStartStackHeight) { m_assembly.setSourceLocation(originLocationOf(_block)); @@ -725,7 +724,7 @@ void CodeTransform::finalizeBlock(Block const& _block, optional blockStartS // pop variables yulAssert(m_info.scopes.at(&_block).get() == m_scope, ""); for (auto const& id: m_scope->identifiers) - if (holds_alternative(id.second)) + if (std::holds_alternative(id.second)) { Scope::Variable const& var = std::get(id.second); if (m_allowStackOpt) @@ -740,11 +739,11 @@ void CodeTransform::finalizeBlock(Block const& _block, optional blockStartS if (blockStartStackHeight) { int deposit = m_assembly.stackHeight() - *blockStartStackHeight; - yulAssert(deposit == 0, "Invalid stack height at end of block: " + to_string(deposit)); + yulAssert(deposit == 0, "Invalid stack height at end of block: " + std::to_string(deposit)); } } -void CodeTransform::generateMultiAssignment(vector const& _variableNames) +void CodeTransform::generateMultiAssignment(std::vector const& _variableNames) { yulAssert(m_scope, ""); for (auto const& variableName: _variableNames | ranges::views::reverse) @@ -786,7 +785,7 @@ size_t CodeTransform::variableHeightDiff(Scope::Variable const& _var, YulString "Variable " + _varName.str() + " is " + - to_string(heightDiff - limit) + + std::to_string(heightDiff - limit) + " slot(s) too deep inside the stack. " + stackTooDeepString ); @@ -798,7 +797,7 @@ size_t CodeTransform::variableHeightDiff(Scope::Variable const& _var, YulString int CodeTransform::variableStackHeight(YulString _name) const { - Scope::Variable const* var = get_if(m_scope->lookup(_name)); + Scope::Variable const* var = std::get_if(m_scope->lookup(_name)); yulAssert(var, ""); return static_cast(m_context->variableStackHeights.at(var)); } diff --git a/libyul/backends/evm/EVMDialect.cpp b/libyul/backends/evm/EVMDialect.cpp index b66738b9d..47130fd6c 100644 --- a/libyul/backends/evm/EVMDialect.cpp +++ b/libyul/backends/evm/EVMDialect.cpp @@ -38,7 +38,7 @@ #include -using namespace std; +using namespace std::string_literals; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -46,9 +46,9 @@ using namespace solidity::util; namespace { -pair createEVMFunction( +std::pair createEVMFunction( langutil::EVMVersion _evmVersion, - string const& _name, + std::string const& _name, evmasm::Instruction _instruction ) { @@ -87,12 +87,12 @@ pair createEVMFunction( return {name, std::move(f)}; } -pair createFunction( - string _name, +std::pair createFunction( + std::string _name, size_t _params, size_t _returns, SideEffects _sideEffects, - vector> _literalArguments, + std::vector> _literalArguments, std::function _generateCode ) { @@ -111,7 +111,7 @@ pair createFunction( return {name, f}; } -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. @@ -122,20 +122,20 @@ set createReservedIdentifiers(langutil::EVMVersion _evmVersion) // TODO remove this in 0.9.0. We allow creating functions or identifiers in Yul with the name // prevrandao for VMs before paris. - auto prevRandaoException = [&](string const& _instrName) -> bool + auto prevRandaoException = [&](std::string const& _instrName) -> bool { // Using string comparison as the opcode is the same as for "difficulty" return _instrName == "prevrandao" && _evmVersion < langutil::EVMVersion::paris(); }; - set reserved; + std::set reserved; for (auto const& instr: evmasm::c_instructions) { - string name = toLower(instr.first); + std::string name = toLower(instr.first); if (!baseFeeException(instr.second) && !prevRandaoException(name)) reserved.emplace(name); } - reserved += vector{ + reserved += std::vector{ "linkersymbol"_yulstring, "datasize"_yulstring, "dataoffset"_yulstring, @@ -146,19 +146,19 @@ set createReservedIdentifiers(langutil::EVMVersion _evmVersion) return reserved; } -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. - auto prevRandaoException = [&](string const& _instrName) -> bool + auto prevRandaoException = [&](std::string const& _instrName) -> bool { return (_instrName == "prevrandao" && _evmVersion < langutil::EVMVersion::paris()) || (_instrName == "difficulty" && _evmVersion >= langutil::EVMVersion::paris()); }; - map builtins; + std::map builtins; for (auto const& instr: evmasm::c_instructions) { - string name = toLower(instr.first); + std::string name = toLower(instr.first); auto const opcode = instr.second; if ( @@ -198,7 +198,7 @@ map createBuiltins(langutil::EVMVersion _evmVe BuiltinContext& ) { yulAssert(_call.arguments.size() == 1, ""); - Literal const* literal = get_if(&_call.arguments.front()); + Literal const* literal = std::get_if(&_call.arguments.front()); yulAssert(literal, ""); _assembly.appendConstant(valueOfLiteral(*literal)); }) @@ -217,10 +217,10 @@ map createBuiltins(langutil::EVMVersion _evmVe _assembly.appendAssemblySize(); else { - vector subIdPath = + std::vector subIdPath = _context.subIDs.count(dataName) == 0 ? _context.currentObject->pathToSubObject(dataName) : - vector{_context.subIDs.at(dataName)}; + std::vector{_context.subIDs.at(dataName)}; yulAssert(!subIdPath.empty(), "Could not find assembly object <" + dataName.str() + ">."); _assembly.appendDataSize(subIdPath); } @@ -238,10 +238,10 @@ map createBuiltins(langutil::EVMVersion _evmVe _assembly.appendConstant(0); else { - vector subIdPath = + std::vector subIdPath = _context.subIDs.count(dataName) == 0 ? _context.currentObject->pathToSubObject(dataName) : - vector{_context.subIDs.at(dataName)}; + std::vector{_context.subIDs.at(dataName)}; yulAssert(!subIdPath.empty(), "Could not find assembly object <" + dataName.str() + ">."); _assembly.appendDataOffset(subIdPath); } @@ -295,9 +295,9 @@ map createBuiltins(langutil::EVMVersion _evmVe return builtins; } -regex const& verbatimPattern() +std::regex const& verbatimPattern() { - regex static const pattern{"verbatim_([1-9]?[0-9])i_([1-9]?[0-9])o"}; + std::regex static const pattern{"verbatim_([1-9]?[0-9])i_([1-9]?[0-9])o"}; return pattern; } @@ -316,7 +316,7 @@ BuiltinFunctionForEVM const* EVMDialect::builtin(YulString _name) const { if (m_objectAccess) { - smatch match; + std::smatch match; if (regex_match(_name.str(), match, verbatimPattern())) return verbatimFunction(stoul(match[1]), stoul(match[2])); } @@ -337,19 +337,19 @@ bool EVMDialect::reservedIdentifier(YulString _name) const EVMDialect const& EVMDialect::strictAssemblyForEVM(langutil::EVMVersion _version) { - static map> dialects; + static std::map> dialects; static YulStringRepository::ResetCallback callback{[&] { dialects.clear(); }}; if (!dialects[_version]) - dialects[_version] = make_unique(_version, false); + dialects[_version] = std::make_unique(_version, false); return *dialects[_version]; } EVMDialect const& EVMDialect::strictAssemblyForEVMObjects(langutil::EVMVersion _version) { - static map> dialects; + static std::map> dialects; static YulStringRepository::ResetCallback callback{[&] { dialects.clear(); }}; if (!dialects[_version]) - dialects[_version] = make_unique(_version, true); + dialects[_version] = std::make_unique(_version, true); return *dialects[_version]; } @@ -374,16 +374,16 @@ SideEffects EVMDialect::sideEffectsOfInstruction(evmasm::Instruction _instructio BuiltinFunctionForEVM const* EVMDialect::verbatimFunction(size_t _arguments, size_t _returnVariables) const { - pair key{_arguments, _returnVariables}; - shared_ptr& function = m_verbatimFunctions[key]; + std::pair key{_arguments, _returnVariables}; + std::shared_ptr& function = m_verbatimFunctions[key]; if (!function) { BuiltinFunctionForEVM builtinFunction = createFunction( - "verbatim_" + to_string(_arguments) + "i_" + to_string(_returnVariables) + "o", + "verbatim_" + std::to_string(_arguments) + "i_" + std::to_string(_returnVariables) + "o", 1 + _arguments, _returnVariables, SideEffects::worst(), - vector>{LiteralKind::String} + vector>(_arguments), + std::vector>{LiteralKind::String} + std::vector>(_arguments), [=]( FunctionCall const& _call, AbstractAssembly& _assembly, @@ -400,7 +400,7 @@ BuiltinFunctionForEVM const* EVMDialect::verbatimFunction(size_t _arguments, siz } ).second; builtinFunction.isMSize = true; - function = make_shared(std::move(builtinFunction)); + function = std::make_shared(std::move(builtinFunction)); } return function.get(); } @@ -501,9 +501,9 @@ BuiltinFunctionForEVM const* EVMDialectTyped::equalityFunction(YulString _type) EVMDialectTyped const& EVMDialectTyped::instance(langutil::EVMVersion _version) { - static map> dialects; + static std::map> dialects; static YulStringRepository::ResetCallback callback{[&] { dialects.clear(); }}; if (!dialects[_version]) - dialects[_version] = make_unique(_version, true); + dialects[_version] = std::make_unique(_version, true); return *dialects[_version]; } diff --git a/libyul/backends/evm/EVMMetrics.cpp b/libyul/backends/evm/EVMMetrics.cpp index 095969838..09c6abdd1 100644 --- a/libyul/backends/evm/EVMMetrics.cpp +++ b/libyul/backends/evm/EVMMetrics.cpp @@ -31,7 +31,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -52,7 +51,7 @@ bigint GasMeter::combineCosts(std::pair _costs) const } -pair GasMeterVisitor::costs( +std::pair GasMeterVisitor::costs( Expression const& _expression, EVMDialect const& _dialect, bool _isCreation @@ -63,7 +62,7 @@ pair GasMeterVisitor::costs( return {gmv.m_runGas, gmv.m_dataGas}; } -pair GasMeterVisitor::instructionCosts( +std::pair GasMeterVisitor::instructionCosts( evmasm::Instruction _instruction, EVMDialect const& _dialect, bool _isCreation diff --git a/libyul/backends/evm/EVMObjectCompiler.cpp b/libyul/backends/evm/EVMObjectCompiler.cpp index e7eae69ba..28b72c087 100644 --- a/libyul/backends/evm/EVMObjectCompiler.cpp +++ b/libyul/backends/evm/EVMObjectCompiler.cpp @@ -33,7 +33,6 @@ #include using namespace solidity::yul; -using namespace std; void EVMObjectCompiler::compile( Object& _object, @@ -91,12 +90,12 @@ void EVMObjectCompiler::run(Object& _object, bool _optimize) ); if (!stackErrors.empty()) { - vector memoryGuardCalls = FunctionCallFinder::run( + std::vector memoryGuardCalls = FunctionCallFinder::run( *_object.code, "memoryguard"_yulstring ); auto stackError = stackErrors.front(); - string msg = stackError.comment() ? *stackError.comment() : ""; + std::string msg = stackError.comment() ? *stackError.comment() : ""; if (memoryGuardCalls.empty()) msg += "\nNo memoryguard was present. " "Consider using memory-safe assembly only and annotating it via " diff --git a/libyul/backends/evm/EthAssemblyAdapter.cpp b/libyul/backends/evm/EthAssemblyAdapter.cpp index 9cbd6e00d..79146f859 100644 --- a/libyul/backends/evm/EthAssemblyAdapter.cpp +++ b/libyul/backends/evm/EthAssemblyAdapter.cpp @@ -33,7 +33,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -122,14 +121,14 @@ void EthAssemblyAdapter::appendAssemblySize() m_assembly.appendProgramSize(); } -pair, AbstractAssembly::SubID> EthAssemblyAdapter::createSubAssembly(bool _creation, string _name) +std::pair, AbstractAssembly::SubID> EthAssemblyAdapter::createSubAssembly(bool _creation, std::string _name) { - shared_ptr assembly{make_shared(m_assembly.evmVersion(), _creation, std::move(_name))}; + std::shared_ptr assembly{std::make_shared(m_assembly.evmVersion(), _creation, std::move(_name))}; auto sub = m_assembly.newSub(assembly); - return {make_shared(*assembly), static_cast(sub.data())}; + return {std::make_shared(*assembly), static_cast(sub.data())}; } -void EthAssemblyAdapter::appendDataOffset(vector const& _subPath) +void EthAssemblyAdapter::appendDataOffset(std::vector const& _subPath) { if (auto it = m_dataHashBySubId.find(_subPath[0]); it != m_dataHashBySubId.end()) { @@ -141,7 +140,7 @@ void EthAssemblyAdapter::appendDataOffset(vector const& m_assembly.pushSubroutineOffset(m_assembly.encodeSubPath(_subPath)); } -void EthAssemblyAdapter::appendDataSize(vector const& _subPath) +void EthAssemblyAdapter::appendDataSize(std::vector const& _subPath) { if (auto it = m_dataHashBySubId.find(_subPath[0]); it != m_dataHashBySubId.end()) { diff --git a/libyul/backends/evm/NoOutputAssembly.cpp b/libyul/backends/evm/NoOutputAssembly.cpp index ac64418ad..2a3cca52c 100644 --- a/libyul/backends/evm/NoOutputAssembly.cpp +++ b/libyul/backends/evm/NoOutputAssembly.cpp @@ -28,7 +28,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -60,12 +59,12 @@ NoOutputAssembly::LabelID NoOutputAssembly::newLabelId() return 1; } -AbstractAssembly::LabelID NoOutputAssembly::namedLabel(string const&, size_t, size_t, optional) +AbstractAssembly::LabelID NoOutputAssembly::namedLabel(std::string const&, size_t, size_t, std::optional) { return 1; } -void NoOutputAssembly::appendLinkerSymbol(string const&) +void NoOutputAssembly::appendLinkerSymbol(std::string const&) { yulAssert(false, "Linker symbols not yet implemented."); } @@ -98,7 +97,7 @@ void NoOutputAssembly::appendAssemblySize() appendInstruction(evmasm::Instruction::PUSH1); } -pair, AbstractAssembly::SubID> NoOutputAssembly::createSubAssembly(bool, std::string) +std::pair, AbstractAssembly::SubID> NoOutputAssembly::createSubAssembly(bool, std::string) { yulAssert(false, "Sub assemblies not implemented."); return {}; diff --git a/libyul/backends/evm/OptimizedEVMCodeTransform.cpp b/libyul/backends/evm/OptimizedEVMCodeTransform.cpp index 8e126a49a..3df75bb88 100644 --- a/libyul/backends/evm/OptimizedEVMCodeTransform.cpp +++ b/libyul/backends/evm/OptimizedEVMCodeTransform.cpp @@ -38,9 +38,8 @@ using namespace solidity; using namespace solidity::yul; -using namespace std; -vector OptimizedEVMCodeTransform::run( +std::vector OptimizedEVMCodeTransform::run( AbstractAssembly& _assembly, AsmAnalysisInfo& _analysisInfo, Block const& _block, @@ -81,7 +80,7 @@ void OptimizedEVMCodeTransform::operator()(CFG::FunctionCall const& _call) // Assert that we got the correct return label on stack. if (_call.canContinue) { - auto const* returnLabelSlot = get_if( + auto const* returnLabelSlot = std::get_if( &m_stack.at(m_stack.size() - _call.functionCall.get().arguments.size() - 1) ); yulAssert(returnLabelSlot && &returnLabelSlot->call.get() == &_call.functionCall.get(), ""); @@ -160,7 +159,7 @@ void OptimizedEVMCodeTransform::operator()(CFG::Assignment const& _assignment) // Invalidate occurrences of the assigned variables. for (auto& currentSlot: m_stack) - if (VariableSlot const* varSlot = get_if(¤tSlot)) + if (VariableSlot const* varSlot = std::get_if(¤tSlot)) if (util::contains(_assignment.variables, *varSlot)) currentSlot = JunkSlot{}; @@ -185,8 +184,8 @@ OptimizedEVMCodeTransform::OptimizedEVMCodeTransform( m_dfg(_dfg), m_stackLayout(_stackLayout), m_functionLabels([&](){ - map functionLabels; - set assignedFunctionNames; + std::map functionLabels; + std::set assignedFunctionNames; for (Scope::Function const* function: m_dfg.functions) { CFG::FunctionInfo const& functionInfo = m_dfg.functionInfo.at(function); @@ -199,7 +198,7 @@ OptimizedEVMCodeTransform::OptimizedEVMCodeTransform( function->name.str(), function->arguments.size(), function->returns.size(), - functionInfo.debugData ? functionInfo.debugData->astID : nullopt + functionInfo.debugData ? functionInfo.debugData->astID : std::nullopt ) : m_assembly.newLabelId(); } @@ -212,7 +211,7 @@ void OptimizedEVMCodeTransform::assertLayoutCompatibility(Stack const& _currentS { yulAssert(_currentStack.size() == _desiredStack.size(), ""); for (auto&& [currentSlot, desiredSlot]: ranges::zip_view(_currentStack, _desiredStack)) - yulAssert(holds_alternative(desiredSlot) || currentSlot == desiredSlot, ""); + yulAssert(std::holds_alternative(desiredSlot) || currentSlot == desiredSlot, ""); } AbstractAssembly::LabelID OptimizedEVMCodeTransform::getFunctionLabel(Scope::Function const& _function) @@ -224,15 +223,15 @@ void OptimizedEVMCodeTransform::validateSlot(StackSlot const& _slot, Expression { std::visit(util::GenericVisitor{ [&](yul::Literal const& _literal) { - auto* literalSlot = get_if(&_slot); + auto* literalSlot = std::get_if(&_slot); yulAssert(literalSlot && valueOfLiteral(_literal) == literalSlot->value, ""); }, [&](yul::Identifier const& _identifier) { - auto* variableSlot = get_if(&_slot); + auto* variableSlot = std::get_if(&_slot); yulAssert(variableSlot && variableSlot->variable.get().name == _identifier.name, ""); }, [&](yul::FunctionCall const& _call) { - auto* temporarySlot = get_if(&_slot); + auto* temporarySlot = std::get_if(&_slot); yulAssert(temporarySlot && &temporarySlot->call.get() == &_call && temporarySlot->index == 0, ""); } }, _expression); @@ -267,10 +266,10 @@ void OptimizedEVMCodeTransform::createStackLayout(std::shared_ptrfunction.name : YulString{}, varNameDeep.empty() ? varNameTop : varNameDeep, @@ -297,9 +296,9 @@ void OptimizedEVMCodeTransform::createStackLayout(std::shared_ptr(*depth - 15); YulString varName = slotVariableName(_slot); - string msg = + std::string msg = (varName.empty() ? "Slot " + stackSlotToString(_slot) : "Variable " + varName.str()) - + " is " + to_string(*depth - 15) + " too deep in the stack " + stackToString(m_stack); + + " 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{}, varName, @@ -503,9 +502,9 @@ void OptimizedEVMCodeTransform::operator()(CFG::BasicBlock const& _block) [&](CFG::BasicBlock::Terminated const&) { yulAssert(!_block.operations.empty()); - if (CFG::BuiltinCall const* builtinCall = get_if(&_block.operations.back().operation)) + if (CFG::BuiltinCall const* builtinCall = std::get_if(&_block.operations.back().operation)) yulAssert(builtinCall->builtin.get().controlFlowSideEffects.terminatesOrReverts(), ""); - else if (CFG::FunctionCall const* functionCall = get_if(&_block.operations.back().operation)) + else if (CFG::FunctionCall const* functionCall = std::get_if(&_block.operations.back().operation)) yulAssert(!functionCall->canContinue); else yulAssert(false); diff --git a/libyul/backends/evm/StackLayoutGenerator.cpp b/libyul/backends/evm/StackLayoutGenerator.cpp index 71bf19458..88190b45b 100644 --- a/libyul/backends/evm/StackLayoutGenerator.cpp +++ b/libyul/backends/evm/StackLayoutGenerator.cpp @@ -46,7 +46,6 @@ using namespace solidity; using namespace solidity::yul; -using namespace std; StackLayout StackLayoutGenerator::run(CFG const& _cfg) { @@ -59,9 +58,9 @@ StackLayout StackLayoutGenerator::run(CFG const& _cfg) return stackLayout; } -map> StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg) +std::map> StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg) { - map> stackTooDeepErrors; + std::map> stackTooDeepErrors; stackTooDeepErrors[YulString{}] = reportStackTooDeep(_cfg, YulString{}); for (auto const& function: _cfg.functions) if (auto errors = reportStackTooDeep(_cfg, function->name); !errors.empty()) @@ -69,7 +68,7 @@ map> StackLayoutGenerator: return stackTooDeepErrors; } -vector StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg, YulString _functionName) +std::vector StackLayoutGenerator::reportStackTooDeep(CFG const& _cfg, YulString _functionName) { StackLayout stackLayout; CFG::FunctionInfo const* functionInfo = nullptr; @@ -98,14 +97,14 @@ StackLayoutGenerator::StackLayoutGenerator(StackLayout& _layout, CFG::FunctionIn namespace { /// @returns all stack too deep errors that would occur when shuffling @a _source to @a _target. -vector findStackTooDeep(Stack const& _source, Stack const& _target) +std::vector findStackTooDeep(Stack const& _source, Stack const& _target) { Stack currentStack = _source; - vector stackTooDeepErrors; + std::vector stackTooDeepErrors; auto getVariableChoices = [](auto&& _range) { - vector result; + std::vector result; for (auto const& slot: _range) - if (auto const* variableSlot = get_if(&slot)) + if (auto const* variableSlot = std::get_if(&slot)) if (!util::contains(result, variableSlot->variable.get().name)) result.push_back(variableSlot->variable.get().name); return result; @@ -160,7 +159,7 @@ Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Calla // PreviousSlot{0}, ..., PreviousSlot{n}, [output<0>], ..., [output] auto layout = ranges::views::iota(0u, preOperationLayoutSize) | ranges::views::transform([](size_t _index) { return PreviousSlot{_index}; }) | - ranges::to>>; + ranges::to>>; layout += _operationOutput; // Shortcut for trivial case. @@ -171,23 +170,23 @@ Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Calla // that are aware of PreviousSlot's. struct ShuffleOperations { - vector>& layout; + std::vector>& layout; Stack const& post; std::set outputs; Multiplicity multiplicity; Callable generateSlotOnTheFly; ShuffleOperations( - vector>& _layout, + std::vector>& _layout, Stack const& _post, Callable _generateSlotOnTheFly ): layout(_layout), post(_post), generateSlotOnTheFly(_generateSlotOnTheFly) { for (auto const& layoutSlot: layout) - if (StackSlot const* slot = get_if(&layoutSlot)) + if (StackSlot const* slot = std::get_if(&layoutSlot)) outputs.insert(*slot); for (auto const& layoutSlot: layout) - if (StackSlot const* slot = get_if(&layoutSlot)) + if (StackSlot const* slot = std::get_if(&layoutSlot)) --multiplicity[*slot]; for (auto&& slot: post) if (outputs.count(slot) || generateSlotOnTheFly(slot)) @@ -235,7 +234,7 @@ Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Calla } void swap(size_t _i) { - yulAssert(!holds_alternative(layout.at(layout.size() - _i - 1)) || !holds_alternative(layout.back()), ""); + yulAssert(!std::holds_alternative(layout.at(layout.size() - _i - 1)) || !std::holds_alternative(layout.back()), ""); std::swap(layout.at(layout.size() - _i - 1), layout.back()); } size_t sourceSize() { return layout.size(); } @@ -250,7 +249,7 @@ Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Calla // output in place. The resulting permutation of the PreviousSlot yields the ideal positions of slots // before the operation, i.e. if PreviousSlot{2} is at a position at which _post contains VariableSlot{"tmp"}, // then we want the variable tmp in the slot at offset 2 in the layout before the operation. - vector> idealLayout(_post.size(), nullopt); + std::vector> idealLayout(_post.size(), std::nullopt); for (auto&& [slot, idealPosition]: ranges::zip_view(_post, layout)) if (PreviousSlot* previousSlot = std::get_if(&idealPosition)) idealLayout.at(previousSlot->slot) = slot; @@ -261,7 +260,7 @@ Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Calla yulAssert(idealLayout.size() == preOperationLayoutSize, ""); - return idealLayout | ranges::views::transform([](optional s) { + return idealLayout | ranges::views::transform([](std::optional s) { yulAssert(s, ""); return *s; }) | ranges::to; @@ -271,7 +270,7 @@ Stack createIdealLayout(Stack const& _operationOutput, Stack const& _post, Calla Stack StackLayoutGenerator::propagateStackThroughOperation(Stack _exitStack, CFG::Operation const& _operation, bool _aggressiveStackCompression) { // Enable aggressive stack compression for recursive calls. - if (auto const* functionCall = get_if(&_operation.operation)) + if (auto const* functionCall = std::get_if(&_operation.operation)) if (functionCall->recursive) _aggressiveStackCompression = true; @@ -285,9 +284,9 @@ Stack StackLayoutGenerator::propagateStackThroughOperation(Stack _exitStack, CFG Stack stack = createIdealLayout(_operation.output, _exitStack, generateSlotOnTheFly); // Make sure the resulting previous slots do not overlap with any assignmed variables. - if (auto const* assignment = get_if(&_operation.operation)) + if (auto const* assignment = std::get_if(&_operation.operation)) for (auto& stackSlot: stack) - if (auto const* varSlot = get_if(&stackSlot)) + if (auto const* varSlot = std::get_if(&stackSlot)) yulAssert(!util::contains(assignment->variables, *varSlot), ""); // Since stack+_operation.output can be easily shuffled to _exitLayout, the desired layout before the operation @@ -335,11 +334,11 @@ Stack StackLayoutGenerator::propagateStackThroughBlock(Stack _exitStack, CFG::Ba void StackLayoutGenerator::processEntryPoint(CFG::BasicBlock const& _entry, CFG::FunctionInfo const* _functionInfo) { - list toVisit{&_entry}; - set visited; + std::list toVisit{&_entry}; + std::set visited; // TODO: check whether visiting only a subset of these in the outer iteration below is enough. - list> backwardsJumps = collectBackwardsJumps(_entry); + std::list> backwardsJumps = collectBackwardsJumps(_entry); while (!toVisit.empty()) { @@ -407,10 +406,10 @@ void StackLayoutGenerator::processEntryPoint(CFG::BasicBlock const& _entry, CFG: fillInJunk(_entry, _functionInfo); } -optional StackLayoutGenerator::getExitLayoutOrStageDependencies( +std::optional StackLayoutGenerator::getExitLayoutOrStageDependencies( CFG::BasicBlock const& _block, - set const& _visited, - list& _toVisit + std::set const& _visited, + std::list& _toVisit ) const { return std::visit(util::GenericVisitor{ @@ -434,7 +433,7 @@ optional StackLayoutGenerator::getExitLayoutOrStageDependencies( return m_layout.blockInfos.at(_jump.target).entryLayout; // Otherwise stage the jump target for visit and defer the current block. _toVisit.emplace_front(_jump.target); - return nullopt; + return std::nullopt; }, [&](CFG::BasicBlock::ConditionalJump const& _conditionalJump) -> std::optional { @@ -456,7 +455,7 @@ optional StackLayoutGenerator::getExitLayoutOrStageDependencies( _toVisit.emplace_front(_conditionalJump.zero); if (!nonZeroVisited) _toVisit.emplace_front(_conditionalJump.nonZero); - return nullopt; + return std::nullopt; }, [&](CFG::BasicBlock::FunctionReturn const& _functionReturn) -> std::optional { @@ -476,9 +475,9 @@ optional StackLayoutGenerator::getExitLayoutOrStageDependencies( }, _block.exit); } -list> StackLayoutGenerator::collectBackwardsJumps(CFG::BasicBlock const& _entry) const +std::list> StackLayoutGenerator::collectBackwardsJumps(CFG::BasicBlock const& _entry) const { - list> backwardsJumps; + std::list> backwardsJumps; util::BreadthFirstSearch{{&_entry}}.run([&](CFG::BasicBlock const* _block, auto _addChild) { std::visit(util::GenericVisitor{ [&](CFG::BasicBlock::MainExit const&) {}, @@ -576,7 +575,7 @@ Stack StackLayoutGenerator::combineStack(Stack const& _stack1, Stack const& _sta if (!util::contains(candidate, slot)) candidate.emplace_back(slot); cxx20::erase_if(candidate, [](StackSlot const& slot) { - return holds_alternative(slot) || holds_alternative(slot); + return std::holds_alternative(slot) || std::holds_alternative(slot); }); auto evaluate = [&](Stack const& _candidate) -> size_t { @@ -633,9 +632,9 @@ Stack StackLayoutGenerator::combineStack(Stack const& _stack1, Stack const& _sta return commonPrefix + bestCandidate; } -vector StackLayoutGenerator::reportStackTooDeep(CFG::BasicBlock const& _entry) const +std::vector StackLayoutGenerator::reportStackTooDeep(CFG::BasicBlock const& _entry) const { - vector stackTooDeepErrors; + std::vector stackTooDeepErrors; util::BreadthFirstSearch breadthFirstSearch{{&_entry}}; breadthFirstSearch.run([&](CFG::BasicBlock const* _block, auto _addChild) { Stack currentStack = m_layout.blockInfos.at(_block).entryLayout; @@ -683,7 +682,7 @@ vector StackLayoutGenerator::reportStackTooD Stack StackLayoutGenerator::compressStack(Stack _stack) { - optional firstDupOffset; + std::optional firstDupOffset; do { if (firstDupOffset) @@ -768,8 +767,8 @@ void StackLayoutGenerator::fillInJunk(CFG::BasicBlock const& _block, CFG::Functi { // This has to be a previously unassigned return variable. // We at least sanity-check that it is among the return variables at all. - yulAssert(m_currentFunctionInfo && holds_alternative(_slot)); - yulAssert(util::contains(m_currentFunctionInfo->returnVariables, get(_slot))); + yulAssert(m_currentFunctionInfo && std::holds_alternative(_slot)); + yulAssert(util::contains(m_currentFunctionInfo->returnVariables, std::get(_slot))); // Strictly speaking the cost of the PUSH0 depends on the targeted EVM version, but the difference // will not matter here. opGas += evmasm::GasMeter::runGas(evmasm::pushInstruction(0), langutil::EVMVersion());; diff --git a/scripts/check_style.sh b/scripts/check_style.sh index f12fcc8e6..69955f717 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -34,6 +34,7 @@ NAMESPACE_STD_FREE_FILES=( libsolidity/lsp/* libsolidity/parsing/* libsolutil/* + libyul/backends/evm/* solc/* ) From 2cf23e15d867f702c9e85864aa68935af9f7c606 Mon Sep 17 00:00:00 2001 From: Jun Zhang Date: Thu, 24 Aug 2023 09:54:58 +0800 Subject: [PATCH 2/3] Bump fmtlib to 9.1.0 In our downstream project, we have two dependencies: solidity and spdlog. Both of them depend on fmtlib. Unfortunately, the versions of fmtlib they use do not match, which leads to compilation failure. The issue arises because spdlog attempts to use solidity's fmtlib, but the specific version (v8.0.1) has a bug. Ref: https://github.com/gabime/spdlog/issues/2142 While we could keep this change in our own fork, we believe it would be worthwhile to contribute it back to the upstream since spdlog is a very popular logging library. Signed-off-by: Jun Zhang --- cmake/fmtlib.cmake | 6 +++--- libsolidity/lsp/SemanticTokensBuilder.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cmake/fmtlib.cmake b/cmake/fmtlib.cmake index 792bf3b02..032a68cd5 100644 --- a/cmake/fmtlib.cmake +++ b/cmake/fmtlib.cmake @@ -4,9 +4,9 @@ FetchContent_Declare( fmtlib PREFIX "${PROJECT_BINARY_DIR}/deps" DOWNLOAD_DIR "${PROJECT_SOURCE_DIR}/deps/downloads" - DOWNLOAD_NAME fmt-8.0.1.tar.gz - URL https://github.com/fmtlib/fmt/archive/8.0.1.tar.gz - URL_HASH SHA256=b06ca3130158c625848f3fb7418f235155a4d389b2abc3a6245fb01cb0eb1e01 + DOWNLOAD_NAME fmt-9.1.0.tar.gz + URL https://github.com/fmtlib/fmt/archive/9.1.0.tar.gz + URL_HASH SHA256=5dea48d1fcddc3ec571ce2058e13910a0d4a6bab4cc09a809d8b1dd1c88ae6f2 ) if (CMAKE_VERSION VERSION_LESS "3.14.0") diff --git a/libsolidity/lsp/SemanticTokensBuilder.cpp b/libsolidity/lsp/SemanticTokensBuilder.cpp index ac5295473..2f4435418 100644 --- a/libsolidity/lsp/SemanticTokensBuilder.cpp +++ b/libsolidity/lsp/SemanticTokensBuilder.cpp @@ -118,7 +118,7 @@ void SemanticTokensBuilder::encode( auto const [line, startChar] = m_charStream->translatePositionToLineColumn(_sourceLocation.start); auto const length = _sourceLocation.end - _sourceLocation.start; - lspDebug(fmt::format("encode [{}:{}..{}] {}", line, startChar, length, _tokenType)); + lspDebug(fmt::format("encode [{}:{}..{}] {}", line, startChar, length, static_cast(_tokenType))); m_encodedTokens.append(line - m_lastLine); if (line == m_lastLine) From c2362c3362fdc9d2fe695f6f7e1581123dff9ec6 Mon Sep 17 00:00:00 2001 From: Jun Zhang Date: Wed, 23 Aug 2023 10:03:44 +0800 Subject: [PATCH 3/3] Purge using namespace std from libyul/optimiser Signed-off-by: Jun Zhang --- libyul/optimiser/ASTCopier.cpp | 1 - libyul/optimiser/ASTWalker.cpp | 1 - libyul/optimiser/BlockFlattener.cpp | 9 +- libyul/optimiser/BlockHasher.cpp | 1 - libyul/optimiser/CallGraphGenerator.cpp | 9 +- libyul/optimiser/CircularReferencesPruner.cpp | 9 +- .../CommonSubexpressionEliminator.cpp | 13 ++- libyul/optimiser/ConditionalSimplifier.cpp | 13 ++- libyul/optimiser/ConditionalUnsimplifier.cpp | 17 ++-- libyul/optimiser/ControlFlowSimplifier.cpp | 13 ++- libyul/optimiser/DataFlowAnalyzer.cpp | 53 ++++++------ libyul/optimiser/DeadCodeEliminator.cpp | 5 +- libyul/optimiser/Disambiguator.cpp | 1 - libyul/optimiser/EqualStoreEliminator.cpp | 7 +- .../optimiser/EquivalentFunctionCombiner.cpp | 1 - .../optimiser/EquivalentFunctionDetector.cpp | 1 - libyul/optimiser/ExpressionInliner.cpp | 5 +- libyul/optimiser/ExpressionJoiner.cpp | 11 ++- libyul/optimiser/ExpressionSimplifier.cpp | 11 ++- libyul/optimiser/ExpressionSplitter.cpp | 13 ++- libyul/optimiser/ForLoopConditionIntoBody.cpp | 11 ++- .../optimiser/ForLoopConditionOutOfBody.cpp | 15 ++-- libyul/optimiser/ForLoopInitRewriter.cpp | 7 +- libyul/optimiser/FullInliner.cpp | 49 ++++++----- libyul/optimiser/FunctionCallFinder.cpp | 3 +- libyul/optimiser/FunctionGrouper.cpp | 9 +- libyul/optimiser/FunctionHoister.cpp | 3 +- libyul/optimiser/FunctionSpecializer.cpp | 35 ++++---- .../InlinableExpressionFunctionFinder.cpp | 5 +- libyul/optimiser/KnowledgeBase.cpp | 43 +++++----- libyul/optimiser/LoadResolver.cpp | 17 ++-- libyul/optimiser/LoopInvariantCodeMotion.cpp | 25 +++--- libyul/optimiser/Metrics.cpp | 31 ++++--- libyul/optimiser/NameCollector.cpp | 17 ++-- libyul/optimiser/NameDispenser.cpp | 7 +- libyul/optimiser/NameDisplacer.cpp | 3 +- libyul/optimiser/NameSimplifier.cpp | 43 +++++----- libyul/optimiser/OptimizerUtilities.cpp | 13 ++- libyul/optimiser/Rematerialiser.cpp | 11 ++- libyul/optimiser/SSAReverser.cpp | 3 +- libyul/optimiser/SSATransform.cpp | 67 ++++++++------- libyul/optimiser/SSAValueTracker.cpp | 5 +- libyul/optimiser/Semantics.cpp | 31 ++++--- libyul/optimiser/SimplificationRules.cpp | 33 ++++---- libyul/optimiser/StackCompressor.cpp | 43 +++++----- libyul/optimiser/StackLimitEvader.cpp | 23 +++--- libyul/optimiser/StackToMemoryMover.cpp | 71 ++++++++-------- libyul/optimiser/StructuralSimplifier.cpp | 11 ++- libyul/optimiser/Substitution.cpp | 3 +- libyul/optimiser/Suite.cpp | 82 +++++++++---------- libyul/optimiser/SyntacticalEquality.cpp | 1 - libyul/optimiser/TypeInfo.cpp | 3 +- libyul/optimiser/UnusedAssignEliminator.cpp | 7 +- .../UnusedFunctionParameterPruner.cpp | 19 ++--- libyul/optimiser/UnusedPruner.cpp | 25 +++--- libyul/optimiser/UnusedStoreBase.cpp | 9 +- libyul/optimiser/UnusedStoreEliminator.cpp | 81 +++++++++--------- libyul/optimiser/VarDeclInitializer.cpp | 9 +- libyul/optimiser/VarNameCleaner.cpp | 19 ++--- scripts/check_style.sh | 1 + 60 files changed, 515 insertions(+), 572 deletions(-) diff --git a/libyul/optimiser/ASTCopier.cpp b/libyul/optimiser/ASTCopier.cpp index 79dc82efa..9f4107941 100644 --- a/libyul/optimiser/ASTCopier.cpp +++ b/libyul/optimiser/ASTCopier.cpp @@ -25,7 +25,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; diff --git a/libyul/optimiser/ASTWalker.cpp b/libyul/optimiser/ASTWalker.cpp index cdcfaa635..cd8732cd0 100644 --- a/libyul/optimiser/ASTWalker.cpp +++ b/libyul/optimiser/ASTWalker.cpp @@ -25,7 +25,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; diff --git a/libyul/optimiser/BlockFlattener.cpp b/libyul/optimiser/BlockFlattener.cpp index 0bb828ee5..f7dc19f96 100644 --- a/libyul/optimiser/BlockFlattener.cpp +++ b/libyul/optimiser/BlockFlattener.cpp @@ -23,7 +23,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -34,9 +33,9 @@ void BlockFlattener::operator()(Block& _block) iterateReplacing( _block.statements, - [](Statement& _s) -> std::optional> + [](Statement& _s) -> std::optional> { - if (holds_alternative(_s)) + if (std::holds_alternative(_s)) return std::move(std::get(_s).statements); else return {}; @@ -48,9 +47,9 @@ void BlockFlattener::run(OptimiserStepContext&, Block& _ast) { BlockFlattener flattener; for (auto& statement: _ast.statements) - if (auto* block = get_if(&statement)) + if (auto* block = std::get_if(&statement)) flattener(*block); - else if (auto* function = get_if(&statement)) + else if (auto* function = std::get_if(&statement)) flattener(function->body); else yulAssert(false, "BlockFlattener requires the FunctionGrouper."); diff --git a/libyul/optimiser/BlockHasher.cpp b/libyul/optimiser/BlockHasher.cpp index ce07ac9f7..380cc15fb 100644 --- a/libyul/optimiser/BlockHasher.cpp +++ b/libyul/optimiser/BlockHasher.cpp @@ -23,7 +23,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; diff --git a/libyul/optimiser/CallGraphGenerator.cpp b/libyul/optimiser/CallGraphGenerator.cpp index 66f740391..87035e68a 100644 --- a/libyul/optimiser/CallGraphGenerator.cpp +++ b/libyul/optimiser/CallGraphGenerator.cpp @@ -25,7 +25,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -36,9 +35,9 @@ namespace struct CallGraphCycleFinder { CallGraph const& callGraph; - set containedInCycle{}; - set visited{}; - vector currentPath{}; + std::set containedInCycle{}; + std::set visited{}; + std::vector currentPath{}; void visit(YulString _function) { @@ -62,7 +61,7 @@ struct CallGraphCycleFinder }; } -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. diff --git a/libyul/optimiser/CircularReferencesPruner.cpp b/libyul/optimiser/CircularReferencesPruner.cpp index ba1fbf11d..824d2be39 100644 --- a/libyul/optimiser/CircularReferencesPruner.cpp +++ b/libyul/optimiser/CircularReferencesPruner.cpp @@ -24,7 +24,6 @@ #include -using namespace std; using namespace solidity::yul; void CircularReferencesPruner::run(OptimiserStepContext& _context, Block& _ast) @@ -35,11 +34,11 @@ void CircularReferencesPruner::run(OptimiserStepContext& _context, Block& _ast) void CircularReferencesPruner::operator()(Block& _block) { - set functionsToKeep = + std::set functionsToKeep = functionsCalledFromOutermostContext(CallGraphGenerator::callGraph(_block)); for (auto&& statement: _block.statements) - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) { FunctionDefinition const& funDef = std::get(statement); if (!functionsToKeep.count(funDef.name)) @@ -49,9 +48,9 @@ void CircularReferencesPruner::operator()(Block& _block) removeEmptyBlocks(_block); } -set CircularReferencesPruner::functionsCalledFromOutermostContext(CallGraph const& _callGraph) +std::set CircularReferencesPruner::functionsCalledFromOutermostContext(CallGraph const& _callGraph) { - set verticesToTraverse = m_reservedIdentifiers; + std::set verticesToTraverse = m_reservedIdentifiers; verticesToTraverse.insert(YulString("")); return util::BreadthFirstSearch{{verticesToTraverse.begin(), verticesToTraverse.end()}}.run( diff --git a/libyul/optimiser/CommonSubexpressionEliminator.cpp b/libyul/optimiser/CommonSubexpressionEliminator.cpp index 5d085cdd4..ae55f75e9 100644 --- a/libyul/optimiser/CommonSubexpressionEliminator.cpp +++ b/libyul/optimiser/CommonSubexpressionEliminator.cpp @@ -31,7 +31,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -47,7 +46,7 @@ void CommonSubexpressionEliminator::run(OptimiserStepContext& _context, Block& _ CommonSubexpressionEliminator::CommonSubexpressionEliminator( Dialect const& _dialect, - map _functionSideEffects + std::map _functionSideEffects ): DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore, std::move(_functionSideEffects)) { @@ -69,7 +68,7 @@ void CommonSubexpressionEliminator::visit(Expression& _e) bool descend = true; // If this is a function call to a function that requires literal arguments, // do not try to simplify there. - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) { FunctionCall& funCall = std::get(_e); @@ -94,13 +93,13 @@ void CommonSubexpressionEliminator::visit(Expression& _e) if (descend) DataFlowAnalyzer::visit(_e); - if (Identifier const* identifier = get_if(&_e)) + if (Identifier const* identifier = std::get_if(&_e)) { YulString identifierName = identifier->name; if (AssignedValue const* assignedValue = variableValue(identifierName)) { assertThrow(assignedValue->value, OptimizerException, ""); - if (Identifier const* value = get_if(assignedValue->value)) + if (Identifier const* value = std::get_if(assignedValue->value)) if (inScope(value->name)) _e = Identifier{debugDataOf(_e), value->name}; } @@ -114,8 +113,8 @@ void CommonSubexpressionEliminator::visit(Expression& _e) // instead of literal zeros. if ( m_returnVariables.count(variable) && - holds_alternative(*value->value) && - valueOfLiteral(get(*value->value)) == 0 + std::holds_alternative(*value->value) && + valueOfLiteral(std::get(*value->value)) == 0 ) continue; // We check for syntactic equality again because the value might have changed. diff --git a/libyul/optimiser/ConditionalSimplifier.cpp b/libyul/optimiser/ConditionalSimplifier.cpp index 62d36520a..b08b113de 100644 --- a/libyul/optimiser/ConditionalSimplifier.cpp +++ b/libyul/optimiser/ConditionalSimplifier.cpp @@ -22,7 +22,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -38,7 +37,7 @@ void ConditionalSimplifier::run(OptimiserStepContext& _context, Block& _ast) void ConditionalSimplifier::operator()(Switch& _switch) { visit(*_switch.expression); - if (!holds_alternative(*_switch.expression)) + if (!std::holds_alternative(*_switch.expression)) { ASTModifier::operator()(_switch); return; @@ -53,7 +52,7 @@ void ConditionalSimplifier::operator()(Switch& _switch) Assignment{ _case.body.debugData, {Identifier{_case.body.debugData, expr}}, - make_unique(*_case.value) + std::make_unique(*_case.value) } ); } @@ -65,14 +64,14 @@ void ConditionalSimplifier::operator()(Block& _block) { iterateReplacing( _block.statements, - [&](Statement& _s) -> std::optional> + [&](Statement& _s) -> std::optional> { visit(_s); - if (holds_alternative(_s)) + if (std::holds_alternative(_s)) { If& _if = std::get(_s); if ( - holds_alternative(*_if.condition) && + std::holds_alternative(*_if.condition) && !_if.body.statements.empty() && TerminationFinder(m_dialect, &m_functionSideEffects).controlFlowKind(_if.body.statements.back()) != TerminationFinder::ControlFlow::FlowOut @@ -85,7 +84,7 @@ void ConditionalSimplifier::operator()(Block& _block) Assignment{ debugData, {Identifier{debugData, condition}}, - make_unique(m_dialect.zeroLiteralForType(m_dialect.boolType)) + std::make_unique(m_dialect.zeroLiteralForType(m_dialect.boolType)) } ); } diff --git a/libyul/optimiser/ConditionalUnsimplifier.cpp b/libyul/optimiser/ConditionalUnsimplifier.cpp index ef640ed7c..2af09af04 100644 --- a/libyul/optimiser/ConditionalUnsimplifier.cpp +++ b/libyul/optimiser/ConditionalUnsimplifier.cpp @@ -23,7 +23,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -39,7 +38,7 @@ void ConditionalUnsimplifier::run(OptimiserStepContext& _context, Block& _ast) void ConditionalUnsimplifier::operator()(Switch& _switch) { visit(*_switch.expression); - if (!holds_alternative(*_switch.expression)) + if (!std::holds_alternative(*_switch.expression)) { ASTModifier::operator()(_switch); return; @@ -52,14 +51,14 @@ void ConditionalUnsimplifier::operator()(Switch& _switch) (*this)(*_case.value); if ( !_case.body.statements.empty() && - holds_alternative(_case.body.statements.front()) + std::holds_alternative(_case.body.statements.front()) ) { Assignment const& assignment = std::get(_case.body.statements.front()); if ( assignment.variableNames.size() == 1 && assignment.variableNames.front().name == expr && - holds_alternative(*assignment.value) && + std::holds_alternative(*assignment.value) && valueOfLiteral(std::get(*assignment.value)) == valueOfLiteral(*_case.value) ) _case.body.statements.erase(_case.body.statements.begin()); @@ -74,19 +73,19 @@ void ConditionalUnsimplifier::operator()(Block& _block) walkVector(_block.statements); iterateReplacingWindow<2>( _block.statements, - [&](Statement& _stmt1, Statement& _stmt2) -> std::optional> + [&](Statement& _stmt1, Statement& _stmt2) -> std::optional> { - if (holds_alternative(_stmt1)) + if (std::holds_alternative(_stmt1)) { If& _if = std::get(_stmt1); if ( - holds_alternative(*_if.condition) && + std::holds_alternative(*_if.condition) && !_if.body.statements.empty() ) { YulString condition = std::get(*_if.condition).name; if ( - holds_alternative(_stmt2) && + std::holds_alternative(_stmt2) && TerminationFinder(m_dialect, &m_functionSideEffects).controlFlowKind(_if.body.statements.back()) != TerminationFinder::ControlFlow::FlowOut ) @@ -95,7 +94,7 @@ void ConditionalUnsimplifier::operator()(Block& _block) if ( assignment.variableNames.size() == 1 && assignment.variableNames.front().name == condition && - holds_alternative(*assignment.value) && + std::holds_alternative(*assignment.value) && valueOfLiteral(std::get(*assignment.value)) == 0 ) return {make_vector(std::move(_stmt1))}; diff --git a/libyul/optimiser/ControlFlowSimplifier.cpp b/libyul/optimiser/ControlFlowSimplifier.cpp index cfd59d09a..771b4e86b 100644 --- a/libyul/optimiser/ControlFlowSimplifier.cpp +++ b/libyul/optimiser/ControlFlowSimplifier.cpp @@ -27,12 +27,11 @@ #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::yul; -using OptionalStatements = std::optional>; +using OptionalStatements = std::optional>; namespace { @@ -85,13 +84,13 @@ void ControlFlowSimplifier::operator()(Block& _block) void ControlFlowSimplifier::operator()(FunctionDefinition& _funDef) { ASTModifier::operator()(_funDef); - if (!_funDef.body.statements.empty() && holds_alternative(_funDef.body.statements.back())) + if (!_funDef.body.statements.empty() && std::holds_alternative(_funDef.body.statements.back())) _funDef.body.statements.pop_back(); } void ControlFlowSimplifier::visit(Statement& _st) { - if (holds_alternative(_st)) + if (std::holds_alternative(_st)) { ForLoop& forLoop = std::get(_st); yulAssert(forLoop.pre.statements.empty(), ""); @@ -141,7 +140,7 @@ void ControlFlowSimplifier::simplify(std::vector& _statements) [&](If& _ifStmt) -> OptionalStatements { if (_ifStmt.body.statements.empty() && m_dialect.discardFunction(m_dialect.boolType)) { - OptionalStatements s = vector{}; + OptionalStatements s = std::vector{}; s->emplace_back(makeDiscardCall( _ifStmt.debugData, *m_dialect.discardFunction(m_dialect.boolType), @@ -197,7 +196,7 @@ OptionalStatements ControlFlowSimplifier::reduceSingleCaseSwitch(Switch& _switch yulAssert(_switchStmt.cases.size() == 1, "Expected only one case!"); auto& switchCase = _switchStmt.cases.front(); - shared_ptr debugData = debugDataOf(*_switchStmt.expression); + std::shared_ptr debugData = debugDataOf(*_switchStmt.expression); YulString type = m_typeInfo.typeOf(*_switchStmt.expression); if (switchCase.value) { @@ -205,7 +204,7 @@ OptionalStatements ControlFlowSimplifier::reduceSingleCaseSwitch(Switch& _switch return {}; return make_vector(If{ std::move(_switchStmt.debugData), - make_unique(FunctionCall{ + std::make_unique(FunctionCall{ debugData, Identifier{debugData, m_dialect.equalityFunction(type)->name}, {std::move(*switchCase.value), std::move(*_switchStmt.expression)} diff --git a/libyul/optimiser/DataFlowAnalyzer.cpp b/libyul/optimiser/DataFlowAnalyzer.cpp index 81028e300..958e70a83 100644 --- a/libyul/optimiser/DataFlowAnalyzer.cpp +++ b/libyul/optimiser/DataFlowAnalyzer.cpp @@ -38,7 +38,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::yul; @@ -46,7 +45,7 @@ using namespace solidity::yul; DataFlowAnalyzer::DataFlowAnalyzer( Dialect const& _dialect, MemoryAndStorage _analyzeStores, - map _functionSideEffects + std::map _functionSideEffects ): m_dialect(_dialect), m_functionSideEffects(std::move(_functionSideEffects)), @@ -99,7 +98,7 @@ void DataFlowAnalyzer::operator()(ExpressionStatement& _statement) void DataFlowAnalyzer::operator()(Assignment& _assignment) { - set names; + std::set names; for (auto const& var: _assignment.variableNames) names.emplace(var.name); assertThrow(_assignment.value, OptimizerException, ""); @@ -110,7 +109,7 @@ void DataFlowAnalyzer::operator()(Assignment& _assignment) void DataFlowAnalyzer::operator()(VariableDeclaration& _varDecl) { - set names; + std::set names; for (auto const& var: _varDecl.variables) names.emplace(var.name); m_variableScopes.back().variables += names; @@ -139,14 +138,14 @@ void DataFlowAnalyzer::operator()(Switch& _switch) { clearKnowledgeIfInvalidated(*_switch.expression); visit(*_switch.expression); - set assignedVariables; + std::set assignedVariables; for (auto& _case: _switch.cases) { Environment preEnvironment = m_state.environment; (*this)(_case.body); joinKnowledge(preEnvironment); - 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); @@ -192,7 +191,7 @@ void DataFlowAnalyzer::operator()(ForLoop& _for) AssignmentsSinceContinue assignmentsSinceCont; assignmentsSinceCont(_for.body); - set assignedVariables = + std::set assignedVariables = assignedVariableNames(_for.body) + assignedVariableNames(_for.post); clearValues(assignedVariables); @@ -223,31 +222,31 @@ void DataFlowAnalyzer::operator()(Block& _block) assertThrow(numScopes == m_variableScopes.size(), OptimizerException, ""); } -optional DataFlowAnalyzer::storageValue(YulString _key) const +std::optional DataFlowAnalyzer::storageValue(YulString _key) const { if (YulString const* value = valueOrNullptr(m_state.environment.storage, _key)) return *value; else - return nullopt; + return std::nullopt; } -optional DataFlowAnalyzer::memoryValue(YulString _key) const +std::optional DataFlowAnalyzer::memoryValue(YulString _key) const { if (YulString const* value = valueOrNullptr(m_state.environment.memory, _key)) return *value; else - return nullopt; + return std::nullopt; } -optional DataFlowAnalyzer::keccakValue(YulString _start, YulString _length) const +std::optional DataFlowAnalyzer::keccakValue(YulString _start, YulString _length) const { - if (YulString const* value = valueOrNullptr(m_state.environment.keccak, make_pair(_start, _length))) + if (YulString const* value = valueOrNullptr(m_state.environment.keccak, std::make_pair(_start, _length))) return *value; else - return nullopt; + return std::nullopt; } -void DataFlowAnalyzer::handleAssignment(set const& _variables, Expression* _value, bool _isDeclaration) +void DataFlowAnalyzer::handleAssignment(std::set const& _variables, Expression* _value, bool _isDeclaration) { if (!_isDeclaration) clearValues(_variables); @@ -321,7 +320,7 @@ void DataFlowAnalyzer::popScope() m_variableScopes.pop_back(); } -void DataFlowAnalyzer::clearValues(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 @@ -410,24 +409,24 @@ bool DataFlowAnalyzer::inScope(YulString _variableName) const return false; } -optional DataFlowAnalyzer::valueOfIdentifier(YulString const& _name) const +std::optional DataFlowAnalyzer::valueOfIdentifier(YulString const& _name) const { if (AssignedValue const* value = variableValue(_name)) - if (Literal const* literal = get_if(value->value)) + if (Literal const* literal = std::get_if(value->value)) return valueOfLiteral(*literal); - return nullopt; + return std::nullopt; } -std::optional> DataFlowAnalyzer::isSimpleStore( +std::optional> DataFlowAnalyzer::isSimpleStore( StoreLoadLocation _location, ExpressionStatement const& _statement ) const { - if (FunctionCall const* funCall = get_if(&_statement.expression)) + if (FunctionCall const* funCall = std::get_if(&_statement.expression)) if (funCall->functionName.name == m_storeFunctionName[static_cast(_location)]) if (Identifier const* key = std::get_if(&funCall->arguments.front())) if (Identifier const* value = std::get_if(&funCall->arguments.back())) - return make_pair(key->name, value->name); + return std::make_pair(key->name, value->name); return {}; } @@ -436,21 +435,21 @@ std::optional DataFlowAnalyzer::isSimpleLoad( Expression const& _expression ) const { - if (FunctionCall const* funCall = get_if(&_expression)) + if (FunctionCall const* funCall = std::get_if(&_expression)) if (funCall->functionName.name == m_loadFunctionName[static_cast(_location)]) if (Identifier const* key = std::get_if(&funCall->arguments.front())) return key->name; return {}; } -optional> DataFlowAnalyzer::isKeccak(Expression const& _expression) const +std::optional> DataFlowAnalyzer::isKeccak(Expression const& _expression) const { - if (FunctionCall const* funCall = get_if(&_expression)) + if (FunctionCall const* funCall = std::get_if(&_expression)) if (funCall->functionName.name == m_dialect.hashFunction({})) if (Identifier const* start = std::get_if(&funCall->arguments.at(0))) if (Identifier const* length = std::get_if(&funCall->arguments.at(1))) - return make_pair(start->name, length->name); - return nullopt; + return std::make_pair(start->name, length->name); + return std::nullopt; } void DataFlowAnalyzer::joinKnowledge(Environment const& _olderEnvironment) diff --git a/libyul/optimiser/DeadCodeEliminator.cpp b/libyul/optimiser/DeadCodeEliminator.cpp index af8454684..71682584a 100644 --- a/libyul/optimiser/DeadCodeEliminator.cpp +++ b/libyul/optimiser/DeadCodeEliminator.cpp @@ -30,7 +30,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::yul; @@ -54,7 +53,7 @@ void DeadCodeEliminator::operator()(Block& _block) { TerminationFinder::ControlFlow controlFlowChange; size_t index; - tie(controlFlowChange, index) = TerminationFinder{m_dialect, &m_functionSideEffects}.firstUnconditionalControlFlowChange(_block.statements); + std::tie(controlFlowChange, index) = TerminationFinder{m_dialect, &m_functionSideEffects}.firstUnconditionalControlFlowChange(_block.statements); // Erase everything after the terminating statement that is not a function definition. if (controlFlowChange != TerminationFinder::ControlFlow::FlowOut && index != std::numeric_limits::max()) @@ -62,7 +61,7 @@ void DeadCodeEliminator::operator()(Block& _block) remove_if( _block.statements.begin() + static_cast(index) + 1, _block.statements.end(), - [] (Statement const& _s) { return !holds_alternative(_s); } + [] (Statement const& _s) { return !std::holds_alternative(_s); } ), _block.statements.end() ); diff --git a/libyul/optimiser/Disambiguator.cpp b/libyul/optimiser/Disambiguator.cpp index 6fa4b5522..34e6bc7e6 100644 --- a/libyul/optimiser/Disambiguator.cpp +++ b/libyul/optimiser/Disambiguator.cpp @@ -26,7 +26,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; diff --git a/libyul/optimiser/EqualStoreEliminator.cpp b/libyul/optimiser/EqualStoreEliminator.cpp index 542d8d50b..1e894608e 100644 --- a/libyul/optimiser/EqualStoreEliminator.cpp +++ b/libyul/optimiser/EqualStoreEliminator.cpp @@ -28,7 +28,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; @@ -50,17 +49,17 @@ void EqualStoreEliminator::visit(Statement& _statement) { // No need to consider potential changes through complex arguments since // isSimpleStore only returns something if the arguments are identifiers. - if (ExpressionStatement const* expression = get_if(&_statement)) + if (ExpressionStatement const* expression = std::get_if(&_statement)) { if (auto vars = isSimpleStore(StoreLoadLocation::Storage, *expression)) { - if (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 (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/EquivalentFunctionCombiner.cpp b/libyul/optimiser/EquivalentFunctionCombiner.cpp index 90091f6ae..10d15126e 100644 --- a/libyul/optimiser/EquivalentFunctionCombiner.cpp +++ b/libyul/optimiser/EquivalentFunctionCombiner.cpp @@ -23,7 +23,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; diff --git a/libyul/optimiser/EquivalentFunctionDetector.cpp b/libyul/optimiser/EquivalentFunctionDetector.cpp index b25600c21..de19887d8 100644 --- a/libyul/optimiser/EquivalentFunctionDetector.cpp +++ b/libyul/optimiser/EquivalentFunctionDetector.cpp @@ -25,7 +25,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; diff --git a/libyul/optimiser/ExpressionInliner.cpp b/libyul/optimiser/ExpressionInliner.cpp index ce0d1c739..cacf5843d 100644 --- a/libyul/optimiser/ExpressionInliner.cpp +++ b/libyul/optimiser/ExpressionInliner.cpp @@ -30,7 +30,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -50,14 +49,14 @@ void ExpressionInliner::operator()(FunctionDefinition& _fun) void ExpressionInliner::visit(Expression& _expression) { ASTModifier::visit(_expression); - if (holds_alternative(_expression)) + if (std::holds_alternative(_expression)) { FunctionCall& funCall = std::get(_expression); if (!m_inlinableFunctions.count(funCall.functionName.name)) return; FunctionDefinition const& fun = *m_inlinableFunctions.at(funCall.functionName.name); - map substitutions; + std::map substitutions; for (size_t i = 0; i < funCall.arguments.size(); i++) { Expression const& arg = funCall.arguments[i]; diff --git a/libyul/optimiser/ExpressionJoiner.cpp b/libyul/optimiser/ExpressionJoiner.cpp index 645bb6c3e..ee8d12b8b 100644 --- a/libyul/optimiser/ExpressionJoiner.cpp +++ b/libyul/optimiser/ExpressionJoiner.cpp @@ -34,7 +34,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -66,7 +65,7 @@ void ExpressionJoiner::operator()(Block& _block) void ExpressionJoiner::visit(Expression& _e) { - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) { Identifier const& identifier = std::get(_e); if (isLatestStatementVarDeclJoinable(identifier)) @@ -89,7 +88,7 @@ ExpressionJoiner::ExpressionJoiner(Block& _ast) m_references = VariableReferencesCounter::countReferences(_ast); } -void ExpressionJoiner::handleArguments(vector& _arguments) +void ExpressionJoiner::handleArguments(std::vector& _arguments) { // We have to fill from left to right, but we can only // fill if everything to the right is just an identifier @@ -101,7 +100,7 @@ void ExpressionJoiner::handleArguments(vector& _arguments) for (Expression const& arg: _arguments | ranges::views::reverse) { --i; - if (!holds_alternative(arg) && !holds_alternative(arg)) + if (!std::holds_alternative(arg) && !std::holds_alternative(arg)) break; } // i points to the last element that is neither an identifier nor a literal, @@ -124,7 +123,7 @@ void ExpressionJoiner::decrementLatestStatementPointer() void ExpressionJoiner::resetLatestStatementPointer() { m_currentBlock = nullptr; - m_latestStatementInBlock = numeric_limits::max(); + m_latestStatementInBlock = std::numeric_limits::max(); } Statement* ExpressionJoiner::latestStatement() @@ -138,7 +137,7 @@ Statement* ExpressionJoiner::latestStatement() bool ExpressionJoiner::isLatestStatementVarDeclJoinable(Identifier const& _identifier) { Statement const* statement = latestStatement(); - if (!statement || !holds_alternative(*statement)) + if (!statement || !std::holds_alternative(*statement)) return false; VariableDeclaration const& varDecl = std::get(*statement); if (varDecl.variables.size() != 1 || !varDecl.value) diff --git a/libyul/optimiser/ExpressionSimplifier.cpp b/libyul/optimiser/ExpressionSimplifier.cpp index 4a423fe46..c87c5df23 100644 --- a/libyul/optimiser/ExpressionSimplifier.cpp +++ b/libyul/optimiser/ExpressionSimplifier.cpp @@ -29,7 +29,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -49,8 +48,8 @@ void ExpressionSimplifier::visit(Expression& _expression) )) _expression = match->action().toExpression(debugDataOf(_expression), evmVersionFromDialect(m_dialect)); - if (auto* functionCall = get_if(&_expression)) - if (optional instruction = toEVMInstruction(m_dialect, functionCall->functionName.name)) + if (auto* functionCall = std::get_if(&_expression)) + if (std::optional instruction = toEVMInstruction(m_dialect, functionCall->functionName.name)) for (auto op: evmasm::SemanticInformation::readWriteOperations(*instruction)) if (op.startParameter && op.lengthParameter) { @@ -59,7 +58,7 @@ void ExpressionSimplifier::visit(Expression& _expression) if ( knownToBeZero(lengthArgument) && !knownToBeZero(startArgument) && - !holds_alternative(startArgument) + !std::holds_alternative(startArgument) ) startArgument = Literal{debugDataOf(startArgument), LiteralKind::Number, "0"_yulstring, {}}; } @@ -67,9 +66,9 @@ void ExpressionSimplifier::visit(Expression& _expression) bool ExpressionSimplifier::knownToBeZero(Expression const& _expression) const { - if (auto const* literal = get_if(&_expression)) + if (auto const* literal = std::get_if(&_expression)) return valueOfLiteral(*literal) == 0; - else if (auto const* identifier = get_if(&_expression)) + else if (auto const* identifier = std::get_if(&_expression)) return valueOfIdentifier(identifier->name) == 0; else return false; diff --git a/libyul/optimiser/ExpressionSplitter.cpp b/libyul/optimiser/ExpressionSplitter.cpp index 713e0e804..986bcb097 100644 --- a/libyul/optimiser/ExpressionSplitter.cpp +++ b/libyul/optimiser/ExpressionSplitter.cpp @@ -30,7 +30,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -75,11 +74,11 @@ void ExpressionSplitter::operator()(ForLoop& _loop) void ExpressionSplitter::operator()(Block& _block) { - vector saved; + std::vector saved; swap(saved, m_statementsToPrefix); - function>(Statement&)> f = - [&](Statement& _statement) -> std::optional> { + std::function>(Statement&)> f = + [&](Statement& _statement) -> std::optional> { m_statementsToPrefix.clear(); visit(_statement); if (m_statementsToPrefix.empty()) @@ -94,18 +93,18 @@ void ExpressionSplitter::operator()(Block& _block) void ExpressionSplitter::outlineExpression(Expression& _expr) { - if (holds_alternative(_expr)) + if (std::holds_alternative(_expr)) return; visit(_expr); - shared_ptr debugData = debugDataOf(_expr); + std::shared_ptr debugData = debugDataOf(_expr); YulString var = m_nameDispenser.newName({}); YulString type = m_typeInfo.typeOf(_expr); m_statementsToPrefix.emplace_back(VariableDeclaration{ debugData, {{TypedName{debugData, var, type}}}, - make_unique(std::move(_expr)) + std::make_unique(std::move(_expr)) }); _expr = Identifier{debugData, var}; m_typeInfo.setVariableType(var, type); diff --git a/libyul/optimiser/ForLoopConditionIntoBody.cpp b/libyul/optimiser/ForLoopConditionIntoBody.cpp index cf7c6814e..2dd0832c4 100644 --- a/libyul/optimiser/ForLoopConditionIntoBody.cpp +++ b/libyul/optimiser/ForLoopConditionIntoBody.cpp @@ -22,7 +22,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -35,17 +34,17 @@ void ForLoopConditionIntoBody::operator()(ForLoop& _forLoop) { if ( m_dialect.booleanNegationFunction() && - !holds_alternative(*_forLoop.condition) && - !holds_alternative(*_forLoop.condition) + !std::holds_alternative(*_forLoop.condition) && + !std::holds_alternative(*_forLoop.condition) ) { - shared_ptr debugData = debugDataOf(*_forLoop.condition); + std::shared_ptr debugData = debugDataOf(*_forLoop.condition); _forLoop.body.statements.emplace( begin(_forLoop.body.statements), If { debugData, - make_unique( + std::make_unique( FunctionCall { debugData, {debugData, m_dialect.booleanNegationFunction()->name}, @@ -55,7 +54,7 @@ void ForLoopConditionIntoBody::operator()(ForLoop& _forLoop) Block {debugData, util::make_vector(Break{{}})} } ); - _forLoop.condition = make_unique( + _forLoop.condition = std::make_unique( Literal { debugData, LiteralKind::Boolean, diff --git a/libyul/optimiser/ForLoopConditionOutOfBody.cpp b/libyul/optimiser/ForLoopConditionOutOfBody.cpp index 98a37d9fc..363ecdf0c 100644 --- a/libyul/optimiser/ForLoopConditionOutOfBody.cpp +++ b/libyul/optimiser/ForLoopConditionOutOfBody.cpp @@ -23,7 +23,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -38,32 +37,32 @@ void ForLoopConditionOutOfBody::operator()(ForLoop& _forLoop) if ( !m_dialect.booleanNegationFunction() || - !holds_alternative(*_forLoop.condition) || + !std::holds_alternative(*_forLoop.condition) || valueOfLiteral(std::get(*_forLoop.condition)) == u256(0) || _forLoop.body.statements.empty() || - !holds_alternative(_forLoop.body.statements.front()) + !std::holds_alternative(_forLoop.body.statements.front()) ) return; If& firstStatement = std::get(_forLoop.body.statements.front()); if ( firstStatement.body.statements.empty() || - !holds_alternative(firstStatement.body.statements.front()) + !std::holds_alternative(firstStatement.body.statements.front()) ) return; if (!SideEffectsCollector(m_dialect, *firstStatement.condition).movable()) return; YulString iszero = m_dialect.booleanNegationFunction()->name; - shared_ptr debugData = debugDataOf(*firstStatement.condition); + std::shared_ptr debugData = debugDataOf(*firstStatement.condition); if ( - holds_alternative(*firstStatement.condition) && + std::holds_alternative(*firstStatement.condition) && std::get(*firstStatement.condition).functionName.name == iszero ) - _forLoop.condition = make_unique(std::move(std::get(*firstStatement.condition).arguments.front())); + _forLoop.condition = std::make_unique(std::move(std::get(*firstStatement.condition).arguments.front())); else - _forLoop.condition = make_unique(FunctionCall{ + _forLoop.condition = std::make_unique(FunctionCall{ debugData, Identifier{debugData, iszero}, util::make_vector( diff --git a/libyul/optimiser/ForLoopInitRewriter.cpp b/libyul/optimiser/ForLoopInitRewriter.cpp index 7cfa16b4f..b0696f3b2 100644 --- a/libyul/optimiser/ForLoopInitRewriter.cpp +++ b/libyul/optimiser/ForLoopInitRewriter.cpp @@ -22,7 +22,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -30,15 +29,15 @@ void ForLoopInitRewriter::operator()(Block& _block) { util::iterateReplacing( _block.statements, - [&](Statement& _stmt) -> std::optional> + [&](Statement& _stmt) -> std::optional> { - if (holds_alternative(_stmt)) + if (std::holds_alternative(_stmt)) { auto& forLoop = std::get(_stmt); (*this)(forLoop.pre); (*this)(forLoop.body); (*this)(forLoop.post); - vector rewrite; + std::vector rewrite; swap(rewrite, forLoop.pre.statements); rewrite.emplace_back(std::move(forLoop)); return { std::move(rewrite) }; diff --git a/libyul/optimiser/FullInliner.cpp b/libyul/optimiser/FullInliner.cpp index ebf82e763..6e4d84971 100644 --- a/libyul/optimiser/FullInliner.cpp +++ b/libyul/optimiser/FullInliner.cpp @@ -41,7 +41,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -63,15 +62,15 @@ FullInliner::FullInliner(Block& _ast, NameDispenser& _dispenser, Dialect const& SSAValueTracker tracker; tracker(m_ast); for (auto const& ssaValue: tracker.values()) - if (ssaValue.second && holds_alternative(*ssaValue.second)) + if (ssaValue.second && std::holds_alternative(*ssaValue.second)) m_constants.emplace(ssaValue.first); // Store size of global statements. m_functionSizes[YulString{}] = CodeSize::codeSize(_ast); - map references = ReferencesCounter::countReferences(m_ast); + std::map references = ReferencesCounter::countReferences(m_ast); for (auto& statement: m_ast.statements) { - if (!holds_alternative(statement)) + if (!std::holds_alternative(statement)) continue; FunctionDefinition& fun = std::get(statement); m_functions[fun.name] = &fun; @@ -84,7 +83,7 @@ FullInliner::FullInliner(Block& _ast, NameDispenser& _dispenser, Dialect const& } // Check for memory guard. - vector memoryGuardCalls = FunctionCallFinder::run( + std::vector memoryGuardCalls = FunctionCallFinder::run( _ast, "memoryguard"_yulstring ); @@ -105,10 +104,10 @@ 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. - map depths = callDepths(); - vector functions; + std::map depths = callDepths(); + std::vector functions; for (auto& statement: m_ast.statements) - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) functions.emplace_back(&std::get(statement)); std::stable_sort(functions.begin(), functions.end(), [depths]( FunctionDefinition const* _a, @@ -123,11 +122,11 @@ void FullInliner::run(Pass _pass) } for (auto& statement: m_ast.statements) - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) handleBlock({}, std::get(statement)); } -map FullInliner::callDepths() const +std::map FullInliner::callDepths() const { CallGraph cg = CallGraphGenerator::callGraph(m_ast); cg.functionCalls.erase(""_yulstring); @@ -140,12 +139,12 @@ map FullInliner::callDepths() const else ++it; - map depths; + std::map depths; size_t currentDepth = 0; while (true) { - vector removed; + std::vector removed; for (auto it = cg.functionCalls.begin(); it != cg.functionCalls.end();) { auto const& [fun, callees] = *it; @@ -192,7 +191,7 @@ bool FullInliner::shallInline(FunctionCall const& _funCall, YulString _callSite) // No inlining of calls where argument expressions may have side-effects. // To avoid running into this, make sure that ExpressionSplitter runs before FullInliner. for (auto const& argument: _funCall.arguments) - if (!holds_alternative(argument) && !holds_alternative(argument)) + if (!std::holds_alternative(argument) && !std::holds_alternative(argument)) return false; // Inline really, really tiny functions @@ -226,8 +225,8 @@ bool FullInliner::shallInline(FunctionCall const& _funCall, YulString _callSite) // Constant arguments might provide a means for further optimization, so they cause a bonus. bool constantArg = false; for (auto const& argument: _funCall.arguments) - if (holds_alternative(argument) || ( - holds_alternative(argument) && + if (std::holds_alternative(argument) || ( + std::holds_alternative(argument) && m_constants.count(std::get(argument).name) )) { @@ -255,20 +254,20 @@ void FullInliner::handleBlock(YulString _currentFunctionName, Block& _block) bool FullInliner::recursive(FunctionDefinition const& _fun) const { - map references = ReferencesCounter::countReferences(_fun); + std::map references = ReferencesCounter::countReferences(_fun); return references[_fun.name] > 0; } void InlineModifier::operator()(Block& _block) { - function>(Statement&)> f = [&](Statement& _statement) -> std::optional> { + std::function>(Statement&)> f = [&](Statement& _statement) -> std::optional> { visit(_statement); return tryInlineStatement(_statement); }; util::iterateReplacing(_block.statements, f); } -std::optional> InlineModifier::tryInlineStatement(Statement& _statement) +std::optional> InlineModifier::tryInlineStatement(Statement& _statement) { // Only inline for expression statements, assignments and variable declarations. Expression* e = std::visit(util::GenericVisitor{ @@ -290,10 +289,10 @@ std::optional> InlineModifier::tryInlineStatement(Statement& _ return {}; } -vector InlineModifier::performInline(Statement& _statement, FunctionCall& _funCall) +std::vector InlineModifier::performInline(Statement& _statement, FunctionCall& _funCall) { - vector newStatements; - map variableReplacements; + std::vector newStatements; + std::map variableReplacements; FunctionDefinition* function = m_driver.function(_funCall.functionName.name); assertThrow(!!function, OptimizerException, "Attempt to inline invalid function."); @@ -307,9 +306,9 @@ vector InlineModifier::performInline(Statement& _statement, FunctionC variableReplacements[_existingVariable.name] = newName; VariableDeclaration varDecl{_funCall.debugData, {{_funCall.debugData, newName, _existingVariable.type}}, {}}; if (_value) - varDecl.value = make_unique(std::move(*_value)); + varDecl.value = std::make_unique(std::move(*_value)); else - varDecl.value = make_unique(m_dialect.zeroLiteralForType(varDecl.variables.front().type)); + varDecl.value = std::make_unique(m_dialect.zeroLiteralForType(varDecl.variables.front().type)); newStatements.emplace_back(std::move(varDecl)); }; @@ -329,7 +328,7 @@ vector InlineModifier::performInline(Statement& _statement, FunctionC newStatements.emplace_back(Assignment{ _assignment.debugData, {_assignment.variableNames[i]}, - make_unique(Identifier{ + std::make_unique(Identifier{ _assignment.debugData, variableReplacements.at(function->returnVariables[i].name) }) @@ -341,7 +340,7 @@ vector InlineModifier::performInline(Statement& _statement, FunctionC newStatements.emplace_back(VariableDeclaration{ _varDecl.debugData, {std::move(_varDecl.variables[i])}, - make_unique(Identifier{ + std::make_unique(Identifier{ _varDecl.debugData, variableReplacements.at(function->returnVariables[i].name) }) diff --git a/libyul/optimiser/FunctionCallFinder.cpp b/libyul/optimiser/FunctionCallFinder.cpp index b8f206440..9d94dc5f9 100644 --- a/libyul/optimiser/FunctionCallFinder.cpp +++ b/libyul/optimiser/FunctionCallFinder.cpp @@ -18,11 +18,10 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; -vector FunctionCallFinder::run(Block& _block, YulString _functionName) +std::vector FunctionCallFinder::run(Block& _block, YulString _functionName) { FunctionCallFinder functionCallFinder(_functionName); functionCallFinder(_block); diff --git a/libyul/optimiser/FunctionGrouper.cpp b/libyul/optimiser/FunctionGrouper.cpp index 41fb75554..5f649d189 100644 --- a/libyul/optimiser/FunctionGrouper.cpp +++ b/libyul/optimiser/FunctionGrouper.cpp @@ -24,7 +24,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -34,12 +33,12 @@ void FunctionGrouper::operator()(Block& _block) if (alreadyGrouped(_block)) return; - vector reordered; + std::vector reordered; reordered.emplace_back(Block{_block.debugData, {}}); for (auto&& statement: _block.statements) { - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) reordered.emplace_back(std::move(statement)); else std::get(reordered.front()).statements.emplace_back(std::move(statement)); @@ -51,10 +50,10 @@ bool FunctionGrouper::alreadyGrouped(Block const& _block) { if (_block.statements.empty()) return false; - if (!holds_alternative(_block.statements.front())) + if (!std::holds_alternative(_block.statements.front())) return false; for (size_t i = 1; i < _block.statements.size(); ++i) - if (!holds_alternative(_block.statements.at(i))) + if (!std::holds_alternative(_block.statements.at(i))) return false; return true; } diff --git a/libyul/optimiser/FunctionHoister.cpp b/libyul/optimiser/FunctionHoister.cpp index 5d5cf7d12..32df3b121 100644 --- a/libyul/optimiser/FunctionHoister.cpp +++ b/libyul/optimiser/FunctionHoister.cpp @@ -27,7 +27,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -38,7 +37,7 @@ void FunctionHoister::operator()(Block& _block) for (auto&& statement: _block.statements) { std::visit(*this, statement); - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) { m_functions.emplace_back(std::move(statement)); statement = Block{_block.debugData, {}}; diff --git a/libyul/optimiser/FunctionSpecializer.cpp b/libyul/optimiser/FunctionSpecializer.cpp index 4555e2f8f..7e6d48632 100644 --- a/libyul/optimiser/FunctionSpecializer.cpp +++ b/libyul/optimiser/FunctionSpecializer.cpp @@ -32,7 +32,6 @@ #include -using namespace std; using namespace solidity::util; using namespace solidity::yul; @@ -40,11 +39,11 @@ FunctionSpecializer::LiteralArguments FunctionSpecializer::specializableArgument FunctionCall const& _f ) { - auto heuristic = [&](Expression const& _e) -> optional + auto heuristic = [&](Expression const& _e) -> std::optional { - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) return ASTCopier{}.translate(_e); - return nullopt; + return std::nullopt; }; return applyMap(_f.arguments, heuristic); @@ -68,7 +67,7 @@ void FunctionSpecializer::operator()(FunctionCall& _f) YulString oldName = std::move(_f.functionName.name); auto newName = m_nameDispenser.newName(oldName); - m_oldToNewMap[oldName].emplace_back(make_pair(newName, arguments)); + m_oldToNewMap[oldName].emplace_back(std::make_pair(newName, arguments)); _f.functionName.name = newName; _f.arguments = util::filter( @@ -86,27 +85,27 @@ FunctionDefinition FunctionSpecializer::specialize( { yulAssert(_arguments.size() == _f.parameters.size(), ""); - map translatedNames = applyMap( + std::map translatedNames = applyMap( NameCollector{_f, NameCollector::OnlyVariables}.names(), - [&](auto& _name) -> pair + [&](auto& _name) -> std::pair { - return make_pair(_name, m_nameDispenser.newName(_name)); + return std::make_pair(_name, m_nameDispenser.newName(_name)); }, - map{} + std::map{} ); - FunctionDefinition newFunction = get(FunctionCopier{translatedNames}(_f)); + FunctionDefinition newFunction = std::get(FunctionCopier{translatedNames}(_f)); // Function parameters that will be specialized inside the body are converted into variable // declarations. - vector missingVariableDeclarations; + std::vector missingVariableDeclarations; for (auto&& [index, argument]: _arguments | ranges::views::enumerate) if (argument) missingVariableDeclarations.emplace_back( VariableDeclaration{ _f.debugData, - vector{newFunction.parameters[index]}, - make_unique(std::move(*argument)) + std::vector{newFunction.parameters[index]}, + std::make_unique(std::move(*argument)) } ); @@ -134,15 +133,15 @@ void FunctionSpecializer::run(OptimiserStepContext& _context, Block& _ast) }; f(_ast); - iterateReplacing(_ast.statements, [&](Statement& _s) -> optional> + iterateReplacing(_ast.statements, [&](Statement& _s) -> std::optional> { - if (holds_alternative(_s)) + if (std::holds_alternative(_s)) { - auto& functionDefinition = get(_s); + auto& functionDefinition = std::get(_s); if (f.m_oldToNewMap.count(functionDefinition.name)) { - vector out = applyMap( + std::vector out = applyMap( f.m_oldToNewMap.at(functionDefinition.name), [&](auto& _p) -> Statement { @@ -153,6 +152,6 @@ void FunctionSpecializer::run(OptimiserStepContext& _context, Block& _ast) } } - return nullopt; + return std::nullopt; }); } diff --git a/libyul/optimiser/InlinableExpressionFunctionFinder.cpp b/libyul/optimiser/InlinableExpressionFunctionFinder.cpp index 8c9b80265..0bb4d368d 100644 --- a/libyul/optimiser/InlinableExpressionFunctionFinder.cpp +++ b/libyul/optimiser/InlinableExpressionFunctionFinder.cpp @@ -24,7 +24,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -46,7 +45,7 @@ void InlinableExpressionFunctionFinder::operator()(FunctionDefinition const& _fu { YulString retVariable = _function.returnVariables.front().name; Statement const& bodyStatement = _function.body.statements.front(); - if (holds_alternative(bodyStatement)) + if (std::holds_alternative(bodyStatement)) { Assignment const& assignment = std::get(bodyStatement); if (assignment.variableNames.size() == 1 && assignment.variableNames.front().name == retVariable) @@ -57,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 = 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/KnowledgeBase.cpp b/libyul/optimiser/KnowledgeBase.cpp index e01090146..c280ecf14 100644 --- a/libyul/optimiser/KnowledgeBase.cpp +++ b/libyul/optimiser/KnowledgeBase.cpp @@ -29,36 +29,35 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; -KnowledgeBase::KnowledgeBase(map const& _ssaValues): +KnowledgeBase::KnowledgeBase(std::map const& _ssaValues): m_valuesAreSSA(true), m_variableValues([_ssaValues](YulString _var) { return util::valueOrNullptr(_ssaValues, _var); }) {} bool KnowledgeBase::knownToBeDifferent(YulString _a, YulString _b) { - if (optional difference = differenceIfKnownConstant(_a, _b)) + if (std::optional difference = differenceIfKnownConstant(_a, _b)) return difference != 0; return false; } -optional KnowledgeBase::differenceIfKnownConstant(YulString _a, YulString _b) +std::optional KnowledgeBase::differenceIfKnownConstant(YulString _a, YulString _b) { VariableOffset offA = explore(_a); VariableOffset offB = explore(_b); if (offA.reference == offB.reference) return offA.offset - offB.offset; else - return nullopt; + return std::nullopt; } bool KnowledgeBase::knownToBeDifferentByAtLeast32(YulString _a, YulString _b) { - if (optional difference = differenceIfKnownConstant(_a, _b)) + if (std::optional difference = differenceIfKnownConstant(_a, _b)) return difference >= 32 && difference <= u256(0) - 32; return false; @@ -69,19 +68,19 @@ bool KnowledgeBase::knownToBeZero(YulString _a) return valueIfKnownConstant(_a) == 0; } -optional KnowledgeBase::valueIfKnownConstant(YulString _a) +std::optional KnowledgeBase::valueIfKnownConstant(YulString _a) { return explore(_a).absoluteValue(); } -optional KnowledgeBase::valueIfKnownConstant(Expression const& _expression) +std::optional KnowledgeBase::valueIfKnownConstant(Expression const& _expression) { - if (Identifier const* ident = get_if(&_expression)) + if (Identifier const* ident = std::get_if(&_expression)) return valueIfKnownConstant(ident->name); - else if (Literal const* lit = get_if(&_expression)) + else if (Literal const* lit = std::get_if(&_expression)) return valueOfLiteral(*lit); else - return nullopt; + return std::nullopt; } KnowledgeBase::VariableOffset KnowledgeBase::explore(YulString _var) @@ -105,24 +104,24 @@ KnowledgeBase::VariableOffset KnowledgeBase::explore(YulString _var) } if (value) - if (optional offset = explore(*value)) + if (std::optional offset = explore(*value)) return setOffset(_var, *offset); return setOffset(_var, VariableOffset{_var, 0}); } -optional KnowledgeBase::explore(Expression const& _value) +std::optional KnowledgeBase::explore(Expression const& _value) { - if (Literal const* literal = get_if(&_value)) + if (Literal const* literal = std::get_if(&_value)) return VariableOffset{YulString{}, valueOfLiteral(*literal)}; - else if (Identifier const* identifier = get_if(&_value)) + else if (Identifier const* identifier = std::get_if(&_value)) return explore(identifier->name); - else if (FunctionCall const* f = get_if(&_value)) + else if (FunctionCall const* f = std::get_if(&_value)) { if (f->functionName.name == "add"_yulstring) { - if (optional a = explore(f->arguments[0])) - if (optional b = explore(f->arguments[1])) + if (std::optional a = explore(f->arguments[0])) + if (std::optional b = explore(f->arguments[1])) { u256 offset = a->offset + b->offset; if (a->isAbsolute()) @@ -134,8 +133,8 @@ optional KnowledgeBase::explore(Expression const& } } else if (f->functionName.name == "sub"_yulstring) - if (optional a = explore(f->arguments[0])) - if (optional b = explore(f->arguments[1])) + 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) @@ -146,7 +145,7 @@ optional KnowledgeBase::explore(Expression const& } } - return nullopt; + return std::nullopt; } Expression const* KnowledgeBase::valueOf(YulString _var) @@ -175,7 +174,7 @@ void KnowledgeBase::reset(YulString _var) m_groupMembers[offset->reference].erase(_var); m_offsets.erase(_var); } - if (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()) diff --git a/libyul/optimiser/LoadResolver.cpp b/libyul/optimiser/LoadResolver.cpp index ce0ce730e..84094c33e 100644 --- a/libyul/optimiser/LoadResolver.cpp +++ b/libyul/optimiser/LoadResolver.cpp @@ -36,7 +36,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::util; using namespace solidity::evmasm; @@ -65,8 +64,8 @@ void LoadResolver::visit(Expression& _e) tryResolve(_e, StoreLoadLocation::Storage, funCall->arguments); else if (!m_containsMSize && funCall->functionName.name == m_dialect.hashFunction({})) { - Identifier const* start = get_if(&funCall->arguments.at(0)); - Identifier const* length = get_if(&funCall->arguments.at(1)); + Identifier const* start = std::get_if(&funCall->arguments.at(0)); + Identifier const* length = std::get_if(&funCall->arguments.at(1)); if (start && length) if (auto const& value = keccakValue(start->name, length->name)) if (inScope(*value)) @@ -82,10 +81,10 @@ void LoadResolver::visit(Expression& _e) void LoadResolver::tryResolve( Expression& _e, StoreLoadLocation _location, - vector const& _arguments + std::vector const& _arguments ) { - if (_arguments.empty() || !holds_alternative(_arguments.at(0))) + if (_arguments.empty() || !std::holds_alternative(_arguments.at(0))) return; YulString key = std::get(_arguments.at(0)).name; @@ -126,7 +125,7 @@ void LoadResolver::tryEvaluateKeccak( {}, LiteralKind::Number, // a dummy 256-bit number to represent the Keccak256 hash. - YulString{numeric_limits::max().str()}, + YulString{std::numeric_limits::max().str()}, {} } ); @@ -138,11 +137,11 @@ void LoadResolver::tryEvaluateKeccak( if (costOfLiteral > costOfKeccak) return; - optional value = memoryValue(memoryKey->name); + std::optional value = memoryValue(memoryKey->name); if (value && inScope(*value)) { - optional memoryContent = valueOfIdentifier(*value); - optional byteLength = valueOfIdentifier(length->name); + std::optional memoryContent = valueOfIdentifier(*value); + std::optional byteLength = valueOfIdentifier(length->name); if (memoryContent && byteLength && *byteLength <= 32) { bytes contentAsBytes = toBigEndian(*memoryContent); diff --git a/libyul/optimiser/LoopInvariantCodeMotion.cpp b/libyul/optimiser/LoopInvariantCodeMotion.cpp index 87454dc96..da3c5e3e0 100644 --- a/libyul/optimiser/LoopInvariantCodeMotion.cpp +++ b/libyul/optimiser/LoopInvariantCodeMotion.cpp @@ -27,16 +27,15 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; void LoopInvariantCodeMotion::run(OptimiserStepContext& _context, Block& _ast) { - map functionSideEffects = + std::map functionSideEffects = SideEffectsPropagator::sideEffects(_context.dialect, CallGraphGenerator::callGraph(_ast)); bool containsMSize = MSizeFinder::containsMSize(_context.dialect, _ast); - set ssaVars = SSAValueTracker::ssaVariables(_ast); + std::set ssaVars = SSAValueTracker::ssaVariables(_ast); LoopInvariantCodeMotion{_context.dialect, ssaVars, functionSideEffects, containsMSize}(_ast); } @@ -44,11 +43,11 @@ void LoopInvariantCodeMotion::operator()(Block& _block) { util::iterateReplacing( _block.statements, - [&](Statement& _s) -> optional> + [&](Statement& _s) -> std::optional> { visit(_s); - if (holds_alternative(_s)) - return rewriteLoop(get(_s)); + if (std::holds_alternative(_s)) + return rewriteLoop(std::get(_s)); else return {}; } @@ -57,7 +56,7 @@ void LoopInvariantCodeMotion::operator()(Block& _block) bool LoopInvariantCodeMotion::canBePromoted( VariableDeclaration const& _varDecl, - set const& _varsDefinedInCurrentScope, + std::set const& _varsDefinedInCurrentScope, SideEffects const& _forLoopSideEffects ) const { @@ -81,29 +80,29 @@ bool LoopInvariantCodeMotion::canBePromoted( return true; } -optional> LoopInvariantCodeMotion::rewriteLoop(ForLoop& _for) +std::optional> LoopInvariantCodeMotion::rewriteLoop(ForLoop& _for) { assertThrow(_for.pre.statements.empty(), OptimizerException, ""); auto forLoopSideEffects = SideEffectsCollector{m_dialect, _for, &m_functionSideEffects}.sideEffects(); - vector replacement; + std::vector replacement; for (Block* block: {&_for.post, &_for.body}) { - set varsDefinedInScope; + std::set varsDefinedInScope; util::iterateReplacing( block->statements, - [&](Statement& _s) -> optional> + [&](Statement& _s) -> std::optional> { - if (holds_alternative(_s)) + if (std::holds_alternative(_s)) { VariableDeclaration const& varDecl = std::get(_s); if (canBePromoted(varDecl, varsDefinedInScope, forLoopSideEffects)) { replacement.emplace_back(std::move(_s)); // Do not add the variables declared here to varsDefinedInScope because we are moving them. - return vector{}; + return std::vector{}; } for (auto const& var: varDecl.variables) varsDefinedInScope.insert(var.name); diff --git a/libyul/optimiser/Metrics.cpp b/libyul/optimiser/Metrics.cpp index a48cbf91b..42845f3b6 100644 --- a/libyul/optimiser/Metrics.cpp +++ b/libyul/optimiser/Metrics.cpp @@ -30,34 +30,33 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; size_t CodeWeights::costOf(Statement const& _statement) const { - if (holds_alternative(_statement)) + if (std::holds_alternative(_statement)) return expressionStatementCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return assignmentCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return variableDeclarationCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return functionDefinitionCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return ifCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return switchCost + caseCost * std::get(_statement).cases.size(); - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return forLoopCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return breakCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return continueCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return leaveCost; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return blockCost; else yulAssert(false, "If you add a new statement type, you must update CodeWeights."); @@ -65,11 +64,11 @@ size_t CodeWeights::costOf(Statement const& _statement) const size_t CodeWeights::costOf(Expression const& _expression) const { - if (holds_alternative(_expression)) + if (std::holds_alternative(_expression)) return functionCallCost; - else if (holds_alternative(_expression)) + else if (std::holds_alternative(_expression)) return identifierCost; - else if (Literal const* literal = get_if(&_expression)) + else if (Literal const* literal = std::get_if(&_expression)) { // Avoid strings because they could be longer than 32 bytes. if (literal->kind != LiteralKind::String && valueOfLiteral(*literal) == 0) @@ -112,7 +111,7 @@ size_t CodeSize::codeSizeIncludingFunctions(Block const& _block, CodeWeights con void CodeSize::visit(Statement const& _statement) { - if (holds_alternative(_statement) && m_ignoreFunctions) + if (std::holds_alternative(_statement) && m_ignoreFunctions) return; m_size += m_weights.costOf(_statement); diff --git a/libyul/optimiser/NameCollector.cpp b/libyul/optimiser/NameCollector.cpp index 2664b8f6d..7fb0c7ed2 100644 --- a/libyul/optimiser/NameCollector.cpp +++ b/libyul/optimiser/NameCollector.cpp @@ -23,7 +23,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; @@ -60,21 +59,21 @@ void ReferencesCounter::operator()(FunctionCall const& _funCall) ASTWalker::operator()(_funCall); } -map ReferencesCounter::countReferences(Block const& _block) +std::map ReferencesCounter::countReferences(Block const& _block) { ReferencesCounter counter; counter(_block); return std::move(counter.m_references); } -map ReferencesCounter::countReferences(FunctionDefinition const& _function) +std::map ReferencesCounter::countReferences(FunctionDefinition const& _function) { ReferencesCounter counter; counter(_function); return std::move(counter.m_references); } -map ReferencesCounter::countReferences(Expression const& _expression) +std::map ReferencesCounter::countReferences(Expression const& _expression) { ReferencesCounter counter; counter.visit(_expression); @@ -86,28 +85,28 @@ void VariableReferencesCounter::operator()(Identifier const& _identifier) ++m_references[_identifier.name]; } -map VariableReferencesCounter::countReferences(Block const& _block) +std::map VariableReferencesCounter::countReferences(Block const& _block) { VariableReferencesCounter counter; counter(_block); return std::move(counter.m_references); } -map VariableReferencesCounter::countReferences(FunctionDefinition const& _function) +std::map VariableReferencesCounter::countReferences(FunctionDefinition const& _function) { VariableReferencesCounter counter; counter(_function); return std::move(counter.m_references); } -map VariableReferencesCounter::countReferences(Expression const& _expression) +std::map VariableReferencesCounter::countReferences(Expression const& _expression) { VariableReferencesCounter counter; counter.visit(_expression); return std::move(counter.m_references); } -map VariableReferencesCounter::countReferences(Statement const& _statement) +std::map VariableReferencesCounter::countReferences(Statement const& _statement) { VariableReferencesCounter counter; counter.visit(_statement); @@ -149,7 +148,7 @@ std::set solidity::yul::assignedVariableNames(Block const& _code) return names; } -map solidity::yul::allFunctionDefinitions(Block const& _block) +std::map solidity::yul::allFunctionDefinitions(Block const& _block) { std::map result; forEach(_block, [&](FunctionDefinition const& _function) { diff --git a/libyul/optimiser/NameDispenser.cpp b/libyul/optimiser/NameDispenser.cpp index d43b6802f..3a8db5ee4 100644 --- a/libyul/optimiser/NameDispenser.cpp +++ b/libyul/optimiser/NameDispenser.cpp @@ -29,18 +29,17 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::util; -NameDispenser::NameDispenser(Dialect const& _dialect, Block const& _ast, 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, set _usedNames): +NameDispenser::NameDispenser(Dialect const& _dialect, std::set _usedNames): m_dialect(_dialect), m_usedNames(std::move(_usedNames)) { @@ -52,7 +51,7 @@ YulString NameDispenser::newName(YulString _nameHint) while (illegalName(name)) { m_counter++; - name = YulString(_nameHint.str() + "_" + to_string(m_counter)); + name = YulString(_nameHint.str() + "_" + std::to_string(m_counter)); } m_usedNames.emplace(name); return name; diff --git a/libyul/optimiser/NameDisplacer.cpp b/libyul/optimiser/NameDisplacer.cpp index 4d1a61a8e..4d0d217d8 100644 --- a/libyul/optimiser/NameDisplacer.cpp +++ b/libyul/optimiser/NameDisplacer.cpp @@ -23,7 +23,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -64,7 +63,7 @@ void NameDisplacer::operator()(Block& _block) // First replace all the names of function definitions // because of scoping. for (auto& st: _block.statements) - if (holds_alternative(st)) + if (std::holds_alternative(st)) checkAndReplaceNew(std::get(st).name); ASTModifier::operator()(_block); diff --git a/libyul/optimiser/NameSimplifier.cpp b/libyul/optimiser/NameSimplifier.cpp index 0eb568beb..f7d732547 100644 --- a/libyul/optimiser/NameSimplifier.cpp +++ b/libyul/optimiser/NameSimplifier.cpp @@ -28,7 +28,6 @@ #include using namespace solidity::yul; -using namespace std; NameSimplifier::NameSimplifier(OptimiserStepContext& _context, Block const& _ast): m_context(_context) @@ -54,7 +53,7 @@ void NameSimplifier::operator()(VariableDeclaration& _varDecl) ASTModifier::operator()(_varDecl); } -void NameSimplifier::renameVariables(vector& _variables) +void NameSimplifier::renameVariables(std::vector& _variables) { for (TypedName& typedName: _variables) translate(typedName.name); @@ -78,31 +77,31 @@ void NameSimplifier::findSimplification(YulString const& _name) if (m_translations.count(_name)) return; - string name = _name.str(); + std::string name = _name.str(); - static auto replacements = vector>{ - {regex("_\\$|\\$_"), "_"}, // remove type mangling delimiters - {regex("_[0-9]+([^0-9a-fA-Fx])"), "$1"}, // removes AST IDs that are not hex. - {regex("_[0-9]+$"), ""}, // removes AST IDs that are not hex. - {regex("_t_"), "_"}, // remove type prefixes - {regex("__"), "_"}, - {regex("(abi_..code.*)_to_.*"), "$1"}, // removes _to... for abi functions - {regex("(stringliteral_?[0-9a-f][0-9a-f][0-9a-f][0-9a-f])[0-9a-f]*"), "$1"}, // shorten string literal - {regex("tuple_"), ""}, - {regex("_memory_ptr"), ""}, - {regex("_calldata_ptr"), "_calldata"}, - {regex("_fromStack"), ""}, - {regex("_storage_storage"), "_storage"}, - {regex("(storage.*)_?storage"), "$1"}, - {regex("_memory_memory"), "_memory"}, - {regex("_contract\\$_([^_]*)_?"), "$1_"}, - {regex("index_access_(t_)?array"), "index_access"}, - {regex("[0-9]*_$"), ""} + static auto replacements = std::vector>{ + {std::regex("_\\$|\\$_"), "_"}, // remove type mangling delimiters + {std::regex("_[0-9]+([^0-9a-fA-Fx])"), "$1"}, // removes AST IDs that are not hex. + {std::regex("_[0-9]+$"), ""}, // removes AST IDs that are not hex. + {std::regex("_t_"), "_"}, // remove type prefixes + {std::regex("__"), "_"}, + {std::regex("(abi_..code.*)_to_.*"), "$1"}, // removes _to... for abi functions + {std::regex("(stringliteral_?[0-9a-f][0-9a-f][0-9a-f][0-9a-f])[0-9a-f]*"), "$1"}, // shorten string literal + {std::regex("tuple_"), ""}, + {std::regex("_memory_ptr"), ""}, + {std::regex("_calldata_ptr"), "_calldata"}, + {std::regex("_fromStack"), ""}, + {std::regex("_storage_storage"), "_storage"}, + {std::regex("(storage.*)_?storage"), "$1"}, + {std::regex("_memory_memory"), "_memory"}, + {std::regex("_contract\\$_([^_]*)_?"), "$1_"}, + {std::regex("index_access_(t_)?array"), "index_access"}, + {std::regex("[0-9]*_$"), ""} }; for (auto const& [pattern, substitute]: replacements) { - string candidate = regex_replace(name, pattern, substitute); + std::string candidate = regex_replace(name, pattern, substitute); if (!candidate.empty() && !m_context.dispenser.illegalName(YulString(candidate))) name = candidate; } diff --git a/libyul/optimiser/OptimizerUtilities.cpp b/libyul/optimiser/OptimizerUtilities.cpp index bd474f748..17f912762 100644 --- a/libyul/optimiser/OptimizerUtilities.cpp +++ b/libyul/optimiser/OptimizerUtilities.cpp @@ -31,7 +31,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::langutil; using namespace solidity::util; @@ -40,7 +39,7 @@ using namespace solidity::yul; void yul::removeEmptyBlocks(Block& _block) { auto isEmptyBlock = [](Statement const& _st) -> bool { - return holds_alternative(_st) && std::get(_st).statements.empty(); + return std::holds_alternative(_st) && std::get(_st).statements.empty(); }; ranges::actions::remove_if(_block.statements, isEmptyBlock); } @@ -50,12 +49,12 @@ bool yul::isRestrictedIdentifier(Dialect const& _dialect, YulString const& _iden return _identifier.empty() || TokenTraits::isYulKeyword(_identifier.str()) || _dialect.reservedIdentifier(_identifier); } -optional yul::toEVMInstruction(Dialect const& _dialect, YulString const& _name) +std::optional yul::toEVMInstruction(Dialect const& _dialect, YulString const& _name) { if (auto const* dialect = dynamic_cast(&_dialect)) if (BuiltinFunctionForEVM const* builtin = dialect->builtin(_name)) return builtin->instruction; - return nullopt; + return std::nullopt; } langutil::EVMVersion const yul::evmVersionFromDialect(Dialect const& _dialect) @@ -69,12 +68,12 @@ void StatementRemover::operator()(Block& _block) { util::iterateReplacing( _block.statements, - [&](Statement& _statement) -> std::optional> + [&](Statement& _statement) -> std::optional> { if (m_toRemove.count(&_statement)) - return {vector{}}; + return {std::vector{}}; else - return nullopt; + return std::nullopt; } ); ASTModifier::operator()(_block); diff --git a/libyul/optimiser/Rematerialiser.cpp b/libyul/optimiser/Rematerialiser.cpp index 02221a17d..db6920f24 100644 --- a/libyul/optimiser/Rematerialiser.cpp +++ b/libyul/optimiser/Rematerialiser.cpp @@ -28,11 +28,10 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; -void Rematerialiser::run(Dialect const& _dialect, Block& _ast, 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); } @@ -40,7 +39,7 @@ void Rematerialiser::run(Dialect const& _dialect, Block& _ast, set _v Rematerialiser::Rematerialiser( Dialect const& _dialect, Block& _ast, - set _varsToAlwaysRematerialize, + std::set _varsToAlwaysRematerialize, bool _onlySelectedVariables ): DataFlowAnalyzer(_dialect, MemoryAndStorage::Ignore), @@ -52,7 +51,7 @@ Rematerialiser::Rematerialiser( void Rematerialiser::visit(Expression& _e) { - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) { Identifier& identifier = std::get(_e); YulString name = identifier.name; @@ -91,14 +90,14 @@ void Rematerialiser::visit(Expression& _e) void LiteralRematerialiser::visit(Expression& _e) { - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) { Identifier& identifier = std::get(_e); YulString name = identifier.name; if (AssignedValue const* value = variableValue(name)) { assertThrow(value->value, OptimizerException, ""); - if (holds_alternative(*value->value)) + if (std::holds_alternative(*value->value)) _e = *value->value; } } diff --git a/libyul/optimiser/SSAReverser.cpp b/libyul/optimiser/SSAReverser.cpp index d6bf7138a..d47c39033 100644 --- a/libyul/optimiser/SSAReverser.cpp +++ b/libyul/optimiser/SSAReverser.cpp @@ -22,7 +22,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -38,7 +37,7 @@ void SSAReverser::operator()(Block& _block) walkVector(_block.statements); util::iterateReplacingWindow<2>( _block.statements, - [&](Statement& _stmt1, Statement& _stmt2) -> std::optional> + [&](Statement& _stmt1, Statement& _stmt2) -> std::optional> { auto* varDecl = std::get_if(&_stmt1); diff --git a/libyul/optimiser/SSATransform.cpp b/libyul/optimiser/SSATransform.cpp index d86e6fbee..74a770149 100644 --- a/libyul/optimiser/SSATransform.cpp +++ b/libyul/optimiser/SSATransform.cpp @@ -30,7 +30,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; using namespace solidity::langutil; @@ -47,7 +46,7 @@ class IntroduceSSA: public ASTModifier public: explicit IntroduceSSA( NameDispenser& _nameDispenser, - set const& _variablesToReplace, + std::set const& _variablesToReplace, TypeInfo& _typeInfo ): m_nameDispenser(_nameDispenser), @@ -59,7 +58,7 @@ public: private: NameDispenser& m_nameDispenser; - set const& m_variablesToReplace; + std::set const& m_variablesToReplace; TypeInfo const& m_typeInfo; }; @@ -68,9 +67,9 @@ void IntroduceSSA::operator()(Block& _block) { util::iterateReplacing( _block.statements, - [&](Statement& _s) -> std::optional> + [&](Statement& _s) -> std::optional> { - if (holds_alternative(_s)) + if (std::holds_alternative(_s)) { VariableDeclaration& varDecl = std::get(_s); if (varDecl.value) @@ -85,8 +84,8 @@ void IntroduceSSA::operator()(Block& _block) // Replace "let a := v" by "let a_1 := v let a := a_1" // Replace "let a, b := v" by "let a_1, b_1 := v let a := a_1 let b := b_2" - shared_ptr debugData = varDecl.debugData; - vector statements; + std::shared_ptr debugData = varDecl.debugData; + std::vector statements; statements.emplace_back(VariableDeclaration{debugData, {}, std::move(varDecl.value)}); TypedNameList newVariables; for (auto const& var: varDecl.variables) @@ -97,13 +96,13 @@ void IntroduceSSA::operator()(Block& _block) statements.emplace_back(VariableDeclaration{ debugData, {TypedName{debugData, oldName, var.type}}, - make_unique(Identifier{debugData, newName}) + std::make_unique(Identifier{debugData, newName}) }); } std::get(statements.front()).variables = std::move(newVariables); return { std::move(statements) }; } - else if (holds_alternative(_s)) + else if (std::holds_alternative(_s)) { Assignment& assignment = std::get(_s); visit(*assignment.value); @@ -113,7 +112,7 @@ void IntroduceSSA::operator()(Block& _block) // Replace "a := v" by "let a_1 := v a := v" // Replace "a, b := v" by "let a_1, b_1 := v a := a_1 b := b_2" std::shared_ptr debugData = assignment.debugData; - vector statements; + std::vector statements; statements.emplace_back(VariableDeclaration{debugData, {}, std::move(assignment.value)}); TypedNameList newVariables; for (auto const& var: assignment.variableNames) @@ -127,7 +126,7 @@ void IntroduceSSA::operator()(Block& _block) statements.emplace_back(Assignment{ debugData, {Identifier{debugData, oldName}}, - make_unique(Identifier{debugData, newName}) + std::make_unique(Identifier{debugData, newName}) }); } std::get(statements.front()).variables = std::move(newVariables); @@ -149,7 +148,7 @@ class IntroduceControlFlowSSA: public ASTModifier public: explicit IntroduceControlFlowSSA( NameDispenser& _nameDispenser, - set const& _variablesToReplace, + std::set const& _variablesToReplace, TypeInfo const& _typeInfo ): m_nameDispenser(_nameDispenser), @@ -164,19 +163,19 @@ public: private: NameDispenser& m_nameDispenser; - set const& m_variablesToReplace; + std::set const& m_variablesToReplace; /// Variables (that are to be replaced) currently in scope. - set m_variablesInScope; + std::set m_variablesInScope; /// Set of variables that do not have a specific value. - set m_variablesToReassign; + std::set m_variablesToReassign; TypeInfo const& m_typeInfo; }; void IntroduceControlFlowSSA::operator()(FunctionDefinition& _function) { - set varsInScope; + std::set varsInScope; std::swap(varsInScope, m_variablesInScope); - set toReassign; + std::set toReassign; std::swap(toReassign, m_variablesToReassign); for (auto const& param: _function.parameters) @@ -208,7 +207,7 @@ void IntroduceControlFlowSSA::operator()(Switch& _switch) { yulAssert(m_variablesToReassign.empty(), ""); - set toReassign; + std::set toReassign; for (auto& c: _switch.cases) { (*this)(c.body); @@ -220,27 +219,27 @@ void IntroduceControlFlowSSA::operator()(Switch& _switch) void IntroduceControlFlowSSA::operator()(Block& _block) { - set variablesDeclaredHere; - set assignedVariables; + std::set variablesDeclaredHere; + std::set assignedVariables; util::iterateReplacing( _block.statements, - [&](Statement& _s) -> std::optional> + [&](Statement& _s) -> std::optional> { - vector toPrepend; + std::vector toPrepend; for (YulString toReassign: m_variablesToReassign) { YulString newName = m_nameDispenser.newName(toReassign); toPrepend.emplace_back(VariableDeclaration{ debugDataOf(_s), {TypedName{debugDataOf(_s), newName, m_typeInfo.typeOfVariable(toReassign)}}, - make_unique(Identifier{debugDataOf(_s), toReassign}) + std::make_unique(Identifier{debugDataOf(_s), toReassign}) }); assignedVariables.insert(toReassign); } m_variablesToReassign.clear(); - if (holds_alternative(_s)) + if (std::holds_alternative(_s)) { VariableDeclaration& varDecl = std::get(_s); for (auto const& var: varDecl.variables) @@ -250,7 +249,7 @@ void IntroduceControlFlowSSA::operator()(Block& _block) m_variablesInScope.insert(var.name); } } - else if (holds_alternative(_s)) + else if (std::holds_alternative(_s)) { Assignment& assignment = std::get(_s); for (auto const& var: assignment.variableNames) @@ -281,7 +280,7 @@ void IntroduceControlFlowSSA::operator()(Block& _block) class PropagateValues: public ASTModifier { public: - explicit PropagateValues(set const& _variablesToReplace): + explicit PropagateValues(std::set const& _variablesToReplace): m_variablesToReplace(_variablesToReplace) { } @@ -294,9 +293,9 @@ public: 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. - set const& m_variablesToReplace; - map m_currentVariableValues; - set m_clearAtEndOfBlock; + std::set const& m_variablesToReplace; + std::map m_currentVariableValues; + std::set m_clearAtEndOfBlock; }; void PropagateValues::operator()(Identifier& _identifier) @@ -316,11 +315,11 @@ void PropagateValues::operator()(VariableDeclaration& _varDecl) if (m_variablesToReplace.count(variable)) { // `let a := a_1` - regular declaration of non-SSA variable - yulAssert(holds_alternative(*_varDecl.value), ""); + yulAssert(std::holds_alternative(*_varDecl.value), ""); m_currentVariableValues[variable] = std::get(*_varDecl.value).name; m_clearAtEndOfBlock.insert(variable); } - else if (_varDecl.value && holds_alternative(*_varDecl.value)) + 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; @@ -345,7 +344,7 @@ void PropagateValues::operator()(Assignment& _assignment) if (!m_variablesToReplace.count(name)) return; - yulAssert(_assignment.value && holds_alternative(*_assignment.value), ""); + yulAssert(_assignment.value && std::holds_alternative(*_assignment.value), ""); m_currentVariableValues[name] = std::get(*_assignment.value).name; m_clearAtEndOfBlock.insert(name); } @@ -364,7 +363,7 @@ void PropagateValues::operator()(ForLoop& _for) void PropagateValues::operator()(Block& _block) { - set clearAtParentBlock = std::move(m_clearAtEndOfBlock); + std::set clearAtParentBlock = std::move(m_clearAtEndOfBlock); m_clearAtEndOfBlock.clear(); ASTModifier::operator()(_block); @@ -380,7 +379,7 @@ void PropagateValues::operator()(Block& _block) void SSATransform::run(OptimiserStepContext& _context, Block& _ast) { TypeInfo typeInfo(_context.dialect, _ast); - 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 df3c5adce..1d25cb54b 100644 --- a/libyul/optimiser/SSAValueTracker.cpp +++ b/libyul/optimiser/SSAValueTracker.cpp @@ -24,7 +24,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -50,11 +49,11 @@ void SSAValueTracker::operator()(VariableDeclaration const& _varDecl) setValue(_varDecl.variables.front().name, _varDecl.value.get()); } -set SSAValueTracker::ssaVariables(Block const& _ast) +std::set SSAValueTracker::ssaVariables(Block const& _ast) { SSAValueTracker t; t(_ast); - set ssaVars; + std::set ssaVars; for (auto const& value: t.values()) ssaVars.insert(value.first); return ssaVars; diff --git a/libyul/optimiser/Semantics.cpp b/libyul/optimiser/Semantics.cpp index d87c20574..5d375b145 100644 --- a/libyul/optimiser/Semantics.cpp +++ b/libyul/optimiser/Semantics.cpp @@ -33,7 +33,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -41,7 +40,7 @@ using namespace solidity::yul; SideEffectsCollector::SideEffectsCollector( Dialect const& _dialect, Expression const& _expression, - map const* _functionSideEffects + std::map const* _functionSideEffects ): SideEffectsCollector(_dialect, _functionSideEffects) { @@ -57,7 +56,7 @@ SideEffectsCollector::SideEffectsCollector(Dialect const& _dialect, Statement co SideEffectsCollector::SideEffectsCollector( Dialect const& _dialect, Block const& _ast, - map const* _functionSideEffects + std::map const* _functionSideEffects ): SideEffectsCollector(_dialect, _functionSideEffects) { @@ -67,7 +66,7 @@ SideEffectsCollector::SideEffectsCollector( SideEffectsCollector::SideEffectsCollector( Dialect const& _dialect, ForLoop const& _ast, - map const* _functionSideEffects + std::map const* _functionSideEffects ): SideEffectsCollector(_dialect, _functionSideEffects) { @@ -99,7 +98,7 @@ bool MSizeFinder::containsMSize(Dialect const& _dialect, Object const& _object) if (containsMSize(_dialect, *_object.code)) return true; - for (shared_ptr const& node: _object.subObjects) + for (std::shared_ptr const& node: _object.subObjects) if (auto const* object = dynamic_cast(node.get())) if (containsMSize(_dialect, *object)) return true; @@ -116,7 +115,7 @@ void MSizeFinder::operator()(FunctionCall const& _functionCall) m_msizeFound = true; } -map SideEffectsPropagator::sideEffects( +std::map SideEffectsPropagator::sideEffects( Dialect const& _dialect, CallGraph const& _directCallGraph ) @@ -127,7 +126,7 @@ map SideEffectsPropagator::sideEffects( // In the future, we should refine that, because the property // is actually a bit different from "not movable". - map ret; + std::map ret; for (auto const& function: _directCallGraph.functionsWithLoops + _directCallGraph.recursiveFunctions()) { ret[function].movable = false; @@ -179,8 +178,8 @@ void MovableChecker::visit(Statement const&) assertThrow(false, OptimizerException, "Movability for statement requested."); } -pair TerminationFinder::firstUnconditionalControlFlowChange( - vector const& _statements +std::pair TerminationFinder::firstUnconditionalControlFlowChange( + std::vector const& _statements ) { for (size_t i = 0; i < _statements.size(); ++i) @@ -189,32 +188,32 @@ pair TerminationFinder::firstUncondition if (controlFlow != ControlFlow::FlowOut) return {controlFlow, i}; } - return {ControlFlow::FlowOut, numeric_limits::max()}; + return {ControlFlow::FlowOut, std::numeric_limits::max()}; } TerminationFinder::ControlFlow TerminationFinder::controlFlowKind(Statement const& _statement) { if ( - holds_alternative(_statement) && + std::holds_alternative(_statement) && std::get(_statement).value && containsNonContinuingFunctionCall(*std::get(_statement).value) ) return ControlFlow::Terminate; else if ( - holds_alternative(_statement) && + std::holds_alternative(_statement) && containsNonContinuingFunctionCall(*std::get(_statement).value) ) return ControlFlow::Terminate; else if ( - holds_alternative(_statement) && + std::holds_alternative(_statement) && containsNonContinuingFunctionCall(std::get(_statement).expression) ) return ControlFlow::Terminate; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return ControlFlow::Break; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return ControlFlow::Continue; - else if (holds_alternative(_statement)) + else if (std::holds_alternative(_statement)) return ControlFlow::Leave; else return ControlFlow::FlowOut; diff --git a/libyul/optimiser/SimplificationRules.cpp b/libyul/optimiser/SimplificationRules.cpp index c3c4d5a53..f8bbcf678 100644 --- a/libyul/optimiser/SimplificationRules.cpp +++ b/libyul/optimiser/SimplificationRules.cpp @@ -32,7 +32,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::evmasm; using namespace solidity::langutil; @@ -41,7 +40,7 @@ using namespace solidity::yul; SimplificationRules::Rule const* SimplificationRules::findFirstMatch( Expression const& _expr, Dialect const& _dialect, - function const& _ssaValues + std::function const& _ssaValues ) { auto instruction = instructionAndArguments(_dialect, _expr); @@ -75,14 +74,14 @@ bool SimplificationRules::isInitialized() const return !m_rules[uint8_t(evmasm::Instruction::ADD)].empty(); } -std::optional const*>> +std::optional const*>> SimplificationRules::instructionAndArguments(Dialect const& _dialect, Expression const& _expr) { - if (holds_alternative(_expr)) + if (std::holds_alternative(_expr)) if (auto const* dialect = dynamic_cast(&_dialect)) if (auto const* builtin = dialect->builtin(std::get(_expr).functionName.name)) if (builtin->instruction) - return make_pair(*builtin->instruction, &std::get(_expr).arguments); + return std::make_pair(*builtin->instruction, &std::get(_expr).arguments); return {}; } @@ -122,14 +121,14 @@ SimplificationRules::SimplificationRules(std::optional _ev assertThrow(isInitialized(), OptimizerException, "Rule list not properly initialized."); } -yul::Pattern::Pattern(evmasm::Instruction _instruction, initializer_list _arguments): +yul::Pattern::Pattern(evmasm::Instruction _instruction, std::initializer_list _arguments): m_kind(PatternKind::Operation), m_instruction(_instruction), m_arguments(_arguments) { } -void Pattern::setMatchGroup(unsigned _group, map& _matchGroups) +void Pattern::setMatchGroup(unsigned _group, std::map& _matchGroups) { m_matchGroup = _group; m_matchGroups = &_matchGroups; @@ -138,14 +137,14 @@ void Pattern::setMatchGroup(unsigned _group, map& _ bool Pattern::matches( Expression const& _expr, Dialect const& _dialect, - function const& _ssaValues + std::function const& _ssaValues ) const { Expression const* expr = &_expr; // Resolve the variable if possible. // Do not do it for "Any" because we can check identity better for variables. - if (m_kind != PatternKind::Any && holds_alternative(_expr)) + if (m_kind != PatternKind::Any && std::holds_alternative(_expr)) { YulString varName = std::get(_expr).name; if (AssignedValue const* value = _ssaValues(varName)) @@ -156,7 +155,7 @@ bool Pattern::matches( if (m_kind == PatternKind::Constant) { - if (!holds_alternative(*expr)) + if (!std::holds_alternative(*expr)) return false; Literal const& literal = std::get(*expr); if (literal.kind != LiteralKind::Number) @@ -178,7 +177,7 @@ bool Pattern::matches( // we reject the match because side-effects could prevent us from // arbitrarily modifying the code. if ( - holds_alternative(arg) || + std::holds_alternative(arg) || !m_arguments[i].matches(arg, _dialect, _ssaValues) ) return false; @@ -187,7 +186,7 @@ bool Pattern::matches( else { assertThrow(m_arguments.empty(), OptimizerException, "\"Any\" should not have arguments."); - assertThrow(!holds_alternative(*expr), OptimizerException, "\"Any\" at top-level."); + assertThrow(!std::holds_alternative(*expr), OptimizerException, "\"Any\" at top-level."); } if (m_matchGroup) @@ -209,8 +208,8 @@ bool Pattern::matches( Expression const* firstMatch = (*m_matchGroups)[m_matchGroup]; assertThrow(firstMatch, OptimizerException, "Match set but to null."); assertThrow( - !holds_alternative(_expr) && - !holds_alternative(*firstMatch), + !std::holds_alternative(_expr) && + !std::holds_alternative(*firstMatch), OptimizerException, "Group matches have to be literals or variables." ); @@ -235,7 +234,7 @@ evmasm::Instruction Pattern::instruction() const return m_instruction; } -Expression Pattern::toExpression(shared_ptr const& _debugData, langutil::EVMVersion _evmVersion) const +Expression Pattern::toExpression(std::shared_ptr const& _debugData, langutil::EVMVersion _evmVersion) const { if (matchGroup()) return ASTCopier().translate(matchGroupValue()); @@ -246,11 +245,11 @@ Expression Pattern::toExpression(shared_ptr const& _debugData, } else if (m_kind == PatternKind::Operation) { - vector arguments; + std::vector arguments; for (auto const& arg: m_arguments) arguments.emplace_back(arg.toExpression(_debugData, _evmVersion)); - string name = util::toLower(instructionInfo(m_instruction, _evmVersion).name); + std::string name = util::toLower(instructionInfo(m_instruction, _evmVersion).name); return FunctionCall{_debugData, Identifier{_debugData, YulString{name}}, diff --git a/libyul/optimiser/StackCompressor.cpp b/libyul/optimiser/StackCompressor.cpp index a6173996f..87a5e411c 100644 --- a/libyul/optimiser/StackCompressor.cpp +++ b/libyul/optimiser/StackCompressor.cpp @@ -40,7 +40,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -61,9 +60,9 @@ public: /// @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. - map>> candidates() + std::map>> candidates() { - map>> cand; + std::map>> cand; for (auto const& [functionName, candidate]: m_candidates) { if (size_t const* cost = util::valueOrNullptr(m_expressionCodeCost, candidate)) @@ -110,7 +109,7 @@ public: // get called on left-hand-sides of assignments. void visit(Expression& _e) override { - if (holds_alternative(_e)) + if (std::holds_alternative(_e)) { YulString name = std::get(_e).name; if (m_expressionCodeCost.count(name)) @@ -134,20 +133,20 @@ public: YulString m_currentFunctionName = {}; /// All candidate variables by function name, in order of occurrence. - vector> m_candidates; + std::vector> m_candidates; /// Candidate variables and the code cost of their value. - map m_expressionCodeCost; + std::map m_expressionCodeCost; /// Number of references to each candidate variable. - map m_numReferences; + std::map m_numReferences; }; /// Selects at most @a _numVariables among @a _candidates. -set chooseVarsToEliminate( - map> const& _candidates, +std::set chooseVarsToEliminate( + std::map> const& _candidates, size_t _numVariables ) { - set varsToEliminate; + std::set varsToEliminate; for (auto&& [cost, candidates]: _candidates) for (auto&& candidate: candidates) { @@ -161,15 +160,15 @@ set chooseVarsToEliminate( void eliminateVariables( Dialect const& _dialect, Block& _ast, - map const& _numVariables, + std::map const& _numVariables, bool _allowMSizeOptimization ) { RematCandidateSelector selector{_dialect}; selector(_ast); - map>> candidates = selector.candidates(); + std::map>> candidates = selector.candidates(); - set varsToEliminate; + std::set varsToEliminate; for (auto const& [functionName, numVariables]: _numVariables) { yulAssert(numVariables > 0); @@ -178,14 +177,14 @@ void eliminateVariables( Rematerialiser::run(_dialect, _ast, std::move(varsToEliminate)); // Do not remove functions. - 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, - map> const& _unreachables, + std::map> const& _unreachables, bool _allowMSizeOptimization ) { @@ -195,19 +194,19 @@ void eliminateVariablesOptimizedCodegen( RematCandidateSelector selector{_dialect}; selector(_ast); - map candidates; + std::map candidates; for (auto const& [functionName, candidatesInFunction]: selector.candidates()) for (auto [cost, candidatesWithCost]: candidatesInFunction) for (auto candidate: candidatesWithCost) candidates[candidate] = cost; - 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) { - map> suitableCandidates; + std::map> suitableCandidates; size_t neededSlots = unreachable.deficit; for (auto varName: unreachable.variableChoices) { @@ -230,7 +229,7 @@ void eliminateVariablesOptimizedCodegen( } Rematerialiser::run(_dialect, _ast, std::move(varsToEliminate), true); // Do not remove functions. - set allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names(); + std::set allFunctions = NameCollector{_ast, NameCollector::OnlyFunctions}.names(); UnusedPruner::runUntilStabilised(_dialect, _ast, _allowMSizeOptimization, nullptr, allFunctions); } @@ -245,7 +244,7 @@ bool StackCompressor::run( { yulAssert( _object.code && - _object.code->statements.size() > 0 && holds_alternative(_object.code->statements.at(0)), + _object.code->statements.size() > 0 && std::holds_alternative(_object.code->statements.at(0)), "Need to run the function grouper before the stack compressor." ); bool usesOptimizedCodeGenerator = false; @@ -258,7 +257,7 @@ bool StackCompressor::run( if (usesOptimizedCodeGenerator) { yul::AsmAnalysisInfo analysisInfo = yul::AsmAnalyzer::analyzeStrictAssertCorrect(_dialect, _object); - unique_ptr cfg = ControlFlowGraphBuilder::build(analysisInfo, _dialect, *_object.code); + std::unique_ptr cfg = ControlFlowGraphBuilder::build(analysisInfo, _dialect, *_object.code); eliminateVariablesOptimizedCodegen( _dialect, *_object.code, @@ -269,7 +268,7 @@ bool StackCompressor::run( else for (size_t iterations = 0; iterations < _maxIterations; iterations++) { - 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 4c84f5155..5d7f7fe5d 100644 --- a/libyul/optimiser/StackLimitEvader.cpp +++ b/libyul/optimiser/StackLimitEvader.cpp @@ -36,7 +36,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -97,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. - map> const& unreachableVariables; + std::map> const& unreachableVariables; /// The graph of immediate function calls of all functions. - map> const& callGraph; + std::map> const& callGraph; /// Maps the name of each user-defined function to its definition. - map const& functionDefinitions; + std::map const& functionDefinitions; /// Maps variable names to the memory slot the respective variable is assigned. - map slotAllocations{}; + std::map slotAllocations{}; /// Maps function names to the number of memory slots the respective function requires. - map slotsRequiredForFunction{}; + std::map slotsRequiredForFunction{}; }; u256 literalArgumentValue(FunctionCall const& _call) @@ -131,7 +130,7 @@ void StackLimitEvader::run( if (evmDialect && evmDialect->evmVersion().canOverchargeGasForCall()) { yul::AsmAnalysisInfo analysisInfo = yul::AsmAnalyzer::analyzeStrictAssertCorrect(*evmDialect, _object); - unique_ptr cfg = ControlFlowGraphBuilder::build(analysisInfo, *evmDialect, *_object.code); + std::unique_ptr cfg = ControlFlowGraphBuilder::build(analysisInfo, *evmDialect, *_object.code); run(_context, _object, StackLayoutGenerator::reportStackTooDeep(*cfg)); } else @@ -146,10 +145,10 @@ void StackLimitEvader::run( void StackLimitEvader::run( OptimiserStepContext& _context, Object& _object, - map> const& _stackTooDeepErrors + std::map> const& _stackTooDeepErrors ) { - map> unreachableVariables; + std::map> unreachableVariables; for (auto&& [function, stackTooDeepErrors]: _stackTooDeepErrors) { auto& unreachables = unreachableVariables[function]; @@ -165,7 +164,7 @@ void StackLimitEvader::run( void StackLimitEvader::run( OptimiserStepContext& _context, Object& _object, - map> const& _unreachableVariables + std::map> const& _unreachableVariables ) { yulAssert(_object.code, ""); @@ -175,7 +174,7 @@ void StackLimitEvader::run( "StackLimitEvader can only be run on objects using the EVMDialect with object access." ); - vector memoryGuardCalls = FunctionCallFinder::run( + std::vector memoryGuardCalls = FunctionCallFinder::run( *_object.code, "memoryguard"_yulstring ); @@ -198,7 +197,7 @@ void StackLimitEvader::run( if (_unreachableVariables.count(function)) return; - map functionDefinitions = allFunctionDefinitions(*_object.code); + std::map functionDefinitions = allFunctionDefinitions(*_object.code); MemoryOffsetAllocator memoryOffsetAllocator{_unreachableVariables, callGraph.functionCalls, functionDefinitions}; uint64_t requiredSlots = memoryOffsetAllocator.run(); diff --git a/libyul/optimiser/StackToMemoryMover.cpp b/libyul/optimiser/StackToMemoryMover.cpp index 74d05635e..ab39669b2 100644 --- a/libyul/optimiser/StackToMemoryMover.cpp +++ b/libyul/optimiser/StackToMemoryMover.cpp @@ -29,22 +29,21 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; namespace { -vector generateMemoryStore( +std::vector generateMemoryStore( Dialect const& _dialect, - shared_ptr const& _debugData, + std::shared_ptr const& _debugData, YulString _mpos, Expression _value ) { BuiltinFunction const* memoryStoreFunction = _dialect.memoryStoreFunction(_dialect.defaultType); yulAssert(memoryStoreFunction, ""); - vector result; + std::vector result; result.emplace_back(ExpressionStatement{_debugData, FunctionCall{ _debugData, Identifier{_debugData, memoryStoreFunction->name}, @@ -77,7 +76,7 @@ FunctionCall generateMemoryLoad(Dialect const& _dialect, std::shared_ptr const& _memorySlots, + std::map const& _memorySlots, uint64_t _numRequiredSlots, Block& _block ) @@ -91,7 +90,7 @@ void StackToMemoryMover::run( util::mapTuple([](YulString _name, FunctionDefinition const* _funDef) { return make_pair(_name, _funDef->returnVariables); }), - map{} + std::map{} ) ); stackToMemoryMover(_block); @@ -101,7 +100,7 @@ void StackToMemoryMover::run( StackToMemoryMover::StackToMemoryMover( OptimiserStepContext& _context, VariableMemoryOffsetTracker const& _memoryOffsetTracker, - map _functionReturnVariables + std::map _functionReturnVariables ): m_context(_context), m_memoryOffsetTracker(_memoryOffsetTracker), @@ -121,7 +120,7 @@ void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition) // variable arguments we might generate below. ASTModifier::operator()(_functionDefinition); - vector memoryVariableInits; + std::vector memoryVariableInits; // All function parameters with a memory slot are moved at the beginning of the function body. for (TypedName const& param: _functionDefinition.parameters) @@ -147,7 +146,7 @@ void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition) if (_functionDefinition.returnVariables.size() == 1 && m_memoryOffsetTracker(_functionDefinition.returnVariables.front().name)) { TypedNameList stackParameters = _functionDefinition.parameters | ranges::views::filter( - not_fn(m_memoryOffsetTracker) + 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); @@ -173,13 +172,13 @@ void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition) Identifier{_functionDefinition.debugData, newFunctionName}, stackParameters | ranges::views::transform([&](TypedName const& _arg) { return Expression{Identifier{_arg.debugData, newArgumentNames.at(_arg.name)}}; - }) | ranges::to> + }) | ranges::to> } }); _functionDefinition.body.statements.emplace_back(Assignment{ _functionDefinition.debugData, {Identifier{_functionDefinition.debugData, _functionDefinition.returnVariables.front().name}}, - make_unique(generateMemoryLoad( + std::make_unique(generateMemoryLoad( m_context.dialect, _functionDefinition.debugData, *m_memoryOffsetTracker(_functionDefinition.returnVariables.front().name) @@ -192,24 +191,24 @@ void StackToMemoryMover::operator()(FunctionDefinition& _functionDefinition) _functionDefinition.body.statements = std::move(memoryVariableInits) + std::move(_functionDefinition.body.statements); _functionDefinition.returnVariables = _functionDefinition.returnVariables | ranges::views::filter( - not_fn(m_memoryOffsetTracker) + std::not_fn(m_memoryOffsetTracker) ) | ranges::to; } void StackToMemoryMover::operator()(Block& _block) { - using OptionalStatements = optional>; + using OptionalStatements = std::optional>; auto rewriteAssignmentOrVariableDeclarationLeftHandSide = [this]( auto& _stmt, auto& _lhsVars ) -> OptionalStatements { - using StatementType = decay_t; + using StatementType = std::decay_t; auto debugData = _stmt.debugData; if (_lhsVars.size() == 1) { - if (optional offset = m_memoryOffsetTracker(_lhsVars.front().name)) + if (std::optional offset = m_memoryOffsetTracker(_lhsVars.front().name)) return generateMemoryStore( m_context.dialect, debugData, @@ -219,48 +218,48 @@ void StackToMemoryMover::operator()(Block& _block) else return {}; } - vector> rhsMemorySlots; + std::vector> rhsMemorySlots; if (_stmt.value) { - FunctionCall const* functionCall = get_if(_stmt.value.get()); + FunctionCall const* functionCall = std::get_if(_stmt.value.get()); yulAssert(functionCall, ""); if (m_context.dialect.builtin(functionCall->functionName.name)) - rhsMemorySlots = vector>(_lhsVars.size(), nullopt); + rhsMemorySlots = std::vector>(_lhsVars.size(), std::nullopt); else rhsMemorySlots = m_functionReturnVariables.at(functionCall->functionName.name) | ranges::views::transform(m_memoryOffsetTracker) | - ranges::to>>; + ranges::to>>; } else - rhsMemorySlots = vector>(_lhsVars.size(), nullopt); + rhsMemorySlots = std::vector>(_lhsVars.size(), std::nullopt); // Nothing to do, if the right-hand-side remains entirely on the stack and // none of the variables in the left-hand-side are moved. if ( - ranges::none_of(rhsMemorySlots, [](optional const& _slot) { return _slot.has_value(); }) && + ranges::none_of(rhsMemorySlots, [](std::optional const& _slot) { return _slot.has_value(); }) && !util::contains_if(_lhsVars, m_memoryOffsetTracker) ) return {}; - vector memoryAssignments; - vector variableAssignments; + std::vector memoryAssignments; + std::vector variableAssignments; VariableDeclaration tempDecl{debugData, {}, std::move(_stmt.value)}; yulAssert(rhsMemorySlots.size() == _lhsVars.size(), ""); for (auto&& [lhsVar, rhsSlot]: ranges::views::zip(_lhsVars, rhsMemorySlots)) { - unique_ptr rhs; + std::unique_ptr rhs; if (rhsSlot) - rhs = make_unique(generateMemoryLoad(m_context.dialect, debugData, *rhsSlot)); + rhs = std::make_unique(generateMemoryLoad(m_context.dialect, debugData, *rhsSlot)); else { YulString tempVarName = m_nameDispenser.newName(lhsVar.name); tempDecl.variables.emplace_back(TypedName{lhsVar.debugData, tempVarName, {}}); - rhs = make_unique(Identifier{debugData, tempVarName}); + rhs = std::make_unique(Identifier{debugData, tempVarName}); } - if (optional offset = m_memoryOffsetTracker(lhsVar.name)) + if (std::optional offset = m_memoryOffsetTracker(lhsVar.name)) memoryAssignments += generateMemoryStore( m_context.dialect, _stmt.debugData, @@ -275,7 +274,7 @@ void StackToMemoryMover::operator()(Block& _block) }); } - vector result; + std::vector result; if (tempDecl.variables.empty()) result.emplace_back(ExpressionStatement{debugData, *std::move(tempDecl.value)}); else @@ -292,9 +291,9 @@ void StackToMemoryMover::operator()(Block& _block) [&](Statement& _statement) -> OptionalStatements { visit(_statement); - if (auto* assignment = get_if(&_statement)) + if (auto* assignment = std::get_if(&_statement)) return rewriteAssignmentOrVariableDeclarationLeftHandSide(*assignment, assignment->variableNames); - else if (auto* varDecl = get_if(&_statement)) + else if (auto* varDecl = std::get_if(&_statement)) return rewriteAssignmentOrVariableDeclarationLeftHandSide(*varDecl, varDecl->variables); return {}; } @@ -304,12 +303,12 @@ void StackToMemoryMover::operator()(Block& _block) void StackToMemoryMover::visit(Expression& _expression) { ASTModifier::visit(_expression); - if (Identifier* identifier = get_if(&_expression)) - if (optional offset = m_memoryOffsetTracker(identifier->name)) + if (Identifier* identifier = std::get_if(&_expression)) + if (std::optional offset = m_memoryOffsetTracker(identifier->name)) _expression = generateMemoryLoad(m_context.dialect, identifier->debugData, *offset); } -optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(YulString _variable) const +std::optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(YulString _variable) const { if (m_memorySlots.count(_variable)) { @@ -318,15 +317,15 @@ optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()( return YulString{toCompactHexWithPrefix(m_reservedMemory + 32 * (m_numRequiredSlots - slot - 1))}; } else - return nullopt; + return std::nullopt; } -optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(TypedName const& _variable) const +std::optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(TypedName const& _variable) const { return (*this)(_variable.name); } -optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(Identifier const& _variable) const +std::optional StackToMemoryMover::VariableMemoryOffsetTracker::operator()(Identifier const& _variable) const { return (*this)(_variable.name); } diff --git a/libyul/optimiser/StructuralSimplifier.cpp b/libyul/optimiser/StructuralSimplifier.cpp index ca8f94239..2af0f7bac 100644 --- a/libyul/optimiser/StructuralSimplifier.cpp +++ b/libyul/optimiser/StructuralSimplifier.cpp @@ -21,11 +21,10 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; -using OptionalStatements = std::optional>; +using OptionalStatements = std::optional>; namespace { @@ -52,12 +51,12 @@ OptionalStatements replaceConstArgSwitch(Switch& _switchStmt, u256 const& _const if (matchingCaseBlock) return util::make_vector(std::move(*matchingCaseBlock)); else - return optional>{vector{}}; + return std::optional>{std::vector{}}; } -optional hasLiteralValue(Expression const& _expression) +std::optional hasLiteralValue(Expression const& _expression) { - if (holds_alternative(_expression)) + if (std::holds_alternative(_expression)) return valueOfLiteral(std::get(_expression)); else return std::optional(); @@ -99,7 +98,7 @@ void StructuralSimplifier::simplify(std::vector& _statements) if (expressionAlwaysTrue(*_ifStmt.condition)) return {std::move(_ifStmt.body.statements)}; else if (expressionAlwaysFalse(*_ifStmt.condition)) - return {vector{}}; + return {std::vector{}}; return {}; }, [&](Switch& _switchStmt) -> OptionalStatements { diff --git a/libyul/optimiser/Substitution.cpp b/libyul/optimiser/Substitution.cpp index e0557ad74..b2d4d469e 100644 --- a/libyul/optimiser/Substitution.cpp +++ b/libyul/optimiser/Substitution.cpp @@ -23,13 +23,12 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; Expression Substitution::translate(Expression const& _expression) { - if (holds_alternative(_expression)) + if (std::holds_alternative(_expression)) { YulString name = std::get(_expression).name; if (m_substitutions.count(name)) diff --git a/libyul/optimiser/Suite.cpp b/libyul/optimiser/Suite.cpp index bd966e5d3..58561ee10 100644 --- a/libyul/optimiser/Suite.cpp +++ b/libyul/optimiser/Suite.cpp @@ -86,12 +86,12 @@ #include #endif -using namespace std; using namespace solidity; using namespace solidity::yul; #ifdef PROFILE_OPTIMIZER_STEPS using namespace std::chrono; #endif +using namespace std::string_literals; namespace { @@ -136,10 +136,10 @@ void OptimiserSuite::run( GasMeter const* _meter, Object& _object, bool _optimizeStackAllocation, - string_view _optimisationSequence, - string_view _optimisationCleanupSequence, - optional _expectedExecutionsPerDeployment, - set const& _externallyUsedIdentifiers + std::string_view _optimisationSequence, + std::string_view _optimisationCleanupSequence, + std::optional _expectedExecutionsPerDeployment, + std::set const& _externallyUsedIdentifiers ) { EVMDialect const* evmDialect = dynamic_cast(&_dialect); @@ -148,7 +148,7 @@ void OptimiserSuite::run( evmDialect && evmDialect->evmVersion().canOverchargeGasForCall() && evmDialect->providesObjectAccess(); - set reservedIdentifiers = _externallyUsedIdentifiers; + std::set reservedIdentifiers = _externallyUsedIdentifiers; reservedIdentifiers += _dialect.fixedFunctionNames(); *_object.code = std::get(Disambiguator( @@ -226,11 +226,11 @@ namespace { template -map> optimiserStepCollection() +std::map> optimiserStepCollection() { - map> ret; - for (unique_ptr& s: util::make_vector>( - (make_unique>())... + std::map> ret; + for (std::unique_ptr& s: util::make_vector>( + (std::make_unique>())... )) { yulAssert(!ret.count(s->name), ""); @@ -241,9 +241,9 @@ map> optimiserStepCollection() } -map> const& OptimiserSuite::allSteps() +std::map> const& OptimiserSuite::allSteps() { - static map> instance; + static std::map> instance; if (instance.empty()) instance = optimiserStepCollection< BlockFlattener, @@ -284,9 +284,9 @@ map> const& OptimiserSuite::allSteps() return instance; } -map const& OptimiserSuite::stepNameToAbbreviationMap() +std::map const& OptimiserSuite::stepNameToAbbreviationMap() { - static map lookupTable{ + static std::map lookupTable{ {BlockFlattener::name, 'f'}, {CircularReferencesPruner::name, 'l'}, {CommonSubexpressionEliminator::name, 'c'}, @@ -322,23 +322,23 @@ map const& OptimiserSuite::stepNameToAbbreviationMap() }; yulAssert(lookupTable.size() == allSteps().size(), ""); yulAssert(( - util::convertContainer>(string(NonStepAbbreviations)) - - util::convertContainer>(lookupTable | ranges::views::values) - ).size() == string(NonStepAbbreviations).size(), + util::convertContainer>(std::string(NonStepAbbreviations)) - + util::convertContainer>(lookupTable | ranges::views::values) + ).size() == std::string(NonStepAbbreviations).size(), "Step abbreviation conflicts with a character reserved for another syntactic element" ); return lookupTable; } -map const& OptimiserSuite::stepAbbreviationToNameMap() +std::map const& OptimiserSuite::stepAbbreviationToNameMap() { - static map lookupTable = util::invertMap(stepNameToAbbreviationMap()); + static std::map lookupTable = util::invertMap(stepNameToAbbreviationMap()); return lookupTable; } -void OptimiserSuite::validateSequence(string_view _stepAbbreviations) +void OptimiserSuite::validateSequence(std::string_view _stepAbbreviations) { int8_t nestingLevel = 0; int8_t colonDelimiters = 0; @@ -349,7 +349,7 @@ void OptimiserSuite::validateSequence(string_view _stepAbbreviations) case '\n': break; case '[': - assertThrow(nestingLevel < numeric_limits::max(), OptimizerException, "Brackets nested too deep"); + assertThrow(nestingLevel < std::numeric_limits::max(), OptimizerException, "Brackets nested too deep"); nestingLevel++; break; case ']': @@ -364,7 +364,7 @@ void OptimiserSuite::validateSequence(string_view _stepAbbreviations) default: { yulAssert( - string(NonStepAbbreviations).find(abbreviation) == string::npos, + std::string(NonStepAbbreviations).find(abbreviation) == std::string::npos, "Unhandled syntactic element in the abbreviation sequence" ); assertThrow( @@ -372,7 +372,7 @@ void OptimiserSuite::validateSequence(string_view _stepAbbreviations) OptimizerException, "'"s + abbreviation + "' is not a valid step abbreviation" ); - optional invalid = allSteps().at(stepAbbreviationToNameMap().at(abbreviation))->invalidInCurrentEnvironment(); + std::optional invalid = allSteps().at(stepAbbreviationToNameMap().at(abbreviation))->invalidInCurrentEnvironment(); assertThrow( !invalid.has_value(), OptimizerException, @@ -383,12 +383,12 @@ void OptimiserSuite::validateSequence(string_view _stepAbbreviations) assertThrow(nestingLevel == 0, OptimizerException, "Unbalanced brackets"); } -void OptimiserSuite::runSequence(string_view _stepAbbreviations, Block& _ast, bool _repeatUntilStable) +void OptimiserSuite::runSequence(std::string_view _stepAbbreviations, Block& _ast, bool _repeatUntilStable) { validateSequence(_stepAbbreviations); // This splits 'aaa[bbb]ccc...' into 'aaa' and '[bbb]ccc...'. - auto extractNonNestedPrefix = [](string_view _tail) -> tuple + auto extractNonNestedPrefix = [](std::string_view _tail) -> std::tuple { for (size_t i = 0; i < _tail.size(); ++i) { @@ -400,7 +400,7 @@ void OptimiserSuite::runSequence(string_view _stepAbbreviations, Block& _ast, bo }; // This splits '[bbb]ccc...' into 'bbb' and 'ccc...'. - auto extractBracketContent = [](string_view _tail) -> tuple + auto extractBracketContent = [](std::string_view _tail) -> std::tuple { yulAssert(!_tail.empty() && _tail[0] == '['); @@ -410,7 +410,7 @@ void OptimiserSuite::runSequence(string_view _stepAbbreviations, Block& _ast, bo { if (abbreviation == '[') { - yulAssert(nestingLevel < numeric_limits::max()); + yulAssert(nestingLevel < std::numeric_limits::max()); ++nestingLevel; } else if (abbreviation == ']') @@ -427,20 +427,20 @@ void OptimiserSuite::runSequence(string_view _stepAbbreviations, Block& _ast, bo return {_tail.substr(1, contentLength), _tail.substr(contentLength + 2)}; }; - auto abbreviationsToSteps = [](string_view _sequence) -> vector + auto abbreviationsToSteps = [](std::string_view _sequence) -> std::vector { - vector steps; + std::vector steps; for (char abbreviation: _sequence) if (abbreviation != ' ' && abbreviation != '\n') steps.emplace_back(stepAbbreviationToNameMap().at(abbreviation)); return steps; }; - vector> subsequences; - string_view tail = _stepAbbreviations; + std::vector> subsequences; + std::string_view tail = _stepAbbreviations; while (!tail.empty()) { - string_view subsequence; + std::string_view subsequence; tie(subsequence, tail) = extractNonNestedPrefix(tail); if (subsequence.size() > 0) subsequences.push_back({subsequence, false}); @@ -474,15 +474,15 @@ void OptimiserSuite::runSequence(string_view _stepAbbreviations, Block& _ast, bo } } -void OptimiserSuite::runSequence(std::vector const& _steps, Block& _ast) +void OptimiserSuite::runSequence(std::vector const& _steps, Block& _ast) { - unique_ptr copy; + std::unique_ptr copy; if (m_debug == Debug::PrintChanges) - copy = make_unique(std::get(ASTCopier{}(_ast))); - for (string const& step: _steps) + copy = std::make_unique(std::get(ASTCopier{}(_ast))); + for (std::string const& step: _steps) { if (m_debug == Debug::PrintStep) - cout << "Running " << step << endl; + std::cout << "Running " << step << std::endl; #ifdef PROFILE_OPTIMIZER_STEPS steady_clock::time_point startTime = steady_clock::now(); #endif @@ -495,12 +495,12 @@ void OptimiserSuite::runSequence(std::vector const& _steps, Block& _ast) { // TODO should add switch to also compare variable names! if (SyntacticallyEqual{}.statementEqual(_ast, *copy)) - cout << "== Running " << step << " did not cause changes." << endl; + std::cout << "== Running " << step << " did not cause changes." << std::endl; else { - cout << "== Running " << step << " changed the AST." << endl; - cout << AsmPrinter{}(_ast) << endl; - copy = make_unique(std::get(ASTCopier{}(_ast))); + std::cout << "== Running " << step << " changed the AST." << std::endl; + std::cout << AsmPrinter{}(_ast) << std::endl; + copy = std::make_unique(std::get(ASTCopier{}(_ast))); } } } diff --git a/libyul/optimiser/SyntacticalEquality.cpp b/libyul/optimiser/SyntacticalEquality.cpp index dccdf62a5..6f7753827 100644 --- a/libyul/optimiser/SyntacticalEquality.cpp +++ b/libyul/optimiser/SyntacticalEquality.cpp @@ -25,7 +25,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; diff --git a/libyul/optimiser/TypeInfo.cpp b/libyul/optimiser/TypeInfo.cpp index 81bc7ac0b..16ce65496 100644 --- a/libyul/optimiser/TypeInfo.cpp +++ b/libyul/optimiser/TypeInfo.cpp @@ -28,7 +28,6 @@ #include -using namespace std; using namespace solidity::yul; using namespace solidity::util; @@ -81,7 +80,7 @@ YulString TypeInfo::typeOf(Expression const& _expression) const return std::visit(GenericVisitor{ [&](FunctionCall const& _funCall) { YulString name = _funCall.functionName.name; - vector const* retTypes = nullptr; + std::vector const* retTypes = nullptr; if (BuiltinFunction const* fun = m_dialect.builtin(name)) retTypes = &fun->returns; else diff --git a/libyul/optimiser/UnusedAssignEliminator.cpp b/libyul/optimiser/UnusedAssignEliminator.cpp index 60021d4a9..f3d78288f 100644 --- a/libyul/optimiser/UnusedAssignEliminator.cpp +++ b/libyul/optimiser/UnusedAssignEliminator.cpp @@ -34,7 +34,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -48,7 +47,7 @@ void UnusedAssignEliminator::run(OptimiserStepContext& _context, Block& _ast) uae.m_storesToRemove += uae.m_allStores - uae.m_usedStores; - set toRemove{uae.m_storesToRemove.begin(), uae.m_storesToRemove.end()}; + std::set toRemove{uae.m_storesToRemove.begin(), uae.m_storesToRemove.end()}; StatementRemover remover{toRemove}; remover(_ast); } @@ -103,7 +102,7 @@ void UnusedAssignEliminator::operator()(Block const& _block) UnusedStoreBase::operator()(_block); for (auto const& statement: _block.statements) - if (auto const* varDecl = get_if(&statement)) + if (auto const* varDecl = std::get_if(&statement)) for (auto const& var: varDecl->variables) m_activeStores.erase(var.name); } @@ -112,7 +111,7 @@ void UnusedAssignEliminator::visit(Statement const& _statement) { UnusedStoreBase::visit(_statement); - if (auto const* assignment = get_if(&_statement)) + if (auto const* assignment = std::get_if(&_statement)) { // We do not remove assignments whose values might have side-effects, // but clear the active stores to the assigned variables in any case. diff --git a/libyul/optimiser/UnusedFunctionParameterPruner.cpp b/libyul/optimiser/UnusedFunctionParameterPruner.cpp index 1ada8224f..40c2fe80c 100644 --- a/libyul/optimiser/UnusedFunctionParameterPruner.cpp +++ b/libyul/optimiser/UnusedFunctionParameterPruner.cpp @@ -36,14 +36,13 @@ #include #include -using namespace std; using namespace solidity::util; using namespace solidity::yul; using namespace solidity::yul::unusedFunctionsCommon; void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ast) { - 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 @@ -55,12 +54,12 @@ 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. - map, 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. for (auto const& statement: _ast.statements) - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) { FunctionDefinition const& f = std::get(statement); @@ -73,7 +72,7 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ }; } - 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`. @@ -91,17 +90,17 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ // For example: introduce a new 'linking' function `f` with the same the body as `f_1`, but with // reduced parameters, i.e., `function f() -> y { y := 1 }`. Now replace the body of `f_1` with // a call to `f`, i.e., `f_1(x) -> y { y := f() }`. - iterateReplacing(_ast.statements, [&](Statement& _s) -> optional> { - if (holds_alternative(_s)) + iterateReplacing(_ast.statements, [&](Statement& _s) -> std::optional> { + if (std::holds_alternative(_s)) { // The original function except that it has a new name (e.g., `f_1`) - FunctionDefinition& originalFunction = get(_s); + FunctionDefinition& originalFunction = std::get(_s); if (newToOriginalNames.count(originalFunction.name)) { YulString linkingFunctionName = originalFunction.name; YulString originalFunctionName = newToOriginalNames.at(linkingFunctionName); - pair, vector> used = + std::pair, std::vector> used = usedParametersAndReturnVariables.at(originalFunctionName); FunctionDefinition linkingFunction = createLinkingFunction( @@ -122,6 +121,6 @@ void UnusedFunctionParameterPruner::run(OptimiserStepContext& _context, Block& _ } } - return nullopt; + return std::nullopt; }); } diff --git a/libyul/optimiser/UnusedPruner.cpp b/libyul/optimiser/UnusedPruner.cpp index cb60f9da8..a64f37ebe 100644 --- a/libyul/optimiser/UnusedPruner.cpp +++ b/libyul/optimiser/UnusedPruner.cpp @@ -30,7 +30,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -44,8 +43,8 @@ UnusedPruner::UnusedPruner( Dialect const& _dialect, Block& _ast, bool _allowMSizeOptimization, - map const* _functionSideEffects, - set const& _externallyUsedFunctions + std::map const* _functionSideEffects, + std::set const& _externallyUsedFunctions ): m_dialect(_dialect), m_allowMSizeOptimization(_allowMSizeOptimization), @@ -60,7 +59,7 @@ UnusedPruner::UnusedPruner( Dialect const& _dialect, FunctionDefinition& _function, bool _allowMSizeOptimization, - set const& _externallyUsedFunctions + std::set const& _externallyUsedFunctions ): m_dialect(_dialect), m_allowMSizeOptimization(_allowMSizeOptimization) @@ -73,7 +72,7 @@ UnusedPruner::UnusedPruner( void UnusedPruner::operator()(Block& _block) { for (auto&& statement: _block.statements) - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) { FunctionDefinition& funDef = std::get(statement); if (!used(funDef.name)) @@ -82,7 +81,7 @@ void UnusedPruner::operator()(Block& _block) statement = Block{std::move(funDef.debugData), {}}; } } - else if (holds_alternative(statement)) + else if (std::holds_alternative(statement)) { VariableDeclaration& varDecl = std::get(statement); // Multi-variable declarations are special. We can only remove it @@ -114,7 +113,7 @@ void UnusedPruner::operator()(Block& _block) }}; } } - else if (holds_alternative(statement)) + else if (std::holds_alternative(statement)) { ExpressionStatement& exprStmt = std::get(statement); if ( @@ -136,8 +135,8 @@ void UnusedPruner::runUntilStabilised( Dialect const& _dialect, Block& _ast, bool _allowMSizeOptimization, - map const* _functionSideEffects, - set const& _externallyUsedFunctions + std::map const* _functionSideEffects, + std::set const& _externallyUsedFunctions ) { while (true) @@ -154,10 +153,10 @@ void UnusedPruner::runUntilStabilised( void UnusedPruner::runUntilStabilisedOnFullAST( Dialect const& _dialect, Block& _ast, - set const& _externallyUsedFunctions + std::set const& _externallyUsedFunctions ) { - map functionSideEffects = + std::map functionSideEffects = SideEffectsPropagator::sideEffects(_dialect, CallGraphGenerator::callGraph(_ast)); bool allowMSizeOptimization = !MSizeFinder::containsMSize(_dialect, _ast); runUntilStabilised(_dialect, _ast, allowMSizeOptimization, &functionSideEffects, _externallyUsedFunctions); @@ -167,7 +166,7 @@ void UnusedPruner::runUntilStabilised( Dialect const& _dialect, FunctionDefinition& _function, bool _allowMSizeOptimization, - set const& _externallyUsedFunctions + std::set const& _externallyUsedFunctions ) { while (true) @@ -184,7 +183,7 @@ bool UnusedPruner::used(YulString _name) const return m_references.count(_name) && m_references.at(_name) > 0; } -void UnusedPruner::subtractReferences(map const& _subtrahend) +void UnusedPruner::subtractReferences(std::map const& _subtrahend) { for (auto const& ref: _subtrahend) { diff --git a/libyul/optimiser/UnusedStoreBase.cpp b/libyul/optimiser/UnusedStoreBase.cpp index c31fda89c..977db11c4 100644 --- a/libyul/optimiser/UnusedStoreBase.cpp +++ b/libyul/optimiser/UnusedStoreBase.cpp @@ -29,7 +29,6 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -50,7 +49,7 @@ void UnusedStoreBase::operator()(Switch const& _switch) ActiveStores const preState{m_activeStores}; bool hasDefault = false; - vector branches; + std::vector branches; for (auto const& c: _switch.cases) { if (!c.value) @@ -146,15 +145,15 @@ void UnusedStoreBase::operator()(Continue const&) void UnusedStoreBase::merge(ActiveStores& _target, ActiveStores&& _other) { util::joinMap(_target, std::move(_other), []( - set& _storesHere, - set&& _storesThere + std::set& _storesHere, + std::set&& _storesThere ) { _storesHere += _storesThere; }); } -void UnusedStoreBase::merge(ActiveStores& _target, vector&& _source) +void UnusedStoreBase::merge(ActiveStores& _target, std::vector&& _source) { for (ActiveStores& ts: _source) merge(_target, std::move(ts)); diff --git a/libyul/optimiser/UnusedStoreEliminator.cpp b/libyul/optimiser/UnusedStoreEliminator.cpp index 2c3d03e4e..d88b07f6b 100644 --- a/libyul/optimiser/UnusedStoreEliminator.cpp +++ b/libyul/optimiser/UnusedStoreEliminator.cpp @@ -40,26 +40,25 @@ #include -using namespace std; using namespace solidity; using namespace solidity::yul; /// Variable names for special constants that can never appear in actual Yul code. -static string const zero{"@ 0"}; -static string const one{"@ 1"}; -static string const thirtyTwo{"@ 32"}; +static std::string const zero{"@ 0"}; +static std::string const one{"@ 1"}; +static std::string const thirtyTwo{"@ 32"}; void UnusedStoreEliminator::run(OptimiserStepContext& _context, Block& _ast) { - map functionSideEffects = SideEffectsPropagator::sideEffects( + std::map functionSideEffects = SideEffectsPropagator::sideEffects( _context.dialect, CallGraphGenerator::callGraph(_ast) ); SSAValueTracker ssaValues; ssaValues(_ast); - map values; + std::map values; for (auto const& [name, expression]: ssaValues.values()) values[name] = AssignedValue{expression, {}}; Expression const zeroLiteral{Literal{{}, LiteralKind::Number, YulString{"0"}, {}}}; @@ -87,16 +86,16 @@ void UnusedStoreEliminator::run(OptimiserStepContext& _context, Block& _ast) rse.markActiveAsUsed(Location::Storage); rse.m_storesToRemove += rse.m_allStores - rse.m_usedStores; - set toRemove{rse.m_storesToRemove.begin(), rse.m_storesToRemove.end()}; + std::set toRemove{rse.m_storesToRemove.begin(), rse.m_storesToRemove.end()}; StatementRemover remover{toRemove}; remover(_ast); } UnusedStoreEliminator::UnusedStoreEliminator( Dialect const& _dialect, - map const& _functionSideEffects, - map _controlFlowSideEffects, - map const& _ssaValues, + std::map const& _functionSideEffects, + std::map _controlFlowSideEffects, + std::map const& _ssaValues, bool _ignoreMemory ): UnusedStoreBase(_dialect), @@ -148,18 +147,18 @@ void UnusedStoreEliminator::visit(Statement const& _statement) UnusedStoreBase::visit(_statement); - auto const* exprStatement = get_if(&_statement); + auto const* exprStatement = std::get_if(&_statement); if (!exprStatement) return; - FunctionCall const* funCall = get_if(&exprStatement->expression); + FunctionCall const* funCall = std::get_if(&exprStatement->expression); yulAssert(funCall); - optional instruction = toEVMInstruction(m_dialect, funCall->functionName.name); + std::optional instruction = toEVMInstruction(m_dialect, funCall->functionName.name); if (!instruction) return; if (!ranges::all_of(funCall->arguments, [](Expression const& _expr) -> bool { - return get_if(&_expr) || get_if(&_expr); + return std::get_if(&_expr) || std::get_if(&_expr); })) return; @@ -195,7 +194,7 @@ void UnusedStoreEliminator::visit(Statement const& _statement) auto length = identifierNameIfSSA(funCall->arguments.at(2)); if (length && startOffset) { - FunctionCall const* lengthCall = get_if(m_ssaValues.at(*length).value); + FunctionCall const* lengthCall = std::get_if(m_ssaValues.at(*length).value); if ( m_knowledgeBase.knownToBeZero(*startOffset) && lengthCall && @@ -207,7 +206,7 @@ void UnusedStoreEliminator::visit(Statement const& _statement) return; } m_allStores.insert(&_statement); - vector operations = operationsFromFunctionCall(*funCall); + std::vector operations = operationsFromFunctionCall(*funCall); yulAssert(operations.size() == 1, ""); if (operations.front().location == Location::Storage) activeStorageStores().insert(&_statement); @@ -217,7 +216,7 @@ void UnusedStoreEliminator::visit(Statement const& _statement) } } -vector UnusedStoreEliminator::operationsFromFunctionCall( +std::vector UnusedStoreEliminator::operationsFromFunctionCall( FunctionCall const& _functionCall ) const { @@ -230,10 +229,10 @@ vector UnusedStoreEliminator::operationsFromFu else sideEffects = m_functionSideEffects.at(functionName); - optional instruction = toEVMInstruction(m_dialect, functionName); + std::optional instruction = toEVMInstruction(m_dialect, functionName); if (!instruction) { - vector result; + std::vector result; // Unknown read is worse than unknown write. if (sideEffects.memory != SideEffects::Effect::None) result.emplace_back(Operation{Location::Memory, Effect::Read, {}, {}}); @@ -269,7 +268,7 @@ vector UnusedStoreEliminator::operationsFromFu void UnusedStoreEliminator::applyOperation(UnusedStoreEliminator::Operation const& _operation) { - set& active = + std::set& active = _operation.location == Location::Storage ? activeStorageStores() : activeMemoryStores(); @@ -324,9 +323,9 @@ bool UnusedStoreEliminator::knownUnrelated( if (_op1.start && _op1.length && _op2.start) { - optional length1 = m_knowledgeBase.valueIfKnownConstant(*_op1.length); - optional start1 = m_knowledgeBase.valueIfKnownConstant(*_op1.start); - optional start2 = m_knowledgeBase.valueIfKnownConstant(*_op2.start); + std::optional length1 = m_knowledgeBase.valueIfKnownConstant(*_op1.length); + std::optional start1 = m_knowledgeBase.valueIfKnownConstant(*_op1.start); + std::optional start2 = m_knowledgeBase.valueIfKnownConstant(*_op2.start); if ( (length1 && start1 && start2) && *start1 + *length1 >= *start1 && // no overflow @@ -336,9 +335,9 @@ bool UnusedStoreEliminator::knownUnrelated( } if (_op2.start && _op2.length && _op1.start) { - optional length2 = m_knowledgeBase.valueIfKnownConstant(*_op2.length); - optional start2 = m_knowledgeBase.valueIfKnownConstant(*_op2.start); - optional start1 = m_knowledgeBase.valueIfKnownConstant(*_op1.start); + std::optional length2 = m_knowledgeBase.valueIfKnownConstant(*_op2.length); + std::optional start2 = m_knowledgeBase.valueIfKnownConstant(*_op2.start); + std::optional start1 = m_knowledgeBase.valueIfKnownConstant(*_op1.start); if ( (length2 && start2 && start1) && *start2 + *length2 >= *start2 && // no overflow @@ -349,8 +348,8 @@ bool UnusedStoreEliminator::knownUnrelated( if (_op1.start && _op1.length && _op2.start && _op2.length) { - optional length1 = m_knowledgeBase.valueIfKnownConstant(*_op1.length); - optional length2 = m_knowledgeBase.valueIfKnownConstant(*_op2.length); + std::optional length1 = m_knowledgeBase.valueIfKnownConstant(*_op1.length); + std::optional length2 = m_knowledgeBase.valueIfKnownConstant(*_op2.length); if ( (length1 && *length1 <= 32) && (length2 && *length2 <= 32) && @@ -384,13 +383,13 @@ bool UnusedStoreEliminator::knownCovered( // i.start <= e.start && e.start + e.length <= i.start + i.length if (!_covered.start || !_covering.start || !_covered.length || !_covering.length) return false; - optional coveredLength = m_knowledgeBase.valueIfKnownConstant(*_covered.length); - optional coveringLength = m_knowledgeBase.valueIfKnownConstant(*_covering.length); + std::optional coveredLength = m_knowledgeBase.valueIfKnownConstant(*_covered.length); + std::optional coveringLength = m_knowledgeBase.valueIfKnownConstant(*_covering.length); if (*_covered.start == *_covering.start) if (coveredLength && coveringLength && *coveredLength <= *coveringLength) return true; - optional coveredStart = m_knowledgeBase.valueIfKnownConstant(*_covered.start); - optional coveringStart = m_knowledgeBase.valueIfKnownConstant(*_covering.start); + std::optional coveredStart = m_knowledgeBase.valueIfKnownConstant(*_covered.start); + std::optional coveringStart = m_knowledgeBase.valueIfKnownConstant(*_covering.start); if (coveredStart && coveringStart && coveredLength && coveringLength) if ( *coveringStart <= *coveredStart && @@ -408,32 +407,32 @@ bool UnusedStoreEliminator::knownCovered( } void UnusedStoreEliminator::markActiveAsUsed( - optional _onlyLocation + std::optional _onlyLocation ) { - if (_onlyLocation == nullopt || _onlyLocation == Location::Memory) + if (_onlyLocation == std::nullopt || _onlyLocation == Location::Memory) for (Statement const* statement: activeMemoryStores()) m_usedStores.insert(statement); - if (_onlyLocation == nullopt || _onlyLocation == Location::Storage) + if (_onlyLocation == std::nullopt || _onlyLocation == Location::Storage) for (Statement const* statement: activeStorageStores()) m_usedStores.insert(statement); clearActive(_onlyLocation); } void UnusedStoreEliminator::clearActive( - optional _onlyLocation + std::optional _onlyLocation ) { - if (_onlyLocation == nullopt || _onlyLocation == Location::Memory) + if (_onlyLocation == std::nullopt || _onlyLocation == Location::Memory) activeMemoryStores() = {}; - if (_onlyLocation == nullopt || _onlyLocation == Location::Storage) + if (_onlyLocation == std::nullopt || _onlyLocation == Location::Storage) activeStorageStores() = {}; } -optional UnusedStoreEliminator::identifierNameIfSSA(Expression const& _expression) const +std::optional UnusedStoreEliminator::identifierNameIfSSA(Expression const& _expression) const { - if (Identifier const* identifier = get_if(&_expression)) + if (Identifier const* identifier = std::get_if(&_expression)) if (m_ssaValues.count(identifier->name)) return {identifier->name}; - return nullopt; + return std::nullopt; } diff --git a/libyul/optimiser/VarDeclInitializer.cpp b/libyul/optimiser/VarDeclInitializer.cpp index 9b96bef3b..845c7cc41 100644 --- a/libyul/optimiser/VarDeclInitializer.cpp +++ b/libyul/optimiser/VarDeclInitializer.cpp @@ -23,7 +23,6 @@ #include #include -using namespace std; using namespace solidity; using namespace solidity::yul; @@ -31,7 +30,7 @@ void VarDeclInitializer::operator()(Block& _block) { ASTModifier::operator()(_block); - using OptionalStatements = std::optional>; + using OptionalStatements = std::optional>; util::GenericVisitor visitor{ util::VisitorFallback{}, [this](VariableDeclaration& _varDecl) -> OptionalStatements @@ -41,15 +40,15 @@ void VarDeclInitializer::operator()(Block& _block) if (_varDecl.variables.size() == 1) { - _varDecl.value = make_unique(m_dialect.zeroLiteralForType(_varDecl.variables.front().type)); + _varDecl.value = std::make_unique(m_dialect.zeroLiteralForType(_varDecl.variables.front().type)); return {}; } else { - OptionalStatements ret{vector{}}; + OptionalStatements ret{std::vector{}}; for (auto& var: _varDecl.variables) { - unique_ptr expr = make_unique(m_dialect.zeroLiteralForType(var.type)); + std::unique_ptr expr = std::make_unique(m_dialect.zeroLiteralForType(var.type)); ret->emplace_back(VariableDeclaration{std::move(_varDecl.debugData), {std::move(var)}, std::move(expr)}); } return ret; diff --git a/libyul/optimiser/VarNameCleaner.cpp b/libyul/optimiser/VarNameCleaner.cpp index 09093f5aa..b13dc8e6b 100644 --- a/libyul/optimiser/VarNameCleaner.cpp +++ b/libyul/optimiser/VarNameCleaner.cpp @@ -29,20 +29,19 @@ #include #include -using namespace std; using namespace solidity::yul; VarNameCleaner::VarNameCleaner( Block const& _ast, Dialect const& _dialect, - set _namesToKeep + std::set _namesToKeep ): m_dialect{_dialect}, m_namesToKeep{std::move(_namesToKeep)}, m_translatedNames{} { for (auto const& statement: _ast.statements) - if (holds_alternative(statement)) + if (std::holds_alternative(statement)) m_namesToKeep.insert(std::get(statement).name); m_usedNames = m_namesToKeep; } @@ -52,9 +51,9 @@ void VarNameCleaner::operator()(FunctionDefinition& _funDef) yulAssert(!m_insideFunction, ""); m_insideFunction = true; - set globalUsedNames = std::move(m_usedNames); + std::set globalUsedNames = std::move(m_usedNames); m_usedNames = m_namesToKeep; - map globalTranslatedNames; + std::map globalTranslatedNames; swap(globalTranslatedNames, m_translatedNames); renameVariables(_funDef.parameters); @@ -73,7 +72,7 @@ void VarNameCleaner::operator()(VariableDeclaration& _varDecl) ASTModifier::operator()(_varDecl); } -void VarNameCleaner::renameVariables(vector& _variables) +void VarNameCleaner::renameVariables(std::vector& _variables) { for (TypedName& typedName: _variables) { @@ -101,9 +100,9 @@ YulString VarNameCleaner::findCleanName(YulString const& _name) const return newName; // create new name with suffix (by finding a free identifier) - for (size_t i = 1; i < numeric_limits::max(); ++i) + for (size_t i = 1; i < std::numeric_limits::max(); ++i) { - YulString newNameSuffixed = YulString{newName.str() + "_" + to_string(i)}; + YulString newNameSuffixed = YulString{newName.str() + "_" + std::to_string(i)}; if (!isUsedName(newNameSuffixed)) return newNameSuffixed; } @@ -117,9 +116,9 @@ bool VarNameCleaner::isUsedName(YulString const& _name) const YulString VarNameCleaner::stripSuffix(YulString const& _name) const { - static regex const suffixRegex("(_+[0-9]+)+$"); + static std::regex const suffixRegex("(_+[0-9]+)+$"); - smatch suffixMatch; + std::smatch suffixMatch; if (regex_search(_name.str(), suffixMatch, suffixRegex)) return {YulString{suffixMatch.prefix().str()}}; return _name; diff --git a/scripts/check_style.sh b/scripts/check_style.sh index 69955f717..09b17ce7d 100755 --- a/scripts/check_style.sh +++ b/scripts/check_style.sh @@ -35,6 +35,7 @@ NAMESPACE_STD_FREE_FILES=( libsolidity/parsing/* libsolutil/* libyul/backends/evm/* + libyul/optimiser/* solc/* )