From d34eecbaded4a2827617315880458e0665ab7a9e Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 05:12:05 +0300 Subject: [PATCH 1/2] [movegen] Generate moves into fixed-capacity inplace vectors Move generation wrote through PseudoLegalMove*& cursors into caller-owned std::array buffers, and legal moves came back in a heap-allocated std::vector. Add InplaceVector, a fixed-capacity vector with the subset of the std::inplace_vector interface the engine needs. std::inplace_vector itself needs libstdc++ 16, and GCC 16 currently builds this engine slower. GeneratePseudoLegalMoves and GenerateLegalMoves return PseudoLegalMoves and LegalMoves by value, the helpers append with unchecked_push_back, the en passant filter is erase_if, and callers use range-for, std::ranges::contains and views::concat instead of pointer loops. GenerateMoves duplicated GenerateLegalMoves and is gone. The principal variation gets its own type bounded by the deepest depth, so move generation and PV extraction no longer allocate. Search is unchanged: identical nodes and best moves on 30 positions, perft startpos d5 4865609 and kiwipete d4 4085603. The push loops keep the size in a register and store it once, and the returned lists are built in place without copies. Instructions per node +0.04% (11708-11719 vs 11714-11721), cycles within noise. Co-Authored-By: Claude Opus 5.5 --- Chess/InplaceVector.h | 83 ++++++++++++++++++ Chess/MoveGenerator.cpp | 143 ++++++++++++++++---------------- Chess/MoveGenerator.h | 31 ++++--- Chess/MovePicker.cpp | 32 +++---- Chess/Position.cpp | 10 +-- Chess/Searcher.h | 14 ++-- Chess/SimpleChessEngine.h | 4 +- Chess/UciCommunicator.h | 2 +- Tests/StagedMovePickerTests.cpp | 30 +++---- Tests/TypedMoveTests.cpp | 3 - Tools/TablebaseBenchmark.cpp | 2 +- 11 files changed, 216 insertions(+), 138 deletions(-) create mode 100644 Chess/InplaceVector.h diff --git a/Chess/InplaceVector.h b/Chess/InplaceVector.h new file mode 100644 index 0000000..68b4e63 --- /dev/null +++ b/Chess/InplaceVector.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace SimpleChessEngine { + +template +using SmallestSizeType = std::conditional_t< + capacity <= std::numeric_limits::max(), std::uint8_t, + std::conditional_t::max(), + std::uint16_t, std::size_t>>; + +template + requires std::is_trivially_copyable_v && + std::is_trivially_default_constructible_v +class InplaceVector { + public: + using value_type = T; + using size_type = SmallestSizeType; + using difference_type = std::ptrdiff_t; + using reference = T&; + using const_reference = const T&; + using pointer = T*; + using const_pointer = const T*; + using iterator = T*; + using const_iterator = const T*; + + constexpr InplaceVector() noexcept = default; + + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + [[nodiscard]] constexpr size_type size() const noexcept { return size_; } + [[nodiscard]] constexpr bool empty() const noexcept { return size_ == 0; } + + [[nodiscard]] constexpr iterator begin() noexcept { return elements_.data(); } + [[nodiscard]] constexpr const_iterator begin() const noexcept { + return elements_.data(); + } + [[nodiscard]] constexpr iterator end() noexcept { return begin() + size_; } + [[nodiscard]] constexpr const_iterator end() const noexcept { + return begin() + size_; + } + + [[nodiscard]] constexpr reference operator[](size_type index) noexcept { + assert(index < size_); + return elements_[index]; + } + [[nodiscard]] constexpr const_reference operator[]( + size_type index) const noexcept { + assert(index < size_); + return elements_[index]; + } + [[nodiscard]] constexpr reference front() noexcept { return (*this)[0]; } + [[nodiscard]] constexpr const_reference front() const noexcept { + return (*this)[0]; + } + + constexpr reference unchecked_push_back(const T& value) noexcept { + assert(size_ < N); + return elements_[size_++] = value; + } + + template + friend constexpr size_type erase_if(InplaceVector& vector, + Predicate predicate) { + const auto kept_end = + std::remove_if(vector.begin(), vector.end(), predicate); + const auto erased = static_cast(vector.end() - kept_end); + vector.size_ = static_cast(kept_end - vector.begin()); + return erased; + } + + private: + std::array elements_; + size_type size_ = 0; +}; + +} // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index 060012e..a7111a4 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -7,17 +7,17 @@ #include "BitBoard.h" namespace SimpleChessEngine { -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kAll>(Position& position) const; -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kQuiescence>(Position& position) const; -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kAddChecks>(Position& position) const; MoveGenerator::~MoveGenerator() = default; -void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, - const Position& position) { +void MoveGenerator::GenerateCastling(PseudoLegalMoves& moves, + const Position& position) { if (position.IsUnderCheck()) { return; } @@ -31,14 +31,15 @@ void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, const auto side_idx = static_cast(castling_side); const auto king_to = kKingCastlingDestination[color_idx][side_idx]; - *moves++ = PseudoLegalMove( - Move::Make(king_square, king_to)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(king_square, king_to))); } } } template -void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMoves& moves, + Position& position, const Bitboard target) const { static_assert(piece != Piece::kPawn && piece != Piece::kKing); @@ -53,7 +54,7 @@ void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& pos template <> void MoveGenerator::GenerateMovesForPiece( - PseudoLegalMove*& moves, Position& position, const Bitboard target) const { + PseudoLegalMoves& moves, Position& position, const Bitboard target) const { const auto us = position.GetSideToMove(); const auto us_idx = static_cast(us); const auto them = Flip(us); @@ -78,7 +79,7 @@ void MoveGenerator::GenerateMovesForPiece( while (push.Any()) { const auto to = push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } auto double_push = Shift(double_push_pawns, direction) & valid_squares; @@ -87,7 +88,7 @@ void MoveGenerator::GenerateMovesForPiece( while (double_push.Any()) { const auto to = double_push.PopFirstBit(); const auto from = Shift(Shift(to, opposite_direction), opposite_direction); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } static constexpr std::array cant_attack_files = {kFileBB[0], kFileBB[7]}; @@ -117,7 +118,7 @@ void MoveGenerator::GenerateMovesForPiece( while (attack_squares.Any()) { const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } } @@ -130,7 +131,7 @@ void MoveGenerator::GenerateMovesForPiece( if (attack_to.Any()) { const auto to = en_croissant_square.value(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove(Move::Make(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move::Make(from, to))); } } } @@ -144,14 +145,14 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = promotion_push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kQueen)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kKnight)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kRook)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kBishop)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kQueen))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kKnight))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kRook))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kBishop))); } for (size_t attack_direction = 0; attack_direction < attacks.size(); @@ -165,21 +166,22 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kQueen)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kKnight)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kRook)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kBishop)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kQueen))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kKnight))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kRook))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kBishop))); } } } template -PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, - PseudoLegalMove* moves) const { +MoveGenerator::PseudoLegalMoves MoveGenerator::GeneratePseudoLegalMoves( + Position& position) const { + PseudoLegalMoves moves; const auto us = position.GetSideToMove(); const auto them = Flip(us); auto target = ~position.GetPieces(us); @@ -208,24 +210,17 @@ PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, target &= ray; pawn_target &= ray; } - auto* pawn_begin = moves; GenerateMovesForPiece(moves, position, pawn_target & ~position.GetPieces(us)); - auto* pawn_end = moves; - moves = pawn_begin; - for (auto* p = pawn_begin; p != pawn_end; ++p) { - if constexpr (type == Type::kQuiets) { - if (p->IsEnPassant()) continue; - } - if (p->IsEnPassant() && checkers.Any()) { - const auto captured = - static_cast(p->To() + (us == Player::kWhite ? -8 : 8)); - if (!checkers.Test(captured) && - !Between(king_square, checkers.GetFirstBit()).Test(p->To())) - continue; - } - *moves++ = *p; - } + erase_if(moves, [&](const PseudoLegalMove move) { + if (!move.IsEnPassant()) return false; + if constexpr (type == Type::kQuiets) return true; + if (checkers.None()) return false; + const auto captured = + static_cast(move.To() + (us == Player::kWhite ? -8 : 8)); + return !checkers.Test(captured) && + !Between(king_square, checkers.GetFirstBit()).Test(move.To()); + }); auto generate = [&]() { auto piece_target = target; if constexpr (type == Type::kAddChecks) { @@ -248,40 +243,43 @@ PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, } template -MoveGenerator::Moves MoveGenerator::GenerateMoves(Position& position) const { - std::array moves; - auto* end = GeneratePseudoLegal(position, moves.data()); +MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves( + Position& position) const { + const auto pseudo_legal = GeneratePseudoLegalMoves(position); position.ComputePins(position.GetSideToMove()); - Moves legal; - legal.reserve(end - moves.data()); - for (auto* p = moves.data(); p != end; ++p) { - if (position.IsLegal(*p)) legal.push_back(LegalMove(static_cast(*p))); + LegalMoves legal; + for (const auto move : pseudo_legal) { + if (position.IsLegal(move)) { + legal.unchecked_push_back(LegalMove(static_cast(move))); + } } return legal; } bool MoveGenerator::HasLegalMove(Position& position) const { - std::array moves; - auto* end = GeneratePseudoLegal(position, moves.data()); + const auto pseudo_legal = GeneratePseudoLegalMoves(position); position.ComputePins(position.GetSideToMove()); - return std::any_of(moves.data(), end, - [&position](Move move) { - return position.IsLegal(move); - }); + return std::ranges::any_of(pseudo_legal, + [&position](const PseudoLegalMove move) { + return position.IsLegal(move); + }); } -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( - Position&, PseudoLegalMove*) const; -template PseudoLegalMove* -MoveGenerator::GeneratePseudoLegal(Position&, - PseudoLegalMove*) const; -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( - Position&, PseudoLegalMove*) const; -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal< - MoveGenerator::Type::kQuiescence>(Position&, PseudoLegalMove*) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; template <> -void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMoves& moves, Position& position, Bitboard target) const { GenerateMovesFromSquare( @@ -290,7 +288,8 @@ void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, } template -void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, +void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMoves& moves, + Position& position, const BitIndex from, Bitboard target) const { assert(position.GetPieceAt(from) == piece); @@ -304,7 +303,7 @@ void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& p while (valid_moves.Any()) { const auto to = valid_moves.PopFirstBit(); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } } } // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.h b/Chess/MoveGenerator.h index cb8fb2c..c5c3d6b 100644 --- a/Chess/MoveGenerator.h +++ b/Chess/MoveGenerator.h @@ -1,8 +1,9 @@ #pragma once +#include #include -#include +#include "InplaceVector.h" #include "Move.h" #include "Position.h" @@ -22,12 +23,14 @@ class MoveGenerator { kQuiets = 8 }; - static constexpr size_t kMaxMovesPerPosition = 256; + static constexpr std::size_t kMaxMovesPerPosition = 256; + + using PseudoLegalMoves = InplaceVector; + using LegalMoves = InplaceVector; + MoveGenerator() = default; ~MoveGenerator(); - using Moves = std::vector; - /** * \brief Generates all possible moves for a given position. * @@ -36,16 +39,11 @@ class MoveGenerator { * \return All possible moves for the given position. */ template - [[nodiscard]] Moves GenerateMoves(Position& position) const; - - template - [[nodiscard, gnu::always_inline]] Moves GenerateLegalMoves(Position& position) const { - return GenerateMoves(position); - } + [[nodiscard]] LegalMoves GenerateLegalMoves(Position& position) const; template - [[nodiscard]] PseudoLegalMove* GeneratePseudoLegal(Position& position, - PseudoLegalMove* moves) const; + [[nodiscard]] PseudoLegalMoves GeneratePseudoLegalMoves( + Position& position) const; [[nodiscard]] bool HasLegalMove(Position& position) const; @@ -60,7 +58,7 @@ class MoveGenerator { * \return All possible moves for the given square. */ template - void GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, + void GenerateMovesForPiece(PseudoLegalMoves& moves, Position& position, Bitboard target) const; /** @@ -75,10 +73,11 @@ class MoveGenerator { * \return All possible moves for the given square and piece. */ template - void GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, BitIndex from, - Bitboard target) const; + void GenerateMovesFromSquare(PseudoLegalMoves& moves, Position& position, + BitIndex from, Bitboard target) const; - static void GenerateCastling(PseudoLegalMove*& moves, const Position& position); + static void GenerateCastling(PseudoLegalMoves& moves, + const Position& position); }; } // namespace SimpleChessEngine diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index 54eca22..f2a8830 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -61,27 +61,21 @@ void MovePicker::InitPicker(Position& position, const Searcher* searcher, } void MovePicker::Generate(bool quiet) { - std::array generated; - auto* begin = generated.data(); - PseudoLegalMove* end; - const MoveGenerator generator; - if (quiet) { - end = generator.GeneratePseudoLegal( - *position_, begin); - } else if (!searcher_ && evasions_) { - end = generator.GeneratePseudoLegal(*position_, - begin); - } else if (!searcher_) { - end = generator.GeneratePseudoLegal( - *position_, begin); - } else { - end = generator.GeneratePseudoLegal( - *position_, begin); - } + const auto generated = [this, quiet] { + using enum MoveGenerator::Type; + const MoveGenerator generator; + if (quiet) return generator.GeneratePseudoLegalMoves(*position_); + if (!searcher_ && evasions_) { + return generator.GeneratePseudoLegalMoves(*position_); + } + if (!searcher_) { + return generator.GeneratePseudoLegalMoves(*position_); + } + return generator.GeneratePseudoLegalMoves(*position_); + }(); current_ = quiet ? bad_end_ : 0; end_ = current_; - for (auto* p = begin; p != end; ++p) { - const auto move = *p; + for (const auto move : generated) { if (move == tt_move_ || move == excluded_move_ || (quiet && std::ranges::find(killers_, move) != killers_.end())) continue; diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 52f209e..4648c72 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -1,5 +1,6 @@ #include "Position.h" +#include #include #include "Attacks.h" @@ -345,11 +346,10 @@ bool Position::IsPseudoLegal(const Move &move) { const auto to = move.To(); if (!GetPieces(side_to_move_).Test(from)) return false; if (!move.IsNormal()) { - std::array moves; - const auto *end = - MoveGenerator{}.GeneratePseudoLegal( - *this, moves.data()); - return std::find(static_cast(moves.data()), end, move) != end; + return std::ranges::contains( + MoveGenerator{}.GeneratePseudoLegalMoves( + *this), + move); } if ((move.Raw() & 0x3000) || from == to || GetPieces(side_to_move_).Test(to)) return false; diff --git a/Chess/Searcher.h b/Chess/Searcher.h index b8abeef..72c4bbc 100644 --- a/Chess/Searcher.h +++ b/Chess/Searcher.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -119,7 +120,10 @@ class Searcher { [[nodiscard]] std::int64_t GetQuietScore(const Move &move, Depth ply) const; [[nodiscard]] std::uint64_t GetRootEffort(const Move &move) const; - [[nodiscard]] MoveGenerator::Moves GetPrincipalVariation( + using PrincipalVariation = + InplaceVector::max()>; + + [[nodiscard]] PrincipalVariation GetPrincipalVariation( Depth max_depth, Position position) const; private: @@ -179,9 +183,9 @@ inline const Position &Searcher::GetPosition() const { return current_position_; inline const Move &Searcher::GetCurrentBestMove() const { return best_move_; } -inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, - Position position) const { - MoveGenerator::Moves answer; +inline Searcher::PrincipalVariation Searcher::GetPrincipalVariation( + Depth max_depth, Position position) const { + PrincipalVariation answer; for (Depth i = 0; i < max_depth; ++i) { const auto hashed_node = best_moves_->GetNode(position); if (!hashed_node.IsOccupied() || @@ -193,7 +197,7 @@ inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, if (found == legal_moves.end()) break; position.DoMove(*found); - answer.push_back(*found); + answer.unchecked_push_back(*found); } return answer; } diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index 3032096..0c67278 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -36,7 +36,7 @@ struct NodePerSecondInfo { struct PrincipalVariationInfo { size_t current_depth = 0; - MoveGenerator::Moves moves; + Searcher::PrincipalVariation moves; }; struct BestMoveInfo { @@ -256,7 +256,7 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( }; const auto legal_moves = - MoveGenerator{}.GenerateMoves(position_); + MoveGenerator{}.GenerateLegalMoves(position_); if (legal_moves.empty()) { finish(BestMoveInfo{Move::None(), std::nullopt}); return; diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index bbf81bf..b2d7362 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -149,7 +149,7 @@ class SearchThread { Position position = info.position; if (MoveGenerator{} - .GenerateMoves(position) + .GenerateLegalMoves(position) .size() == 1) { optimum = std::min(optimum, kSingleMoveTime); } diff --git a/Tests/StagedMovePickerTests.cpp b/Tests/StagedMovePickerTests.cpp index 73e5177..574fc10 100644 --- a/Tests/StagedMovePickerTests.cpp +++ b/Tests/StagedMovePickerTests.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include "MoveGenerator.h" @@ -41,11 +42,12 @@ TEST(StagedMovePicker, PseudoLegalValidationMatchesGenerator) { for (const auto* fen : kPositions) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); - std::array generated; - auto* end = MoveGenerator{}.GeneratePseudoLegal( - position, generated.data()); std::set expected; - for (auto* p = generated.data(); p != end; ++p) expected.insert(p->Raw()); + for (const auto move : + MoveGenerator{}.GeneratePseudoLegalMoves( + position)) { + expected.insert(move.Raw()); + } for (unsigned raw = 0; raw < 65536; ++raw) { EXPECT_EQ(position.IsPseudoLegal(Move(static_cast(raw))), expected.contains(raw)) @@ -59,17 +61,17 @@ TEST(StagedMovePicker, CaptureAndQuietStagesPartitionLegalMoves) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); const auto expected = LegalSet(position); - std::array generated; - auto* middle = - MoveGenerator{}.GeneratePseudoLegal( - position, generated.data()); - auto* end = - MoveGenerator{}.GeneratePseudoLegal( - position, middle); + const MoveGenerator generator; + const auto captures = + generator.GeneratePseudoLegalMoves( + position); + const auto quiets = + generator.GeneratePseudoLegalMoves( + position); std::set actual; - for (auto* p = generated.data(); p != end; ++p) { - if (!position.IsLegal(*p)) continue; - EXPECT_TRUE(actual.insert(p->Raw()).second); + for (const auto move : std::views::concat(captures, quiets)) { + if (!position.IsLegal(move)) continue; + EXPECT_TRUE(actual.insert(move.Raw()).second); } EXPECT_EQ(actual, expected); } diff --git a/Tests/TypedMoveTests.cpp b/Tests/TypedMoveTests.cpp index e4e80a9..0446fe2 100644 --- a/Tests/TypedMoveTests.cpp +++ b/Tests/TypedMoveTests.cpp @@ -81,9 +81,6 @@ TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { "4k3/8/8/8/8/8/8/6KR w H - 0 1"}) { auto position = PositionFactory{}(fen); const auto moves = MoveGenerator{}.GenerateLegalMoves(position); - const auto raw_moves = MoveGenerator{}.GenerateMoves(position); - ASSERT_EQ(moves.size(), raw_moves.size()); - for (size_t i = 0; i < moves.size(); ++i) EXPECT_EQ(moves[i], raw_moves[i]); for (const auto move : moves) { const Move raw = move; const PseudoLegalMove degraded = move; diff --git a/Tools/TablebaseBenchmark.cpp b/Tools/TablebaseBenchmark.cpp index 289eb6c..853f280 100644 --- a/Tools/TablebaseBenchmark.cpp +++ b/Tools/TablebaseBenchmark.cpp @@ -81,7 +81,7 @@ int main(int argc, char** argv) { continue; } const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); const auto root_move = tablebase->RootMove(position); if (tablebase->ProbeWdl(position) && root_move && std::ranges::find(moves, *root_move) != moves.end()) { From 1fc4ead763b80bcb22821b4b618949dfcf2cbc5f Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 05:34:48 +0300 Subject: [PATCH 2/2] [movepicker] Sort and search scored moves through ranges PartialInsertionSort took raw begin/end pointers and a limit that was always INT64_MIN, so the partial part never applied. It becomes SortByScore over a ScoredRange, a std::ranges::subrange of the scored move array, written with iterators and std::prev. The killer lookup in bad captures uses std::ranges::find with a &ScoredMove::move projection instead of find_if over data() pointers. The range is a subrange of std::array iterators rather than a std::span: GCC 15 keeps an extra pointer copy per shifted element in loops over span iterators, while array iterators compile to the same 7-instruction inner loop as before. Search is unchanged (identical nodes and best moves on 30 positions); instructions per node 11712-11716 vs 11710-11713, cycles per node 13468-13524 vs 13590-13602. Co-Authored-By: Claude Opus 5.5 --- Chess/MovePicker.cpp | 35 ++++++++++++++++------------------- Chess/MovePicker.h | 10 +++++++--- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index f2a8830..686b3d7 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -1,7 +1,7 @@ #include "MovePicker.h" #include -#include +#include #include "Position.h" #include "Searcher.h" @@ -28,19 +28,16 @@ constexpr int PromotionRank(Piece promotion) { } } // namespace -void MovePicker::PartialInsertionSort(ScoredMove* begin, ScoredMove* end, - std::int64_t limit) { - if (begin == end) return; - for (auto *sorted_end = begin, *p = begin + 1; p < end; ++p) { - if (p->score >= limit) { - const auto tmp = *p; - *p = *++sorted_end; - auto* q = sorted_end; - for (; q != begin && (q - 1)->score < tmp.score; --q) { - *q = *(q - 1); - } - *q = tmp; +void MovePicker::SortByScore(ScoredRange moves) { + if (moves.empty()) return; + for (auto next = std::next(moves.begin()); next != moves.end(); ++next) { + const ScoredMove inserted = *next; + auto slot = next; + for (; slot != moves.begin() && std::prev(slot)->score < inserted.score; + --slot) { + *slot = *std::prev(slot); } + *slot = inserted; } } @@ -97,8 +94,7 @@ void MovePicker::Generate(bool quiet) { moves_[end_++] = {move, score}; } if (searcher_) { - PartialInsertionSort(moves_.data() + current_, moves_.data() + end_, - std::numeric_limits::min()); + SortByScore({moves_.begin() + current_, moves_.begin() + end_}); } } @@ -145,10 +141,11 @@ MaybeLegalMove MovePicker::SelectNextMove() { !position_->IsLegal(move, blockers_)) continue; if (!move.IsQuiet(*position_)) { - auto* found = std::find_if( - moves_.data(), moves_.data() + bad_end_, - [move](const auto& data) { return data.move == move; }); - if (found == moves_.data() + bad_end_) continue; + const ScoredRange bad_captures{moves_.begin(), + moves_.begin() + bad_end_}; + const auto found = + std::ranges::find(bad_captures, move, &ScoredMove::move); + if (found == bad_captures.end()) continue; found->move = Move::None(); } killers_[index] = move; diff --git a/Chess/MovePicker.h b/Chess/MovePicker.h index f2d18db..d3ac68f 100644 --- a/Chess/MovePicker.h +++ b/Chess/MovePicker.h @@ -2,6 +2,7 @@ #include #include #include +#include #include "Evaluation.h" #include "Move.h" @@ -38,12 +39,15 @@ class MovePicker { std::int64_t score; }; - static void PartialInsertionSort(ScoredMove* begin, ScoredMove* end, - std::int64_t limit); + using ScoredMoves = + std::array; + using ScoredRange = std::ranges::subrange; + + static void SortByScore(ScoredRange moves); void Generate(bool quiet); [[nodiscard]] LegalMove Emit(LegalMove move); - std::array moves_; + ScoredMoves moves_; std::array killers_{}; Position* position_ = nullptr; const Searcher* searcher_ = nullptr;