From 740c4f773e6ee90bd348b91a8aefdd091f1b8724 Mon Sep 17 00:00:00 2001 From: jonmeow Date: Wed, 11 Dec 2024 08:57:59 -0800 Subject: [PATCH] Make more use of llvm STLExtras --- common/array_stack.h | 2 +- common/command_line.cpp | 7 ++--- common/hashing_test.cpp | 33 +++++++++------------- common/raw_hashtable_benchmark_helpers.cpp | 8 +++--- testing/base/source_gen.cpp | 6 ++-- testing/file_test/autoupdate.h | 4 +-- toolchain/check/deduce.cpp | 2 +- toolchain/check/impl_lookup.cpp | 12 ++++---- toolchain/check/scope_stack.cpp | 5 ++-- toolchain/lex/lex.cpp | 5 ++-- toolchain/lex/numeric_literal.cpp | 5 ++-- toolchain/lex/tokenized_buffer.cpp | 11 ++++---- toolchain/parse/extract.cpp | 2 +- toolchain/sem_ir/facet_type_info.cpp | 4 +-- toolchain/testing/coverage_helper.h | 4 +-- 15 files changed, 49 insertions(+), 61 deletions(-) diff --git a/common/array_stack.h b/common/array_stack.h index 9021c8a4bdb53..8fdbbfe47259c 100644 --- a/common/array_stack.h +++ b/common/array_stack.h @@ -78,7 +78,7 @@ class ArrayStack { auto AppendToTop(llvm::ArrayRef values) -> void { CARBON_CHECK(!array_offsets_.empty(), "Must call PushArray before PushValues."); - values_.append(values.begin(), values.end()); + llvm::append_range(values_, values); } // Returns the current number of values in all arrays. diff --git a/common/command_line.cpp b/common/command_line.cpp index f17878ce716ce..95134bed0aa1d 100644 --- a/common/command_line.cpp +++ b/common/command_line.cpp @@ -1070,10 +1070,9 @@ auto Parser::FinalizeParsedOptions() -> ErrorOr { // Sort the missing arguments by name to provide a stable and deterministic // error message. We know there can't be duplicate names because these came // from a may keyed on the name, so this provides a total ordering. - std::sort(missing_options.begin(), missing_options.end(), - [](const Arg* lhs, const Arg* rhs) { - return lhs->info.name < rhs->info.name; - }); + llvm::sort(missing_options, [](const Arg* lhs, const Arg* rhs) { + return lhs->info.name < rhs->info.name; + }); std::string error_str = "required options not provided: "; llvm::raw_string_ostream error(error_str); diff --git a/common/hashing_test.cpp b/common/hashing_test.cpp index c332db8ccac31..df8231abd7433 100644 --- a/common/hashing_test.cpp +++ b/common/hashing_test.cpp @@ -592,9 +592,9 @@ auto FindBitRangeCollisions(llvm::ArrayRef> hashes) // Now we sort by the extracted bit sequence so we can efficiently scan for // colliding bit patterns. - std::sort( - bits_and_indices.begin(), bits_and_indices.end(), - [](const auto& lhs, const auto& rhs) { return lhs.bits < rhs.bits; }); + llvm::sort(bits_and_indices, [](const auto& lhs, const auto& rhs) { + return lhs.bits < rhs.bits; + }); // Scan the sorted bit sequences we've extracted looking for collisions. We // count the total collisions, but we also track the number of individual @@ -635,16 +635,15 @@ auto FindBitRangeCollisions(llvm::ArrayRef> hashes) } // Sort by collision count for each hash. - std::sort(bits_and_indices.begin(), bits_and_indices.end(), - [&](const auto& lhs, const auto& rhs) { - return collision_counts[collision_map[lhs.index]] < - collision_counts[collision_map[rhs.index]]; - }); + llvm::sort(bits_and_indices, [&](const auto& lhs, const auto& rhs) { + return collision_counts[collision_map[lhs.index]] < + collision_counts[collision_map[rhs.index]]; + }); // And compute the median and max. int median = collision_counts [collision_map[bits_and_indices[bits_and_indices.size() / 2].index]]; - int max = *std::max_element(collision_counts.begin(), collision_counts.end()); + int max = *llvm::max_element(collision_counts); CARBON_CHECK(max == collision_counts[collision_map[bits_and_indices.back().index]]); return {.total = total, .median = median, .max = max}; @@ -672,11 +671,9 @@ auto AllByteStringsHashedAndSorted() { hashes.push_back({HashValue(s, TestSeed), s}); } - std::sort(hashes.begin(), hashes.end(), - [](const HashedString& lhs, const HashedString& rhs) { - return static_cast(lhs.hash) < - static_cast(rhs.hash); - }); + llvm::sort(hashes, [](const HashedString& lhs, const HashedString& rhs) { + return static_cast(lhs.hash) < static_cast(rhs.hash); + }); CheckNoDuplicateValues(hashes); return hashes; @@ -832,11 +829,9 @@ struct SparseHashTest : ::testing::Test { } } - std::sort(hashes.begin(), hashes.end(), - [](const HashedString& lhs, const HashedString& rhs) { - return static_cast(lhs.hash) < - static_cast(rhs.hash); - }); + llvm::sort(hashes, [](const HashedString& lhs, const HashedString& rhs) { + return static_cast(lhs.hash) < static_cast(rhs.hash); + }); CheckNoDuplicateValues(hashes); return hashes; diff --git a/common/raw_hashtable_benchmark_helpers.cpp b/common/raw_hashtable_benchmark_helpers.cpp index 1199748b35fb5..5ba7cd13b6536 100644 --- a/common/raw_hashtable_benchmark_helpers.cpp +++ b/common/raw_hashtable_benchmark_helpers.cpp @@ -349,10 +349,10 @@ auto DumpHashStatistics(llvm::ArrayRef keys) -> void { grouped_key_indices[hash_index].push_back(i); } ssize_t max_group_index = - std::max_element(grouped_key_indices.begin(), grouped_key_indices.end(), - [](const auto& lhs, const auto& rhs) { - return lhs.size() < rhs.size(); - }) - + llvm::max_element(grouped_key_indices, + [](const auto& lhs, const auto& rhs) { + return lhs.size() < rhs.size(); + }) - grouped_key_indices.begin(); // If the max number of collisions on the index is less than or equal to the diff --git a/testing/base/source_gen.cpp b/testing/base/source_gen.cpp index 673225320d810..819dccc6e3c47 100644 --- a/testing/base/source_gen.cpp +++ b/testing/base/source_gen.cpp @@ -206,7 +206,7 @@ auto SourceGen::ClassGenState::BuildClassAndTypeNames( int num_declared_types = num_types * type_use_params.declared_types_weight / type_weight_sum; for ([[maybe_unused]] auto _ : llvm::seq(num_declared_types / num_classes)) { - type_names_.append(class_names_.begin(), class_names_.end()); + llvm::append_range(type_names_, class_names_); } // Now append the remainder number of class names. This is where the class // names being un-shuffled is essential. We're going to have one extra @@ -389,8 +389,8 @@ auto SourceGen::GetIdentifiers(int number, int min_length, int max_length, number, min_length, max_length, uniform, [this](int length, int length_count, llvm::SmallVectorImpl& dest) { - auto length_idents = GetSingleLengthIdentifiers(length, length_count); - dest.append(length_idents.begin(), length_idents.end()); + llvm::append_range(dest, + GetSingleLengthIdentifiers(length, length_count)); }); return idents; diff --git a/testing/file_test/autoupdate.h b/testing/file_test/autoupdate.h index f69f5ac9a5ad0..cc206e48739a5 100644 --- a/testing/file_test/autoupdate.h +++ b/testing/file_test/autoupdate.h @@ -58,8 +58,8 @@ class FileTestAutoupdater { // initialization. stdout_(BuildCheckLines(stdout, "STDOUT")), stderr_(BuildCheckLines(stderr, "STDERR")), - any_attached_stdout_lines_(std::any_of( - stdout_.lines.begin(), stdout_.lines.end(), + any_attached_stdout_lines_(llvm::any_of( + stdout_.lines, [&](const CheckLine& line) { return line.line_number() != -1; })), non_check_line_(non_check_lines_.begin()) { for (const auto& replacement : line_number_replacements_) { diff --git a/toolchain/check/deduce.cpp b/toolchain/check/deduce.cpp index ddb44d4816bf6..c4cfe8e8f016a 100644 --- a/toolchain/check/deduce.cpp +++ b/toolchain/check/deduce.cpp @@ -272,7 +272,7 @@ DeductionContext::DeductionContext(Context& context, SemIR::LocId loc_id, // to substitute them into the function declaration. auto args = context.inst_blocks().Get( context.specifics().Get(enclosing_specific_id).args_id); - std::copy(args.begin(), args.end(), result_arg_ids_.begin()); + llvm::copy(args, result_arg_ids_.begin()); // TODO: Subst is linear in the length of the substitutions list. Change // it so we can pass in an array mapping indexes to substitutions instead. diff --git a/toolchain/check/impl_lookup.cpp b/toolchain/check/impl_lookup.cpp index e0dc94187ccd3..53bc43686033f 100644 --- a/toolchain/check/impl_lookup.cpp +++ b/toolchain/check/impl_lookup.cpp @@ -38,8 +38,7 @@ static auto FindAssociatedImportIRs(Context& context, // Push the contents of an instruction block onto our worklist. auto push_block = [&](SemIR::InstBlockId block_id) { if (block_id.is_valid()) { - auto block = context.inst_blocks().Get(block_id); - worklist.append(block.begin(), block.end()); + llvm::append_range(worklist, context.inst_blocks().Get(block_id)); } }; @@ -102,11 +101,10 @@ static auto FindAssociatedImportIRs(Context& context, } // Deduplicate. - std::sort(result.begin(), result.end(), - [](SemIR::ImportIRId a, SemIR::ImportIRId b) { - return a.index < b.index; - }); - result.erase(std::unique(result.begin(), result.end()), result.end()); + llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) { + return a.index < b.index; + }); + result.erase(llvm::unique(result), result.end()); return result; } diff --git a/toolchain/check/scope_stack.cpp b/toolchain/check/scope_stack.cpp index cccdeeebfd698..019c30714c8cd 100644 --- a/toolchain/check/scope_stack.cpp +++ b/toolchain/check/scope_stack.cpp @@ -129,9 +129,8 @@ auto ScopeStack::LookupInLexicalScopes(SemIR::NameId name_id) // Find the first non-lexical scope that is within the scope of the lexical // lookup result. - auto* first_non_lexical_scope = std::lower_bound( - non_lexical_scope_stack_.begin(), non_lexical_scope_stack_.end(), - lexical_results.back().scope_index, + auto* first_non_lexical_scope = llvm::lower_bound( + non_lexical_scope_stack_, lexical_results.back().scope_index, [](const NonLexicalScope& scope, ScopeIndex index) { return scope.scope_index < index; }); diff --git a/toolchain/lex/lex.cpp b/toolchain/lex/lex.cpp index f11c2b8fce1b0..8cfbb3c2eea4e 100644 --- a/toolchain/lex/lex.cpp +++ b/toolchain/lex/lex.cpp @@ -1555,9 +1555,8 @@ auto Lexer::DiagnoseAndFixMismatchedBrackets() -> void { } // Find the innermost matching opening symbol. - auto opening_it = std::find_if( - open_groups_.rbegin(), open_groups_.rend(), - [&](TokenIndex opening_token) { + auto opening_it = llvm::find_if( + llvm::reverse(open_groups_), [&](TokenIndex opening_token) { return buffer_.GetTokenInfo(opening_token).kind().closing_symbol() == kind; }); diff --git a/toolchain/lex/numeric_literal.cpp b/toolchain/lex/numeric_literal.cpp index d75de7e8881aa..8a197bf8a1ae4 100644 --- a/toolchain/lex/numeric_literal.cpp +++ b/toolchain/lex/numeric_literal.cpp @@ -185,9 +185,8 @@ static auto ParseInt(llvm::StringRef digits, NumericLiteral::Radix radix, llvm::SmallString<32> cleaned; if (needs_cleaning) { cleaned.reserve(digits.size()); - std::remove_copy_if(digits.begin(), digits.end(), - std::back_inserter(cleaned), - [](char c) { return c == '_' || c == '.'; }); + llvm::copy_if(digits, std::back_inserter(cleaned), + [](char c) { return c != '_' && c != '.'; }); digits = cleaned; } diff --git a/toolchain/lex/tokenized_buffer.cpp b/toolchain/lex/tokenized_buffer.cpp index 6aec49a05cec7..e4a7652033438 100644 --- a/toolchain/lex/tokenized_buffer.cpp +++ b/toolchain/lex/tokenized_buffer.cpp @@ -317,10 +317,9 @@ auto TokenizedBuffer::PrintToken(llvm::raw_ostream& output_stream, auto TokenizedBuffer::FindLineIndex(int32_t byte_offset) const -> LineIndex { CARBON_DCHECK(!line_infos_.empty()); const auto* line_it = - std::partition_point(line_infos_.begin(), line_infos_.end(), - [byte_offset](LineInfo line_info) { - return line_info.start <= byte_offset; - }); + llvm::partition_point(line_infos_, [byte_offset](LineInfo line_info) { + return line_info.start <= byte_offset; + }); --line_it; // If this isn't the first line but it starts past the end of the source, then @@ -386,8 +385,8 @@ auto TokenizedBuffer::SourceBufferDiagnosticConverter::ConvertLoc( int32_t offset = loc - buffer_->source_->text().begin(); // Find the first line starting after the given location. - const auto* next_line_it = std::partition_point( - buffer_->line_infos_.begin(), buffer_->line_infos_.end(), + const auto* next_line_it = llvm::partition_point( + buffer_->line_infos_, [offset](const LineInfo& line) { return line.start <= offset; }); // Step back one line to find the line containing the given position. diff --git a/toolchain/parse/extract.cpp b/toolchain/parse/extract.cpp index 7106754d9fef7..ae4b87d0161dd 100644 --- a/toolchain/parse/extract.cpp +++ b/toolchain/parse/extract.cpp @@ -201,7 +201,7 @@ auto NodeExtractor::MatchesNodeIdOneOf( *trace_ << "\n"; } return false; - } else if (std::find(kinds.begin(), kinds.end(), node_kind) == kinds.end()) { + } else if (llvm::find(kinds, node_kind) == kinds.end()) { if (trace_) { *trace_ << "NodeIdOneOf error: wrong kind " << node_kind << ", expected "; trace_kinds(); diff --git a/toolchain/sem_ir/facet_type_info.cpp b/toolchain/sem_ir/facet_type_info.cpp index 667c3070a88b9..14eaa025e081e 100644 --- a/toolchain/sem_ir/facet_type_info.cpp +++ b/toolchain/sem_ir/facet_type_info.cpp @@ -8,8 +8,8 @@ namespace Carbon::SemIR { template static auto SortAndDeduplicate(VecT* vec) -> void { - std::sort(vec->begin(), vec->end()); - vec->erase(std::unique(vec->begin(), vec->end()), vec->end()); + llvm::sort(*vec); + vec->erase(llvm::unique(*vec), vec->end()); } auto FacetTypeInfo::Canonicalize() -> void { diff --git a/toolchain/testing/coverage_helper.h b/toolchain/testing/coverage_helper.h index e91dc5792c999..135ddb72f7345 100644 --- a/toolchain/testing/coverage_helper.h +++ b/toolchain/testing/coverage_helper.h @@ -64,14 +64,14 @@ auto TestKindCoverage(const std::string& manifest_path, constexpr llvm::StringLiteral Bullet = "\n - "; - std::sort(missing_kinds.begin(), missing_kinds.end()); + llvm::sort(missing_kinds); EXPECT_TRUE(missing_kinds.empty()) << "Some kinds have no tests:" << Bullet << llvm::join(missing_kinds, Bullet); llvm::SmallVector unexpected_matches; covered_kinds.ForEach( [&](const std::string& match) { unexpected_matches.push_back(match); }); - std::sort(unexpected_matches.begin(), unexpected_matches.end()); + llvm::sort(unexpected_matches); EXPECT_TRUE(unexpected_matches.empty()) << "Matched things that aren't in the kind list:" << Bullet << llvm::join(unexpected_matches, Bullet);