id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,019
|
searchquery.h
|
zealdocs_zeal/src/libs/registry/searchquery.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_SEARCHQUERY_H
#define ZEAL_REGISTRY_SEARCHQUERY_H
#include <QDataStream>
#include <QStringList>
namespace Zeal {
namespace Registry {
/**
* @short The search query model.
*/
class SearchQuery
{
public:
explicit SearchQuery() = default;
explicit SearchQuery(QString query, const QStringList &keywords = QStringList());
/// Creates a search query from a string. Single separator will be
/// used to contstruct docset filter, but separator repeated twice
/// will be left inside coreQuery part since double semicolon is
/// used inside qualified symbol names in popular programming
/// languages (c++, ruby, perl, etc.).
///
/// Examples:
/// "android:setTypeFa" #=> docsetFilters = ["android"], coreQuery = "setTypeFa"
/// "noprefix" #=> docsetFilters = [], coreQuery = "noprefix"
/// ":find" #=> docsetFilters = [], coreQuery = ":find"
/// "std::string" #=> docsetFilters = [], coreQuery = "std::string"
/// "c++:std::string" #=> docsetFilters = ["c++"], coreQuery = "std::string"
///
/// Multiple docsets are supported using the ',' character:
/// "java,android:setTypeFa #=> docsetFilters = ["java", "android"], coreQuery = "setTypeFa"
static SearchQuery fromString(const QString &str);
QString toString() const;
bool isEmpty() const;
QStringList keywords() const;
void setKeywords(const QStringList &list);
/// Returns true if there's a docset filter for the given query
bool hasKeywords() const;
/// Returns true if one the query contains one of the @c keywords.
bool hasKeywords(const QStringList &keywords) const;
/// Returns the docset filter raw size for the given query
int keywordPrefixSize() const;
QString query() const;
void setQuery(const QString &str);
private:
QString m_query;
QStringList m_keywords;
QString m_keywordPrefix;
};
} // namespace Registry
} // namespace Zeal
QDataStream &operator<<(QDataStream &out, const Zeal::Registry::SearchQuery &query);
QDataStream &operator>>(QDataStream &in, Zeal::Registry::SearchQuery &query);
#endif // ZEAL_REGISTRY_SEARCHQUERY_H
| 2,351
|
C++
|
.h
| 55
| 39
| 98
| 0.688899
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,020
|
searchresult.h
|
zealdocs_zeal/src/libs/registry/searchresult.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_SEARCHRESULT_H
#define ZEAL_REGISTRY_SEARCHRESULT_H
#include <QString>
#include <QUrl>
namespace Zeal {
namespace Registry {
class Docset;
struct SearchResult
{
QString name;
QString type;
QString urlPath;
QString urlFragment;
Docset *docset;
int score;
inline bool operator<(const SearchResult &other) const
{
if (score == other.score)
return QString::compare(name, other.name, Qt::CaseInsensitive) < 0;
return score > other.score;
}
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_SEARCHRESULT_H
| 765
|
C++
|
.h
| 28
| 23.642857
| 79
| 0.713499
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,021
|
listmodel.h
|
zealdocs_zeal/src/libs/registry/listmodel.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_LISTMODEL_H
#define ZEAL_REGISTRY_LISTMODEL_H
#include <util/caseinsensitivemap.h>
#include <QAbstractItemModel>
namespace Zeal {
namespace Registry {
class Docset;
class DocsetRegistry;
class ListModel final : public QAbstractItemModel
{
Q_OBJECT
Q_DISABLE_COPY(ListModel)
public:
~ListModel() override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QModelIndex index(int row, int column, const QModelIndex &parent) const override;
QModelIndex parent(const QModelIndex &child) const override;
int columnCount(const QModelIndex &parent) const override;
int rowCount(const QModelIndex &parent) const override;
private slots:
void addDocset(const QString &name);
void removeDocset(const QString &name);
private:
friend class DocsetRegistry;
enum class IndexLevel {
Root,
Docset,
Group,
Symbol
};
explicit ListModel(DocsetRegistry *docsetRegistry);
inline static QString pluralize(const QString &s);
inline static IndexLevel indexLevel(const QModelIndex &index);
DocsetRegistry *m_docsetRegistry = nullptr;
struct DocsetItem;
struct GroupItem {
const IndexLevel level = IndexLevel::Group;
DocsetItem *docsetItem = nullptr;
QString symbolType;
};
struct DocsetItem {
const IndexLevel level = IndexLevel::Docset;
Docset *docset = nullptr;
QList<GroupItem *> groups;
};
inline DocsetItem *itemInRow(int row) const;
Util::CaseInsensitiveMap<DocsetItem *> m_docsetItems;
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_LISTMODEL_H
| 1,959
|
C++
|
.h
| 55
| 30.981818
| 109
| 0.737792
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,022
|
itemdatarole.h
|
zealdocs_zeal/src/libs/registry/itemdatarole.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_ITEMDATAROLE_H
#define ZEAL_REGISTRY_ITEMDATAROLE_H
#include <Qt>
namespace Zeal {
namespace Registry {
enum ItemDataRole {
DocsetIconRole = Qt::UserRole,
DocsetNameRole,
UpdateAvailableRole,
UrlRole
};
enum SectionIndex {
Name,
SearchPrefix,
Actions
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_ITEMDATAROLE_H
| 501
|
C++
|
.h
| 21
| 21.190476
| 61
| 0.750529
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,023
|
movepick.cpp
|
official-stockfish_Stockfish/src/movepick.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "movepick.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <limits>
#include <utility>
#include "bitboard.h"
#include "position.h"
namespace Stockfish {
namespace {
enum Stages {
// generate main search moves
MAIN_TT,
CAPTURE_INIT,
GOOD_CAPTURE,
QUIET_INIT,
GOOD_QUIET,
BAD_CAPTURE,
BAD_QUIET,
// generate evasion moves
EVASION_TT,
EVASION_INIT,
EVASION,
// generate probcut moves
PROBCUT_TT,
PROBCUT_INIT,
PROBCUT,
// generate qsearch moves
QSEARCH_TT,
QCAPTURE_INIT,
QCAPTURE
};
// Sort moves in descending order up to and including a given limit.
// The order of moves smaller than the limit is left unspecified.
void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
if (p->value >= limit)
{
ExtMove tmp = *p, *q;
*p = *++sortedEnd;
for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
*q = *(q - 1);
*q = tmp;
}
}
} // namespace
// Constructors of the MovePicker class. As arguments, we pass information
// to decide which class of moves to emit, to help sorting the (presumably)
// good moves first, and how important move ordering is at the current node.
// MovePicker constructor for the main search and for the quiescence search
MovePicker::MovePicker(const Position& p,
Move ttm,
Depth d,
const ButterflyHistory* mh,
const LowPlyHistory* lph,
const CapturePieceToHistory* cph,
const PieceToHistory** ch,
const PawnHistory* ph,
int pl) :
pos(p),
mainHistory(mh),
lowPlyHistory(lph),
captureHistory(cph),
continuationHistory(ch),
pawnHistory(ph),
ttMove(ttm),
depth(d),
ply(pl) {
if (pos.checkers())
stage = EVASION_TT + !(ttm && pos.pseudo_legal(ttm));
else
stage = (depth > 0 ? MAIN_TT : QSEARCH_TT) + !(ttm && pos.pseudo_legal(ttm));
}
// MovePicker constructor for ProbCut: we generate captures with Static Exchange
// Evaluation (SEE) greater than or equal to the given threshold.
MovePicker::MovePicker(const Position& p, Move ttm, int th, const CapturePieceToHistory* cph) :
pos(p),
captureHistory(cph),
ttMove(ttm),
threshold(th) {
assert(!pos.checkers());
stage = PROBCUT_TT
+ !(ttm && pos.capture_stage(ttm) && pos.pseudo_legal(ttm) && pos.see_ge(ttm, threshold));
}
// Assigns a numerical value to each move in a list, used for sorting.
// Captures are ordered by Most Valuable Victim (MVV), preferring captures
// with a good history. Quiets moves are ordered using the history tables.
template<GenType Type>
void MovePicker::score() {
static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
[[maybe_unused]] Bitboard threatenedByPawn, threatenedByMinor, threatenedByRook,
threatenedPieces;
if constexpr (Type == QUIETS)
{
Color us = pos.side_to_move();
threatenedByPawn = pos.attacks_by<PAWN>(~us);
threatenedByMinor =
pos.attacks_by<KNIGHT>(~us) | pos.attacks_by<BISHOP>(~us) | threatenedByPawn;
threatenedByRook = pos.attacks_by<ROOK>(~us) | threatenedByMinor;
// Pieces threatened by pieces of lesser material value
threatenedPieces = (pos.pieces(us, QUEEN) & threatenedByRook)
| (pos.pieces(us, ROOK) & threatenedByMinor)
| (pos.pieces(us, KNIGHT, BISHOP) & threatenedByPawn);
}
for (auto& m : *this)
if constexpr (Type == CAPTURES)
m.value =
7 * int(PieceValue[pos.piece_on(m.to_sq())])
+ (*captureHistory)[pos.moved_piece(m)][m.to_sq()][type_of(pos.piece_on(m.to_sq()))];
else if constexpr (Type == QUIETS)
{
Piece pc = pos.moved_piece(m);
PieceType pt = type_of(pc);
Square from = m.from_sq();
Square to = m.to_sq();
// histories
m.value = (*mainHistory)[pos.side_to_move()][m.from_to()];
m.value += 2 * (*pawnHistory)[pawn_structure_index(pos)][pc][to];
m.value += 2 * (*continuationHistory[0])[pc][to];
m.value += (*continuationHistory[1])[pc][to];
m.value += (*continuationHistory[2])[pc][to] / 3;
m.value += (*continuationHistory[3])[pc][to];
m.value += (*continuationHistory[5])[pc][to];
// bonus for checks
m.value += bool(pos.check_squares(pt) & to) * 16384;
// bonus for escaping from capture
m.value += threatenedPieces & from ? (pt == QUEEN && !(to & threatenedByRook) ? 51700
: pt == ROOK && !(to & threatenedByMinor) ? 25600
: !(to & threatenedByPawn) ? 14450
: 0)
: 0;
// malus for putting piece en prise
m.value -= (pt == QUEEN ? bool(to & threatenedByRook) * 49000
: pt == ROOK && bool(to & threatenedByMinor) ? 24335
: 0);
if (ply < LOW_PLY_HISTORY_SIZE)
m.value += 8 * (*lowPlyHistory)[ply][m.from_to()] / (1 + 2 * ply);
}
else // Type == EVASIONS
{
if (pos.capture_stage(m))
m.value =
PieceValue[pos.piece_on(m.to_sq())] - type_of(pos.moved_piece(m)) + (1 << 28);
else
m.value = (*mainHistory)[pos.side_to_move()][m.from_to()]
+ (*continuationHistory[0])[pos.moved_piece(m)][m.to_sq()]
+ (*pawnHistory)[pawn_structure_index(pos)][pos.moved_piece(m)][m.to_sq()];
}
}
// Returns the next move satisfying a predicate function.
// This never returns the TT move, as it was emitted before.
template<MovePicker::PickType T, typename Pred>
Move MovePicker::select(Pred filter) {
while (cur < endMoves)
{
if constexpr (T == Best)
std::swap(*cur, *std::max_element(cur, endMoves));
if (*cur != ttMove && filter())
return *cur++;
cur++;
}
return Move::none();
}
// This is the most important method of the MovePicker class. We emit one
// new pseudo-legal move on every call until there are no more moves left,
// picking the move with the highest score from a list of generated moves.
Move MovePicker::next_move() {
auto quiet_threshold = [](Depth d) { return -3560 * d; };
top:
switch (stage)
{
case MAIN_TT :
case EVASION_TT :
case QSEARCH_TT :
case PROBCUT_TT :
++stage;
return ttMove;
case CAPTURE_INIT :
case PROBCUT_INIT :
case QCAPTURE_INIT :
cur = endBadCaptures = moves;
endMoves = generate<CAPTURES>(pos, cur);
score<CAPTURES>();
partial_insertion_sort(cur, endMoves, std::numeric_limits<int>::min());
++stage;
goto top;
case GOOD_CAPTURE :
if (select<Next>([&]() {
// Move losing capture to endBadCaptures to be tried later
return pos.see_ge(*cur, -cur->value / 18) ? true
: (*endBadCaptures++ = *cur, false);
}))
return *(cur - 1);
++stage;
[[fallthrough]];
case QUIET_INIT :
if (!skipQuiets)
{
cur = endBadCaptures;
endMoves = beginBadQuiets = endBadQuiets = generate<QUIETS>(pos, cur);
score<QUIETS>();
partial_insertion_sort(cur, endMoves, quiet_threshold(depth));
}
++stage;
[[fallthrough]];
case GOOD_QUIET :
if (!skipQuiets && select<Next>([]() { return true; }))
{
if ((cur - 1)->value > -7998 || (cur - 1)->value <= quiet_threshold(depth))
return *(cur - 1);
// Remaining quiets are bad
beginBadQuiets = cur - 1;
}
// Prepare the pointers to loop over the bad captures
cur = moves;
endMoves = endBadCaptures;
++stage;
[[fallthrough]];
case BAD_CAPTURE :
if (select<Next>([]() { return true; }))
return *(cur - 1);
// Prepare the pointers to loop over the bad quiets
cur = beginBadQuiets;
endMoves = endBadQuiets;
++stage;
[[fallthrough]];
case BAD_QUIET :
if (!skipQuiets)
return select<Next>([]() { return true; });
return Move::none();
case EVASION_INIT :
cur = moves;
endMoves = generate<EVASIONS>(pos, cur);
score<EVASIONS>();
++stage;
[[fallthrough]];
case EVASION :
return select<Best>([]() { return true; });
case PROBCUT :
return select<Next>([&]() { return pos.see_ge(*cur, threshold); });
case QCAPTURE :
return select<Next>([]() { return true; });
}
assert(false);
return Move::none(); // Silence warning
}
void MovePicker::skip_quiet_moves() { skipQuiets = true; }
} // namespace Stockfish
| 10,515
|
C++
|
.cpp
| 262
| 30.801527
| 100
| 0.561359
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,024
|
engine.cpp
|
official-stockfish_Stockfish/src/engine.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "engine.h"
#include <cassert>
#include <deque>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <sstream>
#include <string_view>
#include <utility>
#include <vector>
#include "evaluate.h"
#include "misc.h"
#include "nnue/network.h"
#include "nnue/nnue_common.h"
#include "perft.h"
#include "position.h"
#include "search.h"
#include "syzygy/tbprobe.h"
#include "types.h"
#include "uci.h"
#include "ucioption.h"
namespace Stockfish {
namespace NN = Eval::NNUE;
constexpr auto StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
constexpr int MaxHashMB = Is64Bit ? 33554432 : 2048;
Engine::Engine(std::optional<std::string> path) :
binaryDirectory(path ? CommandLine::get_binary_directory(*path) : ""),
numaContext(NumaConfig::from_system()),
states(new std::deque<StateInfo>(1)),
threads(),
networks(
numaContext,
NN::Networks(
NN::NetworkBig({EvalFileDefaultNameBig, "None", ""}, NN::EmbeddedNNUEType::BIG),
NN::NetworkSmall({EvalFileDefaultNameSmall, "None", ""}, NN::EmbeddedNNUEType::SMALL))) {
pos.set(StartFEN, false, &states->back());
capSq = SQ_NONE;
options["Debug Log File"] << Option("", [](const Option& o) {
start_logger(o);
return std::nullopt;
});
options["NumaPolicy"] << Option("auto", [this](const Option& o) {
set_numa_config_from_option(o);
return numa_config_information_as_string() + "\n"
+ thread_allocation_information_as_string();
});
options["Threads"] << Option(1, 1, 1024, [this](const Option&) {
resize_threads();
return thread_allocation_information_as_string();
});
options["Hash"] << Option(16, 1, MaxHashMB, [this](const Option& o) {
set_tt_size(o);
return std::nullopt;
});
options["Clear Hash"] << Option([this](const Option&) {
search_clear();
return std::nullopt;
});
options["Ponder"] << Option(false);
options["MultiPV"] << Option(1, 1, MAX_MOVES);
options["Skill Level"] << Option(20, 0, 20);
options["Move Overhead"] << Option(10, 0, 5000);
options["nodestime"] << Option(0, 0, 10000);
options["UCI_Chess960"] << Option(false);
options["UCI_LimitStrength"] << Option(false);
options["UCI_Elo"] << Option(Stockfish::Search::Skill::LowestElo,
Stockfish::Search::Skill::LowestElo,
Stockfish::Search::Skill::HighestElo);
options["UCI_ShowWDL"] << Option(false);
options["SyzygyPath"] << Option("", [](const Option& o) {
Tablebases::init(o);
return std::nullopt;
});
options["SyzygyProbeDepth"] << Option(1, 1, 100);
options["Syzygy50MoveRule"] << Option(true);
options["SyzygyProbeLimit"] << Option(7, 0, 7);
options["EvalFile"] << Option(EvalFileDefaultNameBig, [this](const Option& o) {
load_big_network(o);
return std::nullopt;
});
options["EvalFileSmall"] << Option(EvalFileDefaultNameSmall, [this](const Option& o) {
load_small_network(o);
return std::nullopt;
});
load_networks();
resize_threads();
}
std::uint64_t Engine::perft(const std::string& fen, Depth depth, bool isChess960) {
verify_networks();
return Benchmark::perft(fen, depth, isChess960);
}
void Engine::go(Search::LimitsType& limits) {
assert(limits.perft == 0);
verify_networks();
limits.capSq = capSq;
threads.start_thinking(options, pos, states, limits);
}
void Engine::stop() { threads.stop = true; }
void Engine::search_clear() {
wait_for_search_finished();
tt.clear(threads);
threads.clear();
// @TODO wont work with multiple instances
Tablebases::init(options["SyzygyPath"]); // Free mapped files
}
void Engine::set_on_update_no_moves(std::function<void(const Engine::InfoShort&)>&& f) {
updateContext.onUpdateNoMoves = std::move(f);
}
void Engine::set_on_update_full(std::function<void(const Engine::InfoFull&)>&& f) {
updateContext.onUpdateFull = std::move(f);
}
void Engine::set_on_iter(std::function<void(const Engine::InfoIter&)>&& f) {
updateContext.onIter = std::move(f);
}
void Engine::set_on_bestmove(std::function<void(std::string_view, std::string_view)>&& f) {
updateContext.onBestmove = std::move(f);
}
void Engine::set_on_verify_networks(std::function<void(std::string_view)>&& f) {
onVerifyNetworks = std::move(f);
}
void Engine::wait_for_search_finished() { threads.main_thread()->wait_for_search_finished(); }
void Engine::set_position(const std::string& fen, const std::vector<std::string>& moves) {
// Drop the old state and create a new one
states = StateListPtr(new std::deque<StateInfo>(1));
pos.set(fen, options["UCI_Chess960"], &states->back());
capSq = SQ_NONE;
for (const auto& move : moves)
{
auto m = UCIEngine::to_move(pos, move);
if (m == Move::none())
break;
states->emplace_back();
pos.do_move(m, states->back());
capSq = SQ_NONE;
DirtyPiece& dp = states->back().dirtyPiece;
if (dp.dirty_num > 1 && dp.to[1] == SQ_NONE)
capSq = m.to_sq();
}
}
// modifiers
void Engine::set_numa_config_from_option(const std::string& o) {
if (o == "auto" || o == "system")
{
numaContext.set_numa_config(NumaConfig::from_system());
}
else if (o == "hardware")
{
// Don't respect affinity set in the system.
numaContext.set_numa_config(NumaConfig::from_system(false));
}
else if (o == "none")
{
numaContext.set_numa_config(NumaConfig{});
}
else
{
numaContext.set_numa_config(NumaConfig::from_string(o));
}
// Force reallocation of threads in case affinities need to change.
resize_threads();
threads.ensure_network_replicated();
}
void Engine::resize_threads() {
threads.wait_for_search_finished();
threads.set(numaContext.get_numa_config(), {options, threads, tt, networks}, updateContext);
// Reallocate the hash with the new threadpool size
set_tt_size(options["Hash"]);
threads.ensure_network_replicated();
}
void Engine::set_tt_size(size_t mb) {
wait_for_search_finished();
tt.resize(mb, threads);
}
void Engine::set_ponderhit(bool b) { threads.main_manager()->ponder = b; }
// network related
void Engine::verify_networks() const {
networks->big.verify(options["EvalFile"], onVerifyNetworks);
networks->small.verify(options["EvalFileSmall"], onVerifyNetworks);
}
void Engine::load_networks() {
networks.modify_and_replicate([this](NN::Networks& networks_) {
networks_.big.load(binaryDirectory, options["EvalFile"]);
networks_.small.load(binaryDirectory, options["EvalFileSmall"]);
});
threads.clear();
threads.ensure_network_replicated();
}
void Engine::load_big_network(const std::string& file) {
networks.modify_and_replicate(
[this, &file](NN::Networks& networks_) { networks_.big.load(binaryDirectory, file); });
threads.clear();
threads.ensure_network_replicated();
}
void Engine::load_small_network(const std::string& file) {
networks.modify_and_replicate(
[this, &file](NN::Networks& networks_) { networks_.small.load(binaryDirectory, file); });
threads.clear();
threads.ensure_network_replicated();
}
void Engine::save_network(const std::pair<std::optional<std::string>, std::string> files[2]) {
networks.modify_and_replicate([&files](NN::Networks& networks_) {
networks_.big.save(files[0].first);
networks_.small.save(files[1].first);
});
}
// utility functions
void Engine::trace_eval() const {
StateListPtr trace_states(new std::deque<StateInfo>(1));
Position p;
p.set(pos.fen(), options["UCI_Chess960"], &trace_states->back());
verify_networks();
sync_cout << "\n" << Eval::trace(p, *networks) << sync_endl;
}
const OptionsMap& Engine::get_options() const { return options; }
OptionsMap& Engine::get_options() { return options; }
std::string Engine::fen() const { return pos.fen(); }
void Engine::flip() { pos.flip(); }
std::string Engine::visualize() const {
std::stringstream ss;
ss << pos;
return ss.str();
}
int Engine::get_hashfull(int maxAge) const { return tt.hashfull(maxAge); }
std::vector<std::pair<size_t, size_t>> Engine::get_bound_thread_count_by_numa_node() const {
auto counts = threads.get_bound_thread_count_by_numa_node();
const NumaConfig& cfg = numaContext.get_numa_config();
std::vector<std::pair<size_t, size_t>> ratios;
NumaIndex n = 0;
for (; n < counts.size(); ++n)
ratios.emplace_back(counts[n], cfg.num_cpus_in_numa_node(n));
if (!counts.empty())
for (; n < cfg.num_numa_nodes(); ++n)
ratios.emplace_back(0, cfg.num_cpus_in_numa_node(n));
return ratios;
}
std::string Engine::get_numa_config_as_string() const {
return numaContext.get_numa_config().to_string();
}
std::string Engine::numa_config_information_as_string() const {
auto cfgStr = get_numa_config_as_string();
return "Available processors: " + cfgStr;
}
std::string Engine::thread_binding_information_as_string() const {
auto boundThreadsByNode = get_bound_thread_count_by_numa_node();
std::stringstream ss;
if (boundThreadsByNode.empty())
return ss.str();
bool isFirst = true;
for (auto&& [current, total] : boundThreadsByNode)
{
if (!isFirst)
ss << ":";
ss << current << "/" << total;
isFirst = false;
}
return ss.str();
}
std::string Engine::thread_allocation_information_as_string() const {
std::stringstream ss;
size_t threadsSize = threads.size();
ss << "Using " << threadsSize << (threadsSize > 1 ? " threads" : " thread");
auto boundThreadsByNodeStr = thread_binding_information_as_string();
if (boundThreadsByNodeStr.empty())
return ss.str();
ss << " with NUMA node thread binding: ";
ss << boundThreadsByNodeStr;
return ss.str();
}
}
| 10,974
|
C++
|
.cpp
| 283
| 33.918728
| 98
| 0.656374
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,025
|
timeman.cpp
|
official-stockfish_Stockfish/src/timeman.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "timeman.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include "search.h"
#include "ucioption.h"
namespace Stockfish {
TimePoint TimeManagement::optimum() const { return optimumTime; }
TimePoint TimeManagement::maximum() const { return maximumTime; }
void TimeManagement::clear() {
availableNodes = -1; // When in 'nodes as time' mode
}
void TimeManagement::advance_nodes_time(std::int64_t nodes) {
assert(useNodesTime);
availableNodes = std::max(int64_t(0), availableNodes - nodes);
}
// Called at the beginning of the search and calculates
// the bounds of time allowed for the current game ply. We currently support:
// 1) x basetime (+ z increment)
// 2) x moves in y seconds (+ z increment)
void TimeManagement::init(Search::LimitsType& limits,
Color us,
int ply,
const OptionsMap& options,
double& originalTimeAdjust) {
TimePoint npmsec = TimePoint(options["nodestime"]);
// If we have no time, we don't need to fully initialize TM.
// startTime is used by movetime and useNodesTime is used in elapsed calls.
startTime = limits.startTime;
useNodesTime = npmsec != 0;
if (limits.time[us] == 0)
return;
TimePoint moveOverhead = TimePoint(options["Move Overhead"]);
// optScale is a percentage of available time to use for the current move.
// maxScale is a multiplier applied to optimumTime.
double optScale, maxScale;
// If we have to play in 'nodes as time' mode, then convert from time
// to nodes, and use resulting values in time management formulas.
// WARNING: to avoid time losses, the given npmsec (nodes per millisecond)
// must be much lower than the real engine speed.
if (useNodesTime)
{
if (availableNodes == -1) // Only once at game start
availableNodes = npmsec * limits.time[us]; // Time is in msec
// Convert from milliseconds to nodes
limits.time[us] = TimePoint(availableNodes);
limits.inc[us] *= npmsec;
limits.npmsec = npmsec;
moveOverhead *= npmsec;
}
// These numbers are used where multiplications, divisions or comparisons
// with constants are involved.
const int64_t scaleFactor = useNodesTime ? npmsec : 1;
const TimePoint scaledTime = limits.time[us] / scaleFactor;
const TimePoint scaledInc = limits.inc[us] / scaleFactor;
// Maximum move horizon of 50 moves
int mtg = limits.movestogo ? std::min(limits.movestogo, 50) : 50;
// If less than one second, gradually reduce mtg
if (scaledTime < 1000 && double(mtg) / scaledInc > 0.05)
{
mtg = scaledTime * 0.05;
}
// Make sure timeLeft is > 0 since we may use it as a divisor
TimePoint timeLeft = std::max(TimePoint(1), limits.time[us] + limits.inc[us] * (mtg - 1)
- moveOverhead * (2 + mtg));
// x basetime (+ z increment)
// If there is a healthy increment, timeLeft can exceed the actual available
// game time for the current move, so also cap to a percentage of available game time.
if (limits.movestogo == 0)
{
// Extra time according to timeLeft
if (originalTimeAdjust < 0)
originalTimeAdjust = 0.3285 * std::log10(timeLeft) - 0.4830;
// Calculate time constants based on current time left.
double logTimeInSec = std::log10(scaledTime / 1000.0);
double optConstant = std::min(0.00308 + 0.000319 * logTimeInSec, 0.00506);
double maxConstant = std::max(3.39 + 3.01 * logTimeInSec, 2.93);
optScale = std::min(0.0122 + std::pow(ply + 2.95, 0.462) * optConstant,
0.213 * limits.time[us] / timeLeft)
* originalTimeAdjust;
maxScale = std::min(6.64, maxConstant + ply / 12.0);
}
// x moves in y seconds (+ z increment)
else
{
optScale = std::min((0.88 + ply / 116.4) / mtg, 0.88 * limits.time[us] / timeLeft);
maxScale = std::min(6.3, 1.5 + 0.11 * mtg);
}
// Limit the maximum possible time for this move
optimumTime = TimePoint(optScale * timeLeft);
maximumTime =
TimePoint(std::min(0.825 * limits.time[us] - moveOverhead, maxScale * optimumTime)) - 10;
if (options["Ponder"])
optimumTime += optimumTime / 4;
}
} // namespace Stockfish
| 5,313
|
C++
|
.cpp
| 111
| 41.261261
| 95
| 0.656099
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,026
|
score.cpp
|
official-stockfish_Stockfish/src/score.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "score.h"
#include <cassert>
#include <cmath>
#include <cstdlib>
#include "uci.h"
namespace Stockfish {
Score::Score(Value v, const Position& pos) {
assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
if (std::abs(v) < VALUE_TB_WIN_IN_MAX_PLY)
{
score = InternalUnits{UCIEngine::to_cp(v, pos)};
}
else if (std::abs(v) <= VALUE_TB)
{
auto distance = VALUE_TB - std::abs(v);
score = (v > 0) ? Tablebase{distance, true} : Tablebase{-distance, false};
}
else
{
auto distance = VALUE_MATE - std::abs(v);
score = (v > 0) ? Mate{distance} : Mate{-distance};
}
}
}
| 1,436
|
C++
|
.cpp
| 38
| 33.815789
| 90
| 0.688985
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,027
|
evaluate.cpp
|
official-stockfish_Stockfish/src/evaluate.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "evaluate.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <tuple>
#include "nnue/network.h"
#include "nnue/nnue_misc.h"
#include "position.h"
#include "types.h"
#include "uci.h"
#include "nnue/nnue_accumulator.h"
namespace Stockfish {
// Returns a static, purely materialistic evaluation of the position from
// the point of view of the given color. It can be divided by PawnValue to get
// an approximation of the material advantage on the board in terms of pawns.
int Eval::simple_eval(const Position& pos, Color c) {
return PawnValue * (pos.count<PAWN>(c) - pos.count<PAWN>(~c))
+ (pos.non_pawn_material(c) - pos.non_pawn_material(~c));
}
bool Eval::use_smallnet(const Position& pos) {
int simpleEval = simple_eval(pos, pos.side_to_move());
return std::abs(simpleEval) > 962;
}
// Evaluate is the evaluator for the outer world. It returns a static evaluation
// of the position from the point of view of the side to move.
Value Eval::evaluate(const Eval::NNUE::Networks& networks,
const Position& pos,
Eval::NNUE::AccumulatorCaches& caches,
int optimism) {
assert(!pos.checkers());
bool smallNet = use_smallnet(pos);
auto [psqt, positional] = smallNet ? networks.small.evaluate(pos, &caches.small)
: networks.big.evaluate(pos, &caches.big);
Value nnue = (125 * psqt + 131 * positional) / 128;
// Re-evaluate the position when higher eval accuracy is worth the time spent
if (smallNet && (std::abs(nnue) < 236))
{
std::tie(psqt, positional) = networks.big.evaluate(pos, &caches.big);
nnue = (125 * psqt + 131 * positional) / 128;
smallNet = false;
}
// Blend optimism and eval with nnue complexity
int nnueComplexity = std::abs(psqt - positional);
optimism += optimism * nnueComplexity / 468;
nnue -= nnue * nnueComplexity / (smallNet ? 20233 : 17879);
int material = (smallNet ? 553 : 532) * pos.count<PAWN>() + pos.non_pawn_material();
int v = (nnue * (77777 + material) + optimism * (7777 + material)) / 77777;
// Damp down the evaluation linearly when shuffling
v -= v * pos.rule50_count() / 212;
// Guarantee evaluation does not hit the tablebase range
v = std::clamp(v, VALUE_TB_LOSS_IN_MAX_PLY + 1, VALUE_TB_WIN_IN_MAX_PLY - 1);
return v;
}
// Like evaluate(), but instead of returning a value, it returns
// a string (suitable for outputting to stdout) that contains the detailed
// descriptions and values of each evaluation term. Useful for debugging.
// Trace scores are from white's point of view
std::string Eval::trace(Position& pos, const Eval::NNUE::Networks& networks) {
if (pos.checkers())
return "Final evaluation: none (in check)";
auto caches = std::make_unique<Eval::NNUE::AccumulatorCaches>(networks);
std::stringstream ss;
ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2);
ss << '\n' << NNUE::trace(pos, networks, *caches) << '\n';
ss << std::showpoint << std::showpos << std::fixed << std::setprecision(2) << std::setw(15);
auto [psqt, positional] = networks.big.evaluate(pos, &caches->big);
Value v = psqt + positional;
v = pos.side_to_move() == WHITE ? v : -v;
ss << "NNUE evaluation " << 0.01 * UCIEngine::to_cp(v, pos) << " (white side)\n";
v = evaluate(networks, pos, *caches, VALUE_ZERO);
v = pos.side_to_move() == WHITE ? v : -v;
ss << "Final evaluation " << 0.01 * UCIEngine::to_cp(v, pos) << " (white side)";
ss << " [with scaled NNUE, ...]";
ss << "\n";
return ss.str();
}
} // namespace Stockfish
| 4,731
|
C++
|
.cpp
| 96
| 44.666667
| 96
| 0.65509
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,028
|
tt.cpp
|
official-stockfish_Stockfish/src/tt.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tt.h"
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "memory.h"
#include "misc.h"
#include "syzygy/tbprobe.h"
#include "thread.h"
namespace Stockfish {
// TTEntry struct is the 10 bytes transposition table entry, defined as below:
//
// key 16 bit
// depth 8 bit
// generation 5 bit
// pv node 1 bit
// bound type 2 bit
// move 16 bit
// value 16 bit
// evaluation 16 bit
//
// These fields are in the same order as accessed by TT::probe(), since memory is fastest sequentially.
// Equally, the store order in save() matches this order.
struct TTEntry {
// Convert internal bitfields to external types
TTData read() const {
return TTData{Move(move16), Value(value16),
Value(eval16), Depth(depth8 + DEPTH_ENTRY_OFFSET),
Bound(genBound8 & 0x3), bool(genBound8 & 0x4)};
}
bool is_occupied() const;
void save(Key k, Value v, bool pv, Bound b, Depth d, Move m, Value ev, uint8_t generation8);
// The returned age is a multiple of TranspositionTable::GENERATION_DELTA
uint8_t relative_age(const uint8_t generation8) const;
private:
friend class TranspositionTable;
uint16_t key16;
uint8_t depth8;
uint8_t genBound8;
Move move16;
int16_t value16;
int16_t eval16;
};
// `genBound8` is where most of the details are. We use the following constants to manipulate 5 leading generation bits
// and 3 trailing miscellaneous bits.
// These bits are reserved for other things.
static constexpr unsigned GENERATION_BITS = 3;
// increment for generation field
static constexpr int GENERATION_DELTA = (1 << GENERATION_BITS);
// cycle length
static constexpr int GENERATION_CYCLE = 255 + GENERATION_DELTA;
// mask to pull out generation number
static constexpr int GENERATION_MASK = (0xFF << GENERATION_BITS) & 0xFF;
// DEPTH_ENTRY_OFFSET exists because 1) we use `bool(depth8)` as the occupancy check, but
// 2) we need to store negative depths for QS. (`depth8` is the only field with "spare bits":
// we sacrifice the ability to store depths greater than 1<<8 less the offset, as asserted in `save`.)
bool TTEntry::is_occupied() const { return bool(depth8); }
// Populates the TTEntry with a new node's data, possibly
// overwriting an old position. The update is not atomic and can be racy.
void TTEntry::save(
Key k, Value v, bool pv, Bound b, Depth d, Move m, Value ev, uint8_t generation8) {
// Preserve the old ttmove if we don't have a new one
if (m || uint16_t(k) != key16)
move16 = m;
// Overwrite less valuable entries (cheapest checks first)
if (b == BOUND_EXACT || uint16_t(k) != key16 || d - DEPTH_ENTRY_OFFSET + 2 * pv > depth8 - 4
|| relative_age(generation8))
{
assert(d > DEPTH_ENTRY_OFFSET);
assert(d < 256 + DEPTH_ENTRY_OFFSET);
key16 = uint16_t(k);
depth8 = uint8_t(d - DEPTH_ENTRY_OFFSET);
genBound8 = uint8_t(generation8 | uint8_t(pv) << 2 | b);
value16 = int16_t(v);
eval16 = int16_t(ev);
}
}
uint8_t TTEntry::relative_age(const uint8_t generation8) const {
// Due to our packed storage format for generation and its cyclic
// nature we add GENERATION_CYCLE (256 is the modulus, plus what
// is needed to keep the unrelated lowest n bits from affecting
// the result) to calculate the entry age correctly even after
// generation8 overflows into the next cycle.
return (GENERATION_CYCLE + generation8 - genBound8) & GENERATION_MASK;
}
// TTWriter is but a very thin wrapper around the pointer
TTWriter::TTWriter(TTEntry* tte) :
entry(tte) {}
void TTWriter::write(
Key k, Value v, bool pv, Bound b, Depth d, Move m, Value ev, uint8_t generation8) {
entry->save(k, v, pv, b, d, m, ev, generation8);
}
// A TranspositionTable is an array of Cluster, of size clusterCount. Each cluster consists of ClusterSize number
// of TTEntry. Each non-empty TTEntry contains information on exactly one position. The size of a Cluster should
// divide the size of a cache line for best performance, as the cacheline is prefetched when possible.
static constexpr int ClusterSize = 3;
struct Cluster {
TTEntry entry[ClusterSize];
char padding[2]; // Pad to 32 bytes
};
static_assert(sizeof(Cluster) == 32, "Suboptimal Cluster size");
// Sets the size of the transposition table,
// measured in megabytes. Transposition table consists
// of clusters and each cluster consists of ClusterSize number of TTEntry.
void TranspositionTable::resize(size_t mbSize, ThreadPool& threads) {
aligned_large_pages_free(table);
clusterCount = mbSize * 1024 * 1024 / sizeof(Cluster);
table = static_cast<Cluster*>(aligned_large_pages_alloc(clusterCount * sizeof(Cluster)));
if (!table)
{
std::cerr << "Failed to allocate " << mbSize << "MB for transposition table." << std::endl;
exit(EXIT_FAILURE);
}
clear(threads);
}
// Initializes the entire transposition table to zero,
// in a multi-threaded way.
void TranspositionTable::clear(ThreadPool& threads) {
generation8 = 0;
const size_t threadCount = threads.num_threads();
for (size_t i = 0; i < threadCount; ++i)
{
threads.run_on_thread(i, [this, i, threadCount]() {
// Each thread will zero its part of the hash table
const size_t stride = clusterCount / threadCount;
const size_t start = stride * i;
const size_t len = i + 1 != threadCount ? stride : clusterCount - start;
std::memset(&table[start], 0, len * sizeof(Cluster));
});
}
for (size_t i = 0; i < threadCount; ++i)
threads.wait_on_thread(i);
}
// Returns an approximation of the hashtable
// occupation during a search. The hash is x permill full, as per UCI protocol.
// Only counts entries which match the current generation.
int TranspositionTable::hashfull(int maxAge) const {
int maxAgeInternal = maxAge << GENERATION_BITS;
int cnt = 0;
for (int i = 0; i < 1000; ++i)
for (int j = 0; j < ClusterSize; ++j)
cnt += table[i].entry[j].is_occupied()
&& table[i].entry[j].relative_age(generation8) <= maxAgeInternal;
return cnt / ClusterSize;
}
void TranspositionTable::new_search() {
// increment by delta to keep lower bits as is
generation8 += GENERATION_DELTA;
}
uint8_t TranspositionTable::generation() const { return generation8; }
// Looks up the current position in the transposition
// table. It returns true if the position is found.
// Otherwise, it returns false and a pointer to an empty or least valuable TTEntry
// to be replaced later. The replace value of an entry is calculated as its depth
// minus 8 times its relative age. TTEntry t1 is considered more valuable than
// TTEntry t2 if its replace value is greater than that of t2.
std::tuple<bool, TTData, TTWriter> TranspositionTable::probe(const Key key) const {
TTEntry* const tte = first_entry(key);
const uint16_t key16 = uint16_t(key); // Use the low 16 bits as key inside the cluster
for (int i = 0; i < ClusterSize; ++i)
if (tte[i].key16 == key16)
// This gap is the main place for read races.
// After `read()` completes that copy is final, but may be self-inconsistent.
return {tte[i].is_occupied(), tte[i].read(), TTWriter(&tte[i])};
// Find an entry to be replaced according to the replacement strategy
TTEntry* replace = tte;
for (int i = 1; i < ClusterSize; ++i)
if (replace->depth8 - replace->relative_age(generation8) * 2
> tte[i].depth8 - tte[i].relative_age(generation8) * 2)
replace = &tte[i];
return {false, TTData(), TTWriter(replace)};
}
TTEntry* TranspositionTable::first_entry(const Key key) const {
return &table[mul_hi64(key, clusterCount)].entry[0];
}
} // namespace Stockfish
| 8,825
|
C++
|
.cpp
| 191
| 41.78534
| 119
| 0.691698
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,029
|
main.cpp
|
official-stockfish_Stockfish/src/main.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "bitboard.h"
#include "misc.h"
#include "position.h"
#include "types.h"
#include "uci.h"
#include "tune.h"
using namespace Stockfish;
int main(int argc, char* argv[]) {
std::cout << engine_info() << std::endl;
Bitboards::init();
Position::init();
UCIEngine uci(argc, argv);
Tune::init(uci.engine_options());
uci.loop();
return 0;
}
| 1,168
|
C++
|
.cpp
| 31
| 34.580645
| 71
| 0.742883
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,030
|
benchmark.cpp
|
official-stockfish_Stockfish/src/benchmark.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "benchmark.h"
#include "numa.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <vector>
namespace {
// clang-format off
const std::vector<std::string> Defaults = {
"setoption name UCI_Chess960 value false",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10",
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11",
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14 moves d4e6",
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14 moves g2g4",
"r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15",
"r1bbk1nr/pp3p1p/2n5/1N4p1/2Np1B2/8/PPP2PPP/2KR1B1R w kq - 0 13",
"r1bq1rk1/ppp1nppp/4n3/3p3Q/3P4/1BP1B3/PP1N2PP/R4RK1 w - - 1 16",
"4r1k1/r1q2ppp/ppp2n2/4P3/5Rb1/1N1BQ3/PPP3PP/R5K1 w - - 1 17",
"2rqkb1r/ppp2p2/2npb1p1/1N1Nn2p/2P1PP2/8/PP2B1PP/R1BQK2R b KQ - 0 11",
"r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16",
"3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22",
"r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18",
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22",
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26",
"6k1/6p1/6Pp/ppp5/3pn2P/1P3K2/1PP2P2/3N4 b - - 0 1",
"3b4/5kp1/1p1p1p1p/pP1PpP1P/P1P1P3/3KN3/8/8 w - - 0 1",
"2K5/p7/7P/5pR1/8/5k2/r7/8 w - - 0 1 moves g5g6 f3e3 g6g5 e3f3",
"8/6pk/1p6/8/PP3p1p/5P2/4KP1q/3Q4 w - - 0 1",
"7k/3p2pp/4q3/8/4Q3/5Kp1/P6b/8 w - - 0 1",
"8/2p5/8/2kPKp1p/2p4P/2P5/3P4/8 w - - 0 1",
"8/1p3pp1/7p/5P1P/2k3P1/8/2K2P2/8 w - - 0 1",
"8/pp2r1k1/2p1p3/3pP2p/1P1P1P1P/P5KR/8/8 w - - 0 1",
"8/3p4/p1bk3p/Pp6/1Kp1PpPp/2P2P1P/2P5/5B2 b - - 0 1",
"5k2/7R/4P2p/5K2/p1r2P1p/8/8/8 b - - 0 1",
"6k1/6p1/P6p/r1N5/5p2/7P/1b3PP1/4R1K1 w - - 0 1",
"1r3k2/4q3/2Pp3b/3Bp3/2Q2p2/1p1P2P1/1P2KP2/3N4 w - - 0 1",
"6k1/4pp1p/3p2p1/P1pPb3/R7/1r2P1PP/3B1P2/6K1 w - - 0 1",
"8/3p3B/5p2/5P2/p7/PP5b/k7/6K1 w - - 0 1",
"5rk1/q6p/2p3bR/1pPp1rP1/1P1Pp3/P3B1Q1/1K3P2/R7 w - - 93 90",
"4rrk1/1p1nq3/p7/2p1P1pp/3P2bp/3Q1Bn1/PPPB4/1K2R1NR w - - 40 21",
"r3k2r/3nnpbp/q2pp1p1/p7/Pp1PPPP1/4BNN1/1P5P/R2Q1RK1 w kq - 0 16",
"3Qb1k1/1r2ppb1/pN1n2q1/Pp1Pp1Pr/4P2p/4BP2/4B1R1/1R5K b - - 11 40",
"4k3/3q1r2/1N2r1b1/3ppN2/2nPP3/1B1R2n1/2R1Q3/3K4 w - - 5 1",
// 5-man positions
"8/8/8/8/5kp1/P7/8/1K1N4 w - - 0 1", // Kc2 - mate
"8/8/8/5N2/8/p7/8/2NK3k w - - 0 1", // Na2 - mate
"8/3k4/8/8/8/4B3/4KB2/2B5 w - - 0 1", // draw
// 6-man positions
"8/8/1P6/5pr1/8/4R3/7k/2K5 w - - 0 1", // Re5 - mate
"8/2p4P/8/kr6/6R1/8/8/1K6 w - - 0 1", // Ka2 - mate
"8/8/3P3k/8/1p6/8/1P6/1K3n2 b - - 0 1", // Nd2 - draw
// 7-man positions
"8/R7/2q5/8/6k1/8/1P5p/K6R w - - 0 124", // Draw
// Mate and stalemate positions
"6k1/3b3r/1p1p4/p1n2p2/1PPNpP1q/P3Q1p1/1R1RB1P1/5K2 b - - 0 1",
"r2r1n2/pp2bk2/2p1p2p/3q4/3PN1QP/2P3R1/P4PP1/5RK1 w - - 0 1",
"8/8/8/8/8/6k1/6p1/6K1 w - -",
"7k/7P/6K1/8/3B4/8/8/8 b - -",
// Chess 960
"setoption name UCI_Chess960 value true",
"bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR w HFhf - 0 1 moves g2g3 d7d5 d2d4 c8h3 c1g5 e8d6 g5e7 f7f6",
"nqbnrkrb/pppppppp/8/8/8/8/PPPPPPPP/NQBNRKRB w KQkq - 0 1",
"setoption name UCI_Chess960 value false"
};
// clang-format on
// clang-format off
// human-randomly picked 5 games with <60 moves from
// https://tests.stockfishchess.org/tests/view/665c71f9fd45fb0f907c21e0
// only moves for one side
const std::vector<std::vector<std::string>> BenchmarkPositions = {
{
"rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8",
"rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9",
"r1bq1k1r/pp2bppp/2n1pn2/2p5/2B1NB2/3P1N2/PPP2PPP/R2QR1K1 b - - 3 10",
"r1bq1k1r/pp2bppp/2n1p3/2p5/2B1PB2/5N2/PPP2PPP/R2QR1K1 b - - 0 11",
"r1b2k1r/pp2bppp/2n1p3/2p5/2B1PB2/5N2/PPP2PPP/3RR1K1 b - - 0 12",
"r1b1k2r/pp2bppp/2n1p3/2p5/2B1PB2/2P2N2/PP3PPP/3RR1K1 b - - 0 13",
"r1b1k2r/1p2bppp/p1n1p3/2p5/4PB2/2P2N2/PP2BPPP/3RR1K1 b - - 1 14",
"r1b1k2r/4bppp/p1n1p3/1pp5/P3PB2/2P2N2/1P2BPPP/3RR1K1 b - - 0 15",
"r1b1k2r/4bppp/p1n1p3/1P6/2p1PB2/2P2N2/1P2BPPP/3RR1K1 b - - 0 16",
"r1b1k2r/4bppp/2n1p3/1p6/2p1PB2/1PP2N2/4BPPP/3RR1K1 b - - 0 17",
"r3k2r/3bbppp/2n1p3/1p6/2P1PB2/2P2N2/4BPPP/3RR1K1 b - - 0 18",
"r3k2r/3bbppp/2n1p3/8/1pP1P3/2P2N2/3BBPPP/3RR1K1 b - - 1 19",
"1r2k2r/3bbppp/2n1p3/8/1pPNP3/2P5/3BBPPP/3RR1K1 b - - 3 20",
"1r2k2r/3bbppp/2n1p3/8/2PNP3/2B5/4BPPP/3RR1K1 b - - 0 21",
"1r2k2r/3bb1pp/2n1pp2/1N6/2P1P3/2B5/4BPPP/3RR1K1 b - - 1 22",
"1r2k2r/3b2pp/2n1pp2/1N6/1BP1P3/8/4BPPP/3RR1K1 b - - 0 23",
"1r2k2r/3b2pp/4pp2/1N6/1nP1P3/8/3RBPPP/4R1K1 b - - 1 24",
"1r5r/3bk1pp/4pp2/1N6/1nP1PP2/8/3RB1PP/4R1K1 b - - 0 25",
"1r5r/3bk1pp/2n1pp2/1N6/2P1PP2/8/3RBKPP/4R3 b - - 2 26",
"1r5r/3bk1pp/2n2p2/1N2p3/2P1PP2/6P1/3RBK1P/4R3 b - - 0 27",
"1r1r4/3bk1pp/2n2p2/1N2p3/2P1PP2/6P1/3RBK1P/R7 b - - 2 28",
"1r1r4/N3k1pp/2n1bp2/4p3/2P1PP2/6P1/3RBK1P/R7 b - - 4 29",
"1r1r4/3bk1pp/2N2p2/4p3/2P1PP2/6P1/3RBK1P/R7 b - - 0 30",
"1r1R4/4k1pp/2b2p2/4p3/2P1PP2/6P1/4BK1P/R7 b - - 0 31",
"3r4/4k1pp/2b2p2/4P3/2P1P3/6P1/4BK1P/R7 b - - 0 32",
"3r4/R3k1pp/2b5/4p3/2P1P3/6P1/4BK1P/8 b - - 1 33",
"8/3rk1pp/2b5/R3p3/2P1P3/6P1/4BK1P/8 b - - 3 34",
"8/3r2pp/2bk4/R1P1p3/4P3/6P1/4BK1P/8 b - - 0 35",
"8/2kr2pp/2b5/R1P1p3/4P3/4K1P1/4B2P/8 b - - 2 36",
"1k6/3r2pp/2b5/RBP1p3/4P3/4K1P1/7P/8 b - - 4 37",
"8/1k1r2pp/2b5/R1P1p3/4P3/3BK1P1/7P/8 b - - 6 38",
"1k6/3r2pp/2b5/2P1p3/4P3/3BK1P1/7P/R7 b - - 8 39",
"1k6/r5pp/2b5/2P1p3/4P3/3BK1P1/7P/5R2 b - - 10 40",
"1k3R2/6pp/2b5/2P1p3/4P3/r2BK1P1/7P/8 b - - 12 41",
"5R2/2k3pp/2b5/2P1p3/4P3/r2B2P1/3K3P/8 b - - 14 42",
"5R2/2k3pp/2b5/2P1p3/4P3/3BK1P1/r6P/8 b - - 16 43",
"5R2/2k3pp/2b5/2P1p3/4P3/r2B2P1/4K2P/8 b - - 18 44",
"5R2/2k3pp/2b5/2P1p3/4P3/3B1KP1/r6P/8 b - - 20 45",
"8/2k2Rpp/2b5/2P1p3/4P3/r2B1KP1/7P/8 b - - 22 46",
"3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/4K2P/8 b - - 24 47",
"3k4/5Rpp/2b5/2P1p3/4P3/3B1KP1/r6P/8 b - - 26 48",
"3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/4K2P/8 b - - 28 49",
"3k4/5Rpp/2b5/2P1p3/4P3/3BK1P1/r6P/8 b - - 30 50",
"3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/3K3P/8 b - - 32 51",
"3k4/5Rpp/2b5/2P1p3/4P3/2KB2P1/r6P/8 b - - 34 52",
"3k4/5Rpp/2b5/2P1p3/4P3/r2B2P1/2K4P/8 b - - 36 53",
"3k4/5Rpp/2b5/2P1p3/4P3/1K1B2P1/r6P/8 b - - 38 54",
"3k4/6Rp/2b5/2P1p3/4P3/1K1B2P1/7r/8 b - - 0 55",
"3k4/8/2b3Rp/2P1p3/4P3/1K1B2P1/7r/8 b - - 1 56",
"8/2k3R1/2b4p/2P1p3/4P3/1K1B2P1/7r/8 b - - 3 57",
"3k4/8/2b3Rp/2P1p3/4P3/1K1B2P1/7r/8 b - - 5 58",
"8/2k5/2b3Rp/2P1p3/1K2P3/3B2P1/7r/8 b - - 7 59",
"8/2k5/2b3Rp/2P1p3/4P3/2KB2P1/3r4/8 b - - 9 60",
"8/2k5/2b3Rp/2P1p3/1K2P3/3B2P1/6r1/8 b - - 11 61",
"8/2k5/2b3Rp/2P1p3/4P3/2KB2P1/3r4/8 b - - 13 62",
"8/2k5/2b3Rp/2P1p3/2K1P3/3B2P1/6r1/8 b - - 15 63",
"4b3/2k3R1/7p/2P1p3/2K1P3/3B2P1/6r1/8 b - - 17 64",
},
{
"r1bqkbnr/npp1pppp/p7/3P4/4pB2/2N5/PPP2PPP/R2QKBNR w KQkq - 1 6",
"r1bqkb1r/npp1pppp/p4n2/3P4/4pB2/2N5/PPP1QPPP/R3KBNR w KQkq - 3 7",
"r2qkb1r/npp1pppp/p4n2/3P1b2/4pB2/2N5/PPP1QPPP/2KR1BNR w kq - 5 8",
"r2qkb1r/1pp1pppp/p4n2/1n1P1b2/4pB2/2N4P/PPP1QPP1/2KR1BNR w kq - 1 9",
"r2qkb1r/1pp1pppp/5n2/1p1P1b2/4pB2/7P/PPP1QPP1/2KR1BNR w kq - 0 10",
"r2qkb1r/1ppbpppp/5n2/1Q1P4/4pB2/7P/PPP2PP1/2KR1BNR w kq - 1 11",
"3qkb1r/1Qpbpppp/5n2/3P4/4pB2/7P/rPP2PP1/2KR1BNR w k - 0 12",
"q3kb1r/1Qpbpppp/5n2/3P4/4pB2/7P/rPP2PP1/1K1R1BNR w k - 2 13",
"r3kb1r/2pbpppp/5n2/3P4/4pB2/7P/1PP2PP1/1K1R1BNR w k - 0 14",
"r3kb1r/2Bb1ppp/4pn2/3P4/4p3/7P/1PP2PP1/1K1R1BNR w k - 0 15",
"r3kb1r/2Bb2pp/4pn2/8/4p3/7P/1PP2PP1/1K1R1BNR w k - 0 16",
"r3k2r/2Bb2pp/4pn2/2b5/4p3/7P/1PP1NPP1/1K1R1B1R w k - 2 17",
"r6r/2Bbk1pp/4pn2/2b5/3Np3/7P/1PP2PP1/1K1R1B1R w - - 4 18",
"r6r/b2bk1pp/4pn2/4B3/3Np3/7P/1PP2PP1/1K1R1B1R w - - 6 19",
"r1r5/b2bk1pp/4pn2/4B3/2BNp3/7P/1PP2PP1/1K1R3R w - - 8 20",
"r7/b2bk1pp/4pn2/2r1B3/2BNp3/1P5P/2P2PP1/1K1R3R w - - 1 21",
"rb6/3bk1pp/4pn2/2r1B3/2BNpP2/1P5P/2P3P1/1K1R3R w - - 1 22",
"1r6/3bk1pp/4pn2/2r5/2BNpP2/1P5P/2P3P1/1K1R3R w - - 0 23",
"1r6/3bk1p1/4pn1p/2r5/2BNpP2/1P5P/2P3P1/2KR3R w - - 0 24",
"8/3bk1p1/1r2pn1p/2r5/2BNpP1P/1P6/2P3P1/2KR3R w - - 1 25",
"8/3bk3/1r2pnpp/2r5/2BNpP1P/1P6/2P3P1/2K1R2R w - - 0 26",
"2b5/4k3/1r2pnpp/2r5/2BNpP1P/1P4P1/2P5/2K1R2R w - - 1 27",
"8/1b2k3/1r2pnpp/2r5/2BNpP1P/1P4P1/2P5/2K1R1R1 w - - 3 28",
"8/1b1nk3/1r2p1pp/2r5/2BNpPPP/1P6/2P5/2K1R1R1 w - - 1 29",
"8/1b2k3/1r2p1pp/2r1nP2/2BNp1PP/1P6/2P5/2K1R1R1 w - - 1 30",
"8/1b2k3/1r2p1p1/2r1nPp1/2BNp2P/1P6/2P5/2K1R1R1 w - - 0 31",
"8/1b2k3/1r2p1n1/2r3p1/2BNp2P/1P6/2P5/2K1R1R1 w - - 0 32",
"8/1b2k3/1r2p1n1/6r1/2BNp2P/1P6/2P5/2K1R3 w - - 0 33",
"8/1b2k3/1r2p3/4n1P1/2BNp3/1P6/2P5/2K1R3 w - - 1 34",
"8/1b2k3/1r2p3/4n1P1/2BN4/1P2p3/2P5/2K4R w - - 0 35",
"8/1b2k3/1r2p2R/6P1/2nN4/1P2p3/2P5/2K5 w - - 0 36",
"8/1b2k3/3rp2R/6P1/2PN4/4p3/2P5/2K5 w - - 1 37",
"8/4k3/3rp2R/6P1/2PN4/2P1p3/6b1/2K5 w - - 1 38",
"8/4k3/r3p2R/2P3P1/3N4/2P1p3/6b1/2K5 w - - 1 39",
"8/3k4/r3p2R/2P2NP1/8/2P1p3/6b1/2K5 w - - 3 40",
"8/3k4/4p2R/2P3P1/8/2P1N3/6b1/r1K5 w - - 1 41",
"8/3k4/4p2R/2P3P1/8/2P1N3/3K2b1/6r1 w - - 3 42",
"8/3k4/4p2R/2P3P1/8/2PKNb2/8/6r1 w - - 5 43",
"8/4k3/4p1R1/2P3P1/8/2PKNb2/8/6r1 w - - 7 44",
"8/4k3/4p1R1/2P3P1/3K4/2P1N3/8/6rb w - - 9 45",
"8/3k4/4p1R1/2P1K1P1/8/2P1N3/8/6rb w - - 11 46",
"8/3k4/4p1R1/2P3P1/5K2/2P1N3/8/4r2b w - - 13 47",
"8/3k4/2b1p2R/2P3P1/5K2/2P1N3/8/4r3 w - - 15 48",
"8/3k4/2b1p3/2P3P1/5K2/2P1N2R/8/6r1 w - - 17 49",
"2k5/7R/2b1p3/2P3P1/5K2/2P1N3/8/6r1 w - - 19 50",
"2k5/7R/4p3/2P3P1/b1P2K2/4N3/8/6r1 w - - 1 51",
"2k5/3bR3/4p3/2P3P1/2P2K2/4N3/8/6r1 w - - 3 52",
"3k4/3b2R1/4p3/2P3P1/2P2K2/4N3/8/6r1 w - - 5 53",
"3kb3/6R1/4p1P1/2P5/2P2K2/4N3/8/6r1 w - - 1 54",
"3kb3/6R1/4p1P1/2P5/2P2KN1/8/8/2r5 w - - 3 55",
"3kb3/6R1/4p1P1/2P1N3/2P2K2/8/8/5r2 w - - 5 56",
"3kb3/6R1/4p1P1/2P1N3/2P5/4K3/8/4r3 w - - 7 57",
},
{
"rnbq1rk1/ppp1npb1/4p1p1/3P3p/3PP3/2N2N2/PP2BPPP/R1BQ1RK1 b - - 0 8",
"rnbq1rk1/ppp1npb1/6p1/3pP2p/3P4/2N2N2/PP2BPPP/R1BQ1RK1 b - - 0 9",
"rn1q1rk1/ppp1npb1/6p1/3pP2p/3P2b1/2N2N2/PP2BPPP/R1BQR1K1 b - - 2 10",
"r2q1rk1/ppp1npb1/2n3p1/3pP2p/3P2bN/2N5/PP2BPPP/R1BQR1K1 b - - 4 11",
"r4rk1/pppqnpb1/2n3p1/3pP2p/3P2bN/2N4P/PP2BPP1/R1BQR1K1 b - - 0 12",
"r4rk1/pppqnpb1/2n3p1/3pP2p/3P3N/7P/PP2NPP1/R1BQR1K1 b - - 0 13",
"r4rk1/pppq1pb1/2n3p1/3pPN1p/3P4/7P/PP2NPP1/R1BQR1K1 b - - 0 14",
"r4rk1/ppp2pb1/2n3p1/3pPq1p/3P1N2/7P/PP3PP1/R1BQR1K1 b - - 1 15",
"r4rk1/pppq1pb1/2n3p1/3pP2p/P2P1N2/7P/1P3PP1/R1BQR1K1 b - - 0 16",
"r2n1rk1/pppq1pb1/6p1/3pP2p/P2P1N2/R6P/1P3PP1/2BQR1K1 b - - 2 17",
"r4rk1/pppq1pb1/4N1p1/3pP2p/P2P4/R6P/1P3PP1/2BQR1K1 b - - 0 18",
"r4rk1/ppp2pb1/4q1p1/3pP1Bp/P2P4/R6P/1P3PP1/3QR1K1 b - - 1 19",
"r3r1k1/ppp2pb1/4q1p1/3pP1Bp/P2P1P2/R6P/1P4P1/3QR1K1 b - - 0 20",
"r3r1k1/ppp3b1/4qpp1/3pP2p/P2P1P1B/R6P/1P4P1/3QR1K1 b - - 1 21",
"r3r1k1/ppp3b1/4q1p1/3pP2p/P4P1B/R6P/1P4P1/3QR1K1 b - - 0 22",
"r4rk1/ppp3b1/4q1p1/3pP1Bp/P4P2/R6P/1P4P1/3QR1K1 b - - 2 23",
"r4rk1/pp4b1/4q1p1/2ppP1Bp/P4P2/3R3P/1P4P1/3QR1K1 b - - 1 24",
"r4rk1/pp4b1/4q1p1/2p1P1Bp/P2p1PP1/3R3P/1P6/3QR1K1 b - - 0 25",
"r4rk1/pp4b1/4q1p1/2p1P1B1/P2p1PP1/3R4/1P6/3QR1K1 b - - 0 26",
"r5k1/pp3rb1/4q1p1/2p1P1B1/P2p1PP1/6R1/1P6/3QR1K1 b - - 2 27",
"5rk1/pp3rb1/4q1p1/2p1P1B1/P2pRPP1/6R1/1P6/3Q2K1 b - - 4 28",
"5rk1/1p3rb1/p3q1p1/P1p1P1B1/3pRPP1/6R1/1P6/3Q2K1 b - - 0 29",
"4r1k1/1p3rb1/p3q1p1/P1p1P1B1/3pRPP1/1P4R1/8/3Q2K1 b - - 0 30",
"4r1k1/5rb1/pP2q1p1/2p1P1B1/3pRPP1/1P4R1/8/3Q2K1 b - - 0 31",
"4r1k1/5rb1/pq4p1/2p1P1B1/3pRPP1/1P4R1/4Q3/6K1 b - - 1 32",
"4r1k1/1r4b1/pq4p1/2p1P1B1/3pRPP1/1P4R1/2Q5/6K1 b - - 3 33",
"4r1k1/1r4b1/1q4p1/p1p1P1B1/3p1PP1/1P4R1/2Q5/4R1K1 b - - 1 34",
"4r1k1/3r2b1/1q4p1/p1p1P1B1/2Qp1PP1/1P4R1/8/4R1K1 b - - 3 35",
"4r1k1/3r2b1/4q1p1/p1p1P1B1/2Qp1PP1/1P4R1/5K2/4R3 b - - 5 36",
"4r1k1/3r2b1/6p1/p1p1P1B1/2Pp1PP1/6R1/5K2/4R3 b - - 0 37",
"4r1k1/3r2b1/6p1/p1p1P1B1/2P2PP1/3p2R1/5K2/3R4 b - - 1 38",
"5rk1/3r2b1/6p1/p1p1P1B1/2P2PP1/3p2R1/8/3RK3 b - - 3 39",
"5rk1/6b1/6p1/p1p1P1B1/2Pr1PP1/3R4/8/3RK3 b - - 0 40",
"5rk1/3R2b1/6p1/p1p1P1B1/2r2PP1/8/8/3RK3 b - - 1 41",
"5rk1/3R2b1/6p1/p1p1P1B1/4rPP1/8/3K4/3R4 b - - 3 42",
"1r4k1/3R2b1/6p1/p1p1P1B1/4rPP1/2K5/8/3R4 b - - 5 43",
"1r4k1/3R2b1/6p1/p1p1P1B1/2K2PP1/4r3/8/3R4 b - - 7 44",
"1r3bk1/8/3R2p1/p1p1P1B1/2K2PP1/4r3/8/3R4 b - - 9 45",
"1r3bk1/8/6R1/2p1P1B1/p1K2PP1/4r3/8/3R4 b - - 0 46",
"1r3b2/5k2/R7/2p1P1B1/p1K2PP1/4r3/8/3R4 b - - 2 47",
"5b2/1r3k2/R7/2p1P1B1/p1K2PP1/4r3/8/7R b - - 4 48",
"5b2/5k2/R7/2pKP1B1/pr3PP1/4r3/8/7R b - - 6 49",
"5b2/5k2/R1K5/2p1P1B1/p2r1PP1/4r3/8/7R b - - 8 50",
"8/R4kb1/2K5/2p1P1B1/p2r1PP1/4r3/8/7R b - - 10 51",
"8/R5b1/2K3k1/2p1PPB1/p2r2P1/4r3/8/7R b - - 0 52",
"8/6R1/2K5/2p1PPk1/p2r2P1/4r3/8/7R b - - 0 53",
"8/6R1/2K5/2p1PP2/p2r1kP1/4r3/8/5R2 b - - 2 54",
"8/6R1/2K2P2/2p1P3/p2r2P1/4r1k1/8/5R2 b - - 0 55",
"8/5PR1/2K5/2p1P3/p2r2P1/4r3/6k1/5R2 b - - 0 56",
},
{
"rn1qkb1r/p1pbpppp/5n2/8/2pP4/2N5/1PQ1PPPP/R1B1KBNR w KQkq - 0 7",
"r2qkb1r/p1pbpppp/2n2n2/8/2pP4/2N2N2/1PQ1PPPP/R1B1KB1R w KQkq - 2 8",
"r2qkb1r/p1pbpppp/5n2/8/1npPP3/2N2N2/1PQ2PPP/R1B1KB1R w KQkq - 1 9",
"r2qkb1r/p1pb1ppp/4pn2/8/1npPP3/2N2N2/1P3PPP/R1BQKB1R w KQkq - 0 10",
"r2qk2r/p1pbbppp/4pn2/8/1nBPP3/2N2N2/1P3PPP/R1BQK2R w KQkq - 1 11",
"r2q1rk1/p1pbbppp/4pn2/8/1nBPP3/2N2N2/1P3PPP/R1BQ1RK1 w - - 3 12",
"r2q1rk1/2pbbppp/p3pn2/8/1nBPPB2/2N2N2/1P3PPP/R2Q1RK1 w - - 0 13",
"r2q1rk1/2p1bppp/p3pn2/1b6/1nBPPB2/2N2N2/1P3PPP/R2QR1K1 w - - 2 14",
"r2q1rk1/4bppp/p1p1pn2/1b6/1nBPPB2/1PN2N2/5PPP/R2QR1K1 w - - 0 15",
"r4rk1/3qbppp/p1p1pn2/1b6/1nBPPB2/1PN2N2/3Q1PPP/R3R1K1 w - - 2 16",
"r4rk1/1q2bppp/p1p1pn2/1b6/1nBPPB2/1PN2N1P/3Q1PP1/R3R1K1 w - - 1 17",
"r3r1k1/1q2bppp/p1p1pn2/1b6/1nBPPB2/1PN2N1P/4QPP1/R3R1K1 w - - 3 18",
"r3r1k1/1q1nbppp/p1p1p3/1b6/1nBPPB2/1PN2N1P/4QPP1/3RR1K1 w - - 5 19",
"r3rbk1/1q1n1ppp/p1p1p3/1b6/1nBPPB2/1PN2N1P/3RQPP1/4R1K1 w - - 7 20",
"r3rbk1/1q3ppp/pnp1p3/1b6/1nBPPB2/1PN2N1P/3RQPP1/4R2K w - - 9 21",
"2r1rbk1/1q3ppp/pnp1p3/1b6/1nBPPB2/1PN2N1P/3RQPP1/1R5K w - - 11 22",
"2r1rbk1/1q4pp/pnp1pp2/1b6/1nBPPB2/1PN2N1P/4QPP1/1R1R3K w - - 0 23",
"2r1rbk1/5qpp/pnp1pp2/1b6/1nBPP3/1PN1BN1P/4QPP1/1R1R3K w - - 2 24",
"2r1rbk1/5qp1/pnp1pp1p/1b6/1nBPP3/1PN1BN1P/4QPP1/1R1R2K1 w - - 0 25",
"2r1rbk1/5qp1/pnp1pp1p/1b6/2BPP3/1P2BN1P/n3QPP1/1R1R2K1 w - - 0 26",
"r3rbk1/5qp1/pnp1pp1p/1b6/2BPP3/1P2BN1P/Q4PP1/1R1R2K1 w - - 1 27",
"rr3bk1/5qp1/pnp1pp1p/1b6/2BPP3/1P2BN1P/Q4PP1/R2R2K1 w - - 3 28",
"rr2qbk1/6p1/pnp1pp1p/1b6/2BPP3/1P2BN1P/4QPP1/R2R2K1 w - - 5 29",
"rr2qbk1/6p1/1np1pp1p/pb6/2BPP3/1P1QBN1P/5PP1/R2R2K1 w - - 0 30",
"rr2qbk1/6p1/1n2pp1p/pp6/3PP3/1P1QBN1P/5PP1/R2R2K1 w - - 0 31",
"rr2qbk1/6p1/1n2pp1p/1p1P4/p3P3/1P1QBN1P/5PP1/R2R2K1 w - - 0 32",
"rr2qbk1/3n2p1/3Ppp1p/1p6/p3P3/1P1QBN1P/5PP1/R2R2K1 w - - 1 33",
"rr3bk1/3n2p1/3Ppp1p/1p5q/pP2P3/3QBN1P/5PP1/R2R2K1 w - - 1 34",
"rr3bk1/3n2p1/3Ppp1p/1p5q/1P2P3/p2QBN1P/5PP1/2RR2K1 w - - 0 35",
"1r3bk1/3n2p1/r2Ppp1p/1p5q/1P2P3/pQ2BN1P/5PP1/2RR2K1 w - - 2 36",
"1r2qbk1/2Rn2p1/r2Ppp1p/1p6/1P2P3/pQ2BN1P/5PP1/3R2K1 w - - 4 37",
"1r2qbk1/2Rn2p1/r2Ppp1p/1pB5/1P2P3/1Q3N1P/p4PP1/3R2K1 w - - 0 38",
"1r2q1k1/2Rn2p1/r2bpp1p/1pB5/1P2P3/1Q3N1P/p4PP1/R5K1 w - - 0 39",
"1r2q1k1/2Rn2p1/3rpp1p/1p6/1P2P3/1Q3N1P/p4PP1/R5K1 w - - 0 40",
"2r1q1k1/2Rn2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 1 41",
"1r2q1k1/1R1n2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 3 42",
"2r1q1k1/2Rn2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 5 43",
"1r2q1k1/1R1n2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 7 44",
"1rq3k1/R2n2p1/3rpp1p/1p6/1P2P3/5N1P/Q4PP1/R5K1 w - - 9 45",
"2q3k1/Rr1n2p1/3rpp1p/1p6/1P2P3/5N1P/4QPP1/R5K1 w - - 11 46",
"Rrq3k1/3n2p1/3rpp1p/1p6/1P2P3/5N1P/4QPP1/R5K1 w - - 13 47",
},
{
"rn1qkb1r/1pp2ppp/p4p2/3p1b2/5P2/1P2PN2/P1PP2PP/RN1QKB1R b KQkq - 1 6",
"r2qkb1r/1pp2ppp/p1n2p2/3p1b2/3P1P2/1P2PN2/P1P3PP/RN1QKB1R b KQkq - 0 7",
"r2qkb1r/1pp2ppp/p4p2/3p1b2/1n1P1P2/1P1BPN2/P1P3PP/RN1QK2R b KQkq - 2 8",
"r2qkb1r/1pp2ppp/p4p2/3p1b2/3P1P2/1P1PPN2/P5PP/RN1QK2R b KQkq - 0 9",
"r2qk2r/1pp2ppp/p2b1p2/3p1b2/3P1P2/1PNPPN2/P5PP/R2QK2R b KQkq - 2 10",
"r2qk2r/1p3ppp/p1pb1p2/3p1b2/3P1P2/1PNPPN2/P5PP/R2Q1RK1 b kq - 1 11",
"r2q1rk1/1p3ppp/p1pb1p2/3p1b2/3P1P2/1PNPPN2/P2Q2PP/R4RK1 b - - 3 12",
"r2qr1k1/1p3ppp/p1pb1p2/3p1b2/3P1P2/1P1PPN2/P2QN1PP/R4RK1 b - - 5 13",
"r3r1k1/1p3ppp/pqpb1p2/3p1b2/3P1P2/1P1PPNN1/P2Q2PP/R4RK1 b - - 7 14",
"r3r1k1/1p3ppp/pqp2p2/3p1b2/1b1P1P2/1P1PPNN1/P1Q3PP/R4RK1 b - - 9 15",
"r3r1k1/1p1b1ppp/pqp2p2/3p4/1b1P1P2/1P1PPNN1/P4QPP/R4RK1 b - - 11 16",
"2r1r1k1/1p1b1ppp/pqp2p2/3p4/1b1PPP2/1P1P1NN1/P4QPP/R4RK1 b - - 0 17",
"2r1r1k1/1p1b1ppp/pq3p2/2pp4/1b1PPP2/PP1P1NN1/5QPP/R4RK1 b - - 0 18",
"2r1r1k1/1p1b1ppp/pq3p2/2Pp4/4PP2/PPbP1NN1/5QPP/R4RK1 b - - 0 19",
"2r1r1k1/1p1b1ppp/p4p2/2Pp4/4PP2/PqbP1NN1/5QPP/RR4K1 b - - 1 20",
"2r1r1k1/1p1b1ppp/p4p2/2Pp4/q3PP2/P1bP1NN1/R4QPP/1R4K1 b - - 3 21",
"2r1r1k1/1p3ppp/p4p2/1bPP4/q4P2/P1bP1NN1/R4QPP/1R4K1 b - - 0 22",
"2r1r1k1/1p3ppp/p4p2/2PP4/q4P2/P1bb1NN1/R4QPP/2R3K1 b - - 1 23",
"2r1r1k1/1p3ppp/p2P1p2/2P5/2q2P2/P1bb1NN1/R4QPP/2R3K1 b - - 0 24",
"2rr2k1/1p3ppp/p2P1p2/2P5/2q2P2/P1bb1NN1/R4QPP/2R4K b - - 2 25",
"2rr2k1/1p3ppp/p2P1p2/2Q5/5P2/P1bb1NN1/R5PP/2R4K b - - 0 26",
"3r2k1/1p3ppp/p2P1p2/2r5/5P2/P1bb1N2/R3N1PP/2R4K b - - 1 27",
"3r2k1/1p3ppp/p2P1p2/2r5/5P2/P1b2N2/4R1PP/2R4K b - - 0 28",
"3r2k1/1p3ppp/p2P1p2/2r5/1b3P2/P4N2/4R1PP/3R3K b - - 2 29",
"3r2k1/1p2Rppp/p2P1p2/b1r5/5P2/P4N2/6PP/3R3K b - - 4 30",
"3r2k1/1R3ppp/p1rP1p2/b7/5P2/P4N2/6PP/3R3K b - - 0 31",
"3r2k1/1R3ppp/p2R1p2/b7/5P2/P4N2/6PP/7K b - - 0 32",
"6k1/1R3ppp/p2r1p2/b7/5P2/P4NP1/7P/7K b - - 0 33",
"6k1/1R3p1p/p2r1pp1/b7/5P1P/P4NP1/8/7K b - - 0 34",
"6k1/3R1p1p/pr3pp1/b7/5P1P/P4NP1/8/7K b - - 2 35",
"6k1/5p2/pr3pp1/b2R3p/5P1P/P4NP1/8/7K b - - 1 36",
"6k1/5p2/pr3pp1/7p/5P1P/P1bR1NP1/8/7K b - - 3 37",
"6k1/5p2/p1r2pp1/7p/5P1P/P1bR1NP1/6K1/8 b - - 5 38",
"6k1/5p2/p1r2pp1/b2R3p/5P1P/P4NP1/6K1/8 b - - 7 39",
"6k1/5p2/p4pp1/b2R3p/5P1P/P4NPK/2r5/8 b - - 9 40",
"6k1/2b2p2/p4pp1/7p/5P1P/P2R1NPK/2r5/8 b - - 11 41",
"6k1/2b2p2/5pp1/p6p/3N1P1P/P2R2PK/2r5/8 b - - 1 42",
"6k1/2b2p2/5pp1/p6p/3N1P1P/P1R3PK/r7/8 b - - 3 43",
"6k1/5p2/1b3pp1/p6p/5P1P/P1R3PK/r1N5/8 b - - 5 44",
"8/5pk1/1bR2pp1/p6p/5P1P/P5PK/r1N5/8 b - - 7 45",
"3b4/5pk1/2R2pp1/p4P1p/7P/P5PK/r1N5/8 b - - 0 46",
"8/4bpk1/2R2pp1/p4P1p/6PP/P6K/r1N5/8 b - - 0 47",
"8/5pk1/2R2pP1/p6p/6PP/b6K/r1N5/8 b - - 0 48",
"8/6k1/2R2pp1/p6P/7P/b6K/r1N5/8 b - - 0 49",
"8/6k1/2R2p2/p6p/7P/b5K1/r1N5/8 b - - 1 50",
"8/8/2R2pk1/p6p/7P/b4K2/r1N5/8 b - - 3 51",
"8/8/2R2pk1/p6p/7P/4NK2/rb6/8 b - - 5 52",
"2R5/8/5pk1/7p/p6P/4NK2/rb6/8 b - - 1 53",
"6R1/8/5pk1/7p/p6P/4NK2/1b6/r7 b - - 3 54",
"R7/5k2/5p2/7p/p6P/4NK2/1b6/r7 b - - 5 55",
"R7/5k2/5p2/7p/7P/p3N3/1b2K3/r7 b - - 1 56",
"8/R4k2/5p2/7p/7P/p3N3/1b2K3/7r b - - 3 57",
"8/8/5pk1/7p/R6P/p3N3/1b2K3/7r b - - 5 58",
"8/8/5pk1/7p/R6P/p7/4K3/2bN3r b - - 7 59",
"8/8/5pk1/7p/R6P/p7/4KN1r/2b5 b - - 9 60",
"8/8/5pk1/7p/R6P/p3K3/1b3N1r/8 b - - 11 61",
"8/8/R4pk1/7p/7P/p1b1K3/5N1r/8 b - - 13 62",
"8/8/5pk1/7p/7P/2b1K3/R4N1r/8 b - - 0 63",
"8/8/5pk1/7p/3K3P/8/R4N1r/4b3 b - - 2 64",
}
};
// clang-format on
} // namespace
namespace Stockfish::Benchmark {
// Builds a list of UCI commands to be run by bench. There
// are five parameters: TT size in MB, number of search threads that
// should be used, the limit value spent for each position, a file name
// where to look for positions in FEN format, and the type of the limit:
// depth, perft, nodes and movetime (in milliseconds). Examples:
//
// bench : search default positions up to depth 13
// bench 64 1 15 : search default positions up to depth 15 (TT = 64MB)
// bench 64 1 100000 default nodes : search default positions for 100K nodes each
// bench 64 4 5000 current movetime : search current position with 4 threads for 5 sec
// bench 16 1 5 blah perft : run a perft 5 on positions in file "blah"
std::vector<std::string> setup_bench(const std::string& currentFen, std::istream& is) {
std::vector<std::string> fens, list;
std::string go, token;
// Assign default values to missing arguments
std::string ttSize = (is >> token) ? token : "16";
std::string threads = (is >> token) ? token : "1";
std::string limit = (is >> token) ? token : "13";
std::string fenFile = (is >> token) ? token : "default";
std::string limitType = (is >> token) ? token : "depth";
go = limitType == "eval" ? "eval" : "go " + limitType + " " + limit;
if (fenFile == "default")
fens = Defaults;
else if (fenFile == "current")
fens.push_back(currentFen);
else
{
std::string fen;
std::ifstream file(fenFile);
if (!file.is_open())
{
std::cerr << "Unable to open file " << fenFile << std::endl;
exit(EXIT_FAILURE);
}
while (getline(file, fen))
if (!fen.empty())
fens.push_back(fen);
file.close();
}
list.emplace_back("setoption name Threads value " + threads);
list.emplace_back("setoption name Hash value " + ttSize);
list.emplace_back("ucinewgame");
for (const std::string& fen : fens)
if (fen.find("setoption") != std::string::npos)
list.emplace_back(fen);
else
{
list.emplace_back("position fen " + fen);
list.emplace_back(go);
}
return list;
}
BenchmarkSetup setup_benchmark(std::istream& is) {
// TT_SIZE_PER_THREAD is chosen such that roughly half of the hash is used all positions
// for the current sequence have been searched.
static constexpr int TT_SIZE_PER_THREAD = 128;
static constexpr int DEFAULT_DURATION_S = 150;
BenchmarkSetup setup{};
// Assign default values to missing arguments
int desiredTimeS;
if (!(is >> setup.threads))
setup.threads = get_hardware_concurrency();
else
setup.originalInvocation += std::to_string(setup.threads);
if (!(is >> setup.ttSize))
setup.ttSize = TT_SIZE_PER_THREAD * setup.threads;
else
setup.originalInvocation += " " + std::to_string(setup.ttSize);
if (!(is >> desiredTimeS))
desiredTimeS = DEFAULT_DURATION_S;
else
setup.originalInvocation += " " + std::to_string(desiredTimeS);
setup.filledInvocation += std::to_string(setup.threads) + " " + std::to_string(setup.ttSize)
+ " " + std::to_string(desiredTimeS);
auto getCorrectedTime = [&](int ply) {
// time per move is fit roughly based on LTC games
// seconds = 50/{ply+15}
// ms = 50000/{ply+15}
// with this fit 10th move gets 2000ms
// adjust for desired 10th move time
return 50000.0 / (static_cast<double>(ply) + 15.0);
};
float totalTime = 0;
for (const auto& game : BenchmarkPositions)
{
setup.commands.emplace_back("ucinewgame");
int ply = 1;
for (int i = 0; i < static_cast<int>(game.size()); ++i)
{
const float correctedTime = getCorrectedTime(ply);
totalTime += correctedTime;
ply += 1;
}
}
float timeScaleFactor = static_cast<float>(desiredTimeS * 1000) / totalTime;
for (const auto& game : BenchmarkPositions)
{
setup.commands.emplace_back("ucinewgame");
int ply = 1;
for (const std::string& fen : game)
{
setup.commands.emplace_back("position fen " + fen);
const int correctedTime = static_cast<int>(getCorrectedTime(ply) * timeScaleFactor);
setup.commands.emplace_back("go movetime " + std::to_string(correctedTime));
ply += 1;
}
}
return setup;
}
} // namespace Stockfish
| 26,327
|
C++
|
.cpp
| 468
| 48.974359
| 107
| 0.628835
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,031
|
memory.cpp
|
official-stockfish_Stockfish/src/memory.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "memory.h"
#include <cstdlib>
#if __has_include("features.h")
#include <features.h>
#endif
#if defined(__linux__) && !defined(__ANDROID__)
#include <sys/mman.h>
#endif
#if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) \
|| (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) \
|| defined(__e2k__)
#define POSIXALIGNEDALLOC
#include <stdlib.h>
#endif
#ifdef _WIN32
#if _WIN32_WINNT < 0x0601
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <ios> // std::hex, std::dec
#include <iostream> // std::cerr
#include <ostream> // std::endl
#include <windows.h>
// The needed Windows API for processor groups could be missed from old Windows
// versions, so instead of calling them directly (forcing the linker to resolve
// the calls at compile time), try to load them at runtime. To do this we need
// first to define the corresponding function pointers.
extern "C" {
using OpenProcessToken_t = bool (*)(HANDLE, DWORD, PHANDLE);
using LookupPrivilegeValueA_t = bool (*)(LPCSTR, LPCSTR, PLUID);
using AdjustTokenPrivileges_t =
bool (*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
}
#endif
namespace Stockfish {
// Wrappers for systems where the c++17 implementation does not guarantee the
// availability of aligned_alloc(). Memory allocated with std_aligned_alloc()
// must be freed with std_aligned_free().
void* std_aligned_alloc(size_t alignment, size_t size) {
#if defined(_ISOC11_SOURCE)
return aligned_alloc(alignment, size);
#elif defined(POSIXALIGNEDALLOC)
void* mem = nullptr;
posix_memalign(&mem, alignment, size);
return mem;
#elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
return _mm_malloc(size, alignment);
#elif defined(_WIN32)
return _aligned_malloc(size, alignment);
#else
return std::aligned_alloc(alignment, size);
#endif
}
void std_aligned_free(void* ptr) {
#if defined(POSIXALIGNEDALLOC)
free(ptr);
#elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
_mm_free(ptr);
#elif defined(_WIN32)
_aligned_free(ptr);
#else
free(ptr);
#endif
}
// aligned_large_pages_alloc() will return suitably aligned memory,
// if possible using large pages.
#if defined(_WIN32)
static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
#if !defined(_WIN64)
return nullptr;
#else
HANDLE hProcessToken{};
LUID luid{};
void* mem = nullptr;
const size_t largePageSize = GetLargePageMinimum();
if (!largePageSize)
return nullptr;
// Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
if (!hAdvapi32)
hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
auto OpenProcessToken_f =
OpenProcessToken_t((void (*)()) GetProcAddress(hAdvapi32, "OpenProcessToken"));
if (!OpenProcessToken_f)
return nullptr;
auto LookupPrivilegeValueA_f =
LookupPrivilegeValueA_t((void (*)()) GetProcAddress(hAdvapi32, "LookupPrivilegeValueA"));
if (!LookupPrivilegeValueA_f)
return nullptr;
auto AdjustTokenPrivileges_f =
AdjustTokenPrivileges_t((void (*)()) GetProcAddress(hAdvapi32, "AdjustTokenPrivileges"));
if (!AdjustTokenPrivileges_f)
return nullptr;
// We need SeLockMemoryPrivilege, so try to enable it for the process
if (!OpenProcessToken_f( // OpenProcessToken()
GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
return nullptr;
if (LookupPrivilegeValueA_f(nullptr, "SeLockMemoryPrivilege", &luid))
{
TOKEN_PRIVILEGES tp{};
TOKEN_PRIVILEGES prevTp{};
DWORD prevTpLen = 0;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges()
// succeeds, we still need to query GetLastError() to ensure that the privileges
// were actually obtained.
if (AdjustTokenPrivileges_f(hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp,
&prevTpLen)
&& GetLastError() == ERROR_SUCCESS)
{
// Round up size to full pages and allocate
allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
PAGE_READWRITE);
// Privilege no longer needed, restore previous state
AdjustTokenPrivileges_f(hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
}
}
CloseHandle(hProcessToken);
return mem;
#endif
}
void* aligned_large_pages_alloc(size_t allocSize) {
// Try to allocate large pages
void* mem = aligned_large_pages_alloc_windows(allocSize);
// Fall back to regular, page-aligned, allocation if necessary
if (!mem)
mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
return mem;
}
#else
void* aligned_large_pages_alloc(size_t allocSize) {
#if defined(__linux__)
constexpr size_t alignment = 2 * 1024 * 1024; // 2MB page size assumed
#else
constexpr size_t alignment = 4096; // small page size assumed
#endif
// Round up to multiples of alignment
size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
void* mem = std_aligned_alloc(alignment, size);
#if defined(MADV_HUGEPAGE)
madvise(mem, size, MADV_HUGEPAGE);
#endif
return mem;
}
#endif
bool has_large_pages() {
#if defined(_WIN32)
constexpr size_t page_size = 2 * 1024 * 1024; // 2MB page size assumed
void* mem = aligned_large_pages_alloc_windows(page_size);
if (mem == nullptr)
{
return false;
}
else
{
aligned_large_pages_free(mem);
return true;
}
#elif defined(__linux__)
#if defined(MADV_HUGEPAGE)
return true;
#else
return false;
#endif
#else
return false;
#endif
}
// aligned_large_pages_free() will free the previously memory allocated
// by aligned_large_pages_alloc(). The effect is a nop if mem == nullptr.
#if defined(_WIN32)
void aligned_large_pages_free(void* mem) {
if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
{
DWORD err = GetLastError();
std::cerr << "Failed to free large page memory. Error code: 0x" << std::hex << err
<< std::dec << std::endl;
exit(EXIT_FAILURE);
}
}
#else
void aligned_large_pages_free(void* mem) { std_aligned_free(mem); }
#endif
} // namespace Stockfish
| 7,779
|
C++
|
.cpp
| 204
| 33.029412
| 100
| 0.679404
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,032
|
search.cpp
|
official-stockfish_Stockfish/src/search.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "search.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <initializer_list>
#include <iostream>
#include <list>
#include <ratio>
#include <string>
#include <utility>
#include "evaluate.h"
#include "history.h"
#include "misc.h"
#include "movegen.h"
#include "movepick.h"
#include "nnue/network.h"
#include "nnue/nnue_accumulator.h"
#include "nnue/nnue_common.h"
#include "nnue/nnue_misc.h"
#include "position.h"
#include "syzygy/tbprobe.h"
#include "thread.h"
#include "timeman.h"
#include "tt.h"
#include "uci.h"
#include "ucioption.h"
namespace Stockfish {
namespace TB = Tablebases;
void syzygy_extend_pv(const OptionsMap& options,
const Search::LimitsType& limits,
Stockfish::Position& pos,
Stockfish::Search::RootMove& rootMove,
Value& v);
using Eval::evaluate;
using namespace Search;
namespace {
// Futility margin
Value futility_margin(Depth d, bool noTtCutNode, bool improving, bool oppWorsening) {
Value futilityMult = 109 - 27 * noTtCutNode;
Value improvingDeduction = improving * futilityMult * 2;
Value worseningDeduction = oppWorsening * futilityMult / 3;
return futilityMult * d - improvingDeduction - worseningDeduction;
}
constexpr int futility_move_count(bool improving, Depth depth) {
return (3 + depth * depth) / (2 - improving);
}
// Add correctionHistory value to raw staticEval and guarantee evaluation
// does not hit the tablebase range.
Value to_corrected_static_eval(Value v, const Worker& w, const Position& pos, Stack* ss) {
const Color us = pos.side_to_move();
const auto m = (ss - 1)->currentMove;
const auto pcv = w.pawnCorrectionHistory[us][pawn_structure_index<Correction>(pos)];
const auto macv = w.majorPieceCorrectionHistory[us][major_piece_index(pos)];
const auto micv = w.minorPieceCorrectionHistory[us][minor_piece_index(pos)];
const auto wnpcv = w.nonPawnCorrectionHistory[WHITE][us][non_pawn_index<WHITE>(pos)];
const auto bnpcv = w.nonPawnCorrectionHistory[BLACK][us][non_pawn_index<BLACK>(pos)];
int cntcv = 1;
if (m.is_ok())
cntcv = int((*(ss - 2)->continuationCorrectionHistory)[pos.piece_on(m.to_sq())][m.to_sq()]);
const auto cv =
(6384 * pcv + 3583 * macv + 6492 * micv + 6725 * (wnpcv + bnpcv) + cntcv * 5880) / 131072;
v += cv;
return std::clamp(v, VALUE_TB_LOSS_IN_MAX_PLY + 1, VALUE_TB_WIN_IN_MAX_PLY - 1);
}
// History and stats update bonus, based on depth
int stat_bonus(Depth d) { return std::min(168 * d - 100, 1718); }
// History and stats update malus, based on depth
int stat_malus(Depth d) { return std::min(768 * d - 257, 2351); }
// Add a small random component to draw evaluations to avoid 3-fold blindness
Value value_draw(size_t nodes) { return VALUE_DRAW - 1 + Value(nodes & 0x2); }
Value value_to_tt(Value v, int ply);
Value value_from_tt(Value v, int ply, int r50c);
void update_pv(Move* pv, Move move, const Move* childPv);
void update_continuation_histories(Stack* ss, Piece pc, Square to, int bonus);
void update_quiet_histories(
const Position& pos, Stack* ss, Search::Worker& workerThread, Move move, int bonus);
void update_all_stats(const Position& pos,
Stack* ss,
Search::Worker& workerThread,
Move bestMove,
Square prevSq,
ValueList<Move, 32>& quietsSearched,
ValueList<Move, 32>& capturesSearched,
Depth depth);
} // namespace
Search::Worker::Worker(SharedState& sharedState,
std::unique_ptr<ISearchManager> sm,
size_t threadId,
NumaReplicatedAccessToken token) :
// Unpack the SharedState struct into member variables
threadIdx(threadId),
numaAccessToken(token),
manager(std::move(sm)),
options(sharedState.options),
threads(sharedState.threads),
tt(sharedState.tt),
networks(sharedState.networks),
refreshTable(networks[token]) {
clear();
}
void Search::Worker::ensure_network_replicated() {
// Access once to force lazy initialization.
// We do this because we want to avoid initialization during search.
(void) (networks[numaAccessToken]);
}
void Search::Worker::start_searching() {
// Non-main threads go directly to iterative_deepening()
if (!is_mainthread())
{
iterative_deepening();
return;
}
main_manager()->tm.init(limits, rootPos.side_to_move(), rootPos.game_ply(), options,
main_manager()->originalTimeAdjust);
tt.new_search();
if (rootMoves.empty())
{
rootMoves.emplace_back(Move::none());
main_manager()->updates.onUpdateNoMoves(
{0, {rootPos.checkers() ? -VALUE_MATE : VALUE_DRAW, rootPos}});
}
else
{
threads.start_searching(); // start non-main threads
iterative_deepening(); // main thread start searching
}
// When we reach the maximum depth, we can arrive here without a raise of
// threads.stop. However, if we are pondering or in an infinite search,
// the UCI protocol states that we shouldn't print the best move before the
// GUI sends a "stop" or "ponderhit" command. We therefore simply wait here
// until the GUI sends one of those commands.
while (!threads.stop && (main_manager()->ponder || limits.infinite))
{} // Busy wait for a stop or a ponder reset
// Stop the threads if not already stopped (also raise the stop if
// "ponderhit" just reset threads.ponder)
threads.stop = true;
// Wait until all threads have finished
threads.wait_for_search_finished();
// When playing in 'nodes as time' mode, subtract the searched nodes from
// the available ones before exiting.
if (limits.npmsec)
main_manager()->tm.advance_nodes_time(threads.nodes_searched()
- limits.inc[rootPos.side_to_move()]);
Worker* bestThread = this;
Skill skill =
Skill(options["Skill Level"], options["UCI_LimitStrength"] ? int(options["UCI_Elo"]) : 0);
if (int(options["MultiPV"]) == 1 && !limits.depth && !limits.mate && !skill.enabled()
&& rootMoves[0].pv[0] != Move::none())
bestThread = threads.get_best_thread()->worker.get();
main_manager()->bestPreviousScore = bestThread->rootMoves[0].score;
main_manager()->bestPreviousAverageScore = bestThread->rootMoves[0].averageScore;
// Send again PV info if we have a new best thread
if (bestThread != this)
main_manager()->pv(*bestThread, threads, tt, bestThread->completedDepth);
std::string ponder;
if (bestThread->rootMoves[0].pv.size() > 1
|| bestThread->rootMoves[0].extract_ponder_from_tt(tt, rootPos))
ponder = UCIEngine::move(bestThread->rootMoves[0].pv[1], rootPos.is_chess960());
auto bestmove = UCIEngine::move(bestThread->rootMoves[0].pv[0], rootPos.is_chess960());
main_manager()->updates.onBestmove(bestmove, ponder);
}
// Main iterative deepening loop. It calls search()
// repeatedly with increasing depth until the allocated thinking time has been
// consumed, the user stops the search, or the maximum search depth is reached.
void Search::Worker::iterative_deepening() {
SearchManager* mainThread = (is_mainthread() ? main_manager() : nullptr);
Move pv[MAX_PLY + 1];
Depth lastBestMoveDepth = 0;
Value lastBestScore = -VALUE_INFINITE;
auto lastBestPV = std::vector{Move::none()};
Value alpha, beta;
Value bestValue = -VALUE_INFINITE;
Color us = rootPos.side_to_move();
double timeReduction = 1, totBestMoveChanges = 0;
int delta, iterIdx = 0;
// Allocate stack with extra size to allow access from (ss - 7) to (ss + 2):
// (ss - 7) is needed for update_continuation_histories(ss - 1) which accesses (ss - 6),
// (ss + 2) is needed for initialization of cutOffCnt.
Stack stack[MAX_PLY + 10] = {};
Stack* ss = stack + 7;
for (int i = 7; i > 0; --i)
{
(ss - i)->continuationHistory =
&this->continuationHistory[0][0][NO_PIECE][0]; // Use as a sentinel
(ss - i)->continuationCorrectionHistory = &this->continuationCorrectionHistory[NO_PIECE][0];
(ss - i)->staticEval = VALUE_NONE;
}
for (int i = 0; i <= MAX_PLY + 2; ++i)
(ss + i)->ply = i;
ss->pv = pv;
if (mainThread)
{
if (mainThread->bestPreviousScore == VALUE_INFINITE)
mainThread->iterValue.fill(VALUE_ZERO);
else
mainThread->iterValue.fill(mainThread->bestPreviousScore);
}
size_t multiPV = size_t(options["MultiPV"]);
Skill skill(options["Skill Level"], options["UCI_LimitStrength"] ? int(options["UCI_Elo"]) : 0);
// When playing with strength handicap enable MultiPV search that we will
// use behind-the-scenes to retrieve a set of possible moves.
if (skill.enabled())
multiPV = std::max(multiPV, size_t(4));
multiPV = std::min(multiPV, rootMoves.size());
int searchAgainCounter = 0;
lowPlyHistory.fill(0);
// Iterative deepening loop until requested to stop or the target depth is reached
while (++rootDepth < MAX_PLY && !threads.stop
&& !(limits.depth && mainThread && rootDepth > limits.depth))
{
// Age out PV variability metric
if (mainThread)
totBestMoveChanges /= 2;
// Save the last iteration's scores before the first PV line is searched and
// all the move scores except the (new) PV are set to -VALUE_INFINITE.
for (RootMove& rm : rootMoves)
rm.previousScore = rm.score;
size_t pvFirst = 0;
pvLast = 0;
if (!threads.increaseDepth)
searchAgainCounter++;
// MultiPV loop. We perform a full root search for each PV line
for (pvIdx = 0; pvIdx < multiPV; ++pvIdx)
{
if (pvIdx == pvLast)
{
pvFirst = pvLast;
for (pvLast++; pvLast < rootMoves.size(); pvLast++)
if (rootMoves[pvLast].tbRank != rootMoves[pvFirst].tbRank)
break;
}
// Reset UCI info selDepth for each depth and each PV line
selDepth = 0;
// Reset aspiration window starting size
delta = 5 + std::abs(rootMoves[pvIdx].meanSquaredScore) / 13461;
Value avg = rootMoves[pvIdx].averageScore;
alpha = std::max(avg - delta, -VALUE_INFINITE);
beta = std::min(avg + delta, VALUE_INFINITE);
// Adjust optimism based on root move's averageScore (~4 Elo)
optimism[us] = 150 * avg / (std::abs(avg) + 85);
optimism[~us] = -optimism[us];
// Start with a small aspiration window and, in the case of a fail
// high/low, re-search with a bigger window until we don't fail
// high/low anymore.
int failedHighCnt = 0;
while (true)
{
// Adjust the effective depth searched, but ensure at least one
// effective increment for every four searchAgain steps (see issue #2717).
Depth adjustedDepth =
std::max(1, rootDepth - failedHighCnt - 3 * (searchAgainCounter + 1) / 4);
rootDelta = beta - alpha;
bestValue = search<Root>(rootPos, ss, alpha, beta, adjustedDepth, false);
// Bring the best move to the front. It is critical that sorting
// is done with a stable algorithm because all the values but the
// first and eventually the new best one is set to -VALUE_INFINITE
// and we want to keep the same order for all the moves except the
// new PV that goes to the front. Note that in the case of MultiPV
// search the already searched PV lines are preserved.
std::stable_sort(rootMoves.begin() + pvIdx, rootMoves.begin() + pvLast);
// If search has been stopped, we break immediately. Sorting is
// safe because RootMoves is still valid, although it refers to
// the previous iteration.
if (threads.stop)
break;
// When failing high/low give some update before a re-search. To avoid
// excessive output that could hang GUIs like Fritz 19, only start
// at nodes > 10M (rather than depth N, which can be reached quickly)
if (mainThread && multiPV == 1 && (bestValue <= alpha || bestValue >= beta)
&& nodes > 10000000)
main_manager()->pv(*this, threads, tt, rootDepth);
// In case of failing low/high increase aspiration window and re-search,
// otherwise exit the loop.
if (bestValue <= alpha)
{
beta = (alpha + beta) / 2;
alpha = std::max(bestValue - delta, -VALUE_INFINITE);
failedHighCnt = 0;
if (mainThread)
mainThread->stopOnPonderhit = false;
}
else if (bestValue >= beta)
{
beta = std::min(bestValue + delta, VALUE_INFINITE);
++failedHighCnt;
}
else
break;
delta += delta / 3;
assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
}
// Sort the PV lines searched so far and update the GUI
std::stable_sort(rootMoves.begin() + pvFirst, rootMoves.begin() + pvIdx + 1);
if (mainThread
&& (threads.stop || pvIdx + 1 == multiPV || nodes > 10000000)
// A thread that aborted search can have mated-in/TB-loss PV and
// score that cannot be trusted, i.e. it can be delayed or refuted
// if we would have had time to fully search other root-moves. Thus
// we suppress this output and below pick a proven score/PV for this
// thread (from the previous iteration).
&& !(threads.abortedSearch && rootMoves[0].uciScore <= VALUE_TB_LOSS_IN_MAX_PLY))
main_manager()->pv(*this, threads, tt, rootDepth);
if (threads.stop)
break;
}
if (!threads.stop)
completedDepth = rootDepth;
// We make sure not to pick an unproven mated-in score,
// in case this thread prematurely stopped search (aborted-search).
if (threads.abortedSearch && rootMoves[0].score != -VALUE_INFINITE
&& rootMoves[0].score <= VALUE_TB_LOSS_IN_MAX_PLY)
{
// Bring the last best move to the front for best thread selection.
Utility::move_to_front(rootMoves, [&lastBestPV = std::as_const(lastBestPV)](
const auto& rm) { return rm == lastBestPV[0]; });
rootMoves[0].pv = lastBestPV;
rootMoves[0].score = rootMoves[0].uciScore = lastBestScore;
}
else if (rootMoves[0].pv[0] != lastBestPV[0])
{
lastBestPV = rootMoves[0].pv;
lastBestScore = rootMoves[0].score;
lastBestMoveDepth = rootDepth;
}
if (!mainThread)
continue;
// Have we found a "mate in x"?
if (limits.mate && rootMoves[0].score == rootMoves[0].uciScore
&& ((rootMoves[0].score >= VALUE_MATE_IN_MAX_PLY
&& VALUE_MATE - rootMoves[0].score <= 2 * limits.mate)
|| (rootMoves[0].score != -VALUE_INFINITE
&& rootMoves[0].score <= VALUE_MATED_IN_MAX_PLY
&& VALUE_MATE + rootMoves[0].score <= 2 * limits.mate)))
threads.stop = true;
// If the skill level is enabled and time is up, pick a sub-optimal best move
if (skill.enabled() && skill.time_to_pick(rootDepth))
skill.pick_best(rootMoves, multiPV);
// Use part of the gained time from a previous stable move for the current move
for (auto&& th : threads)
{
totBestMoveChanges += th->worker->bestMoveChanges;
th->worker->bestMoveChanges = 0;
}
// Do we have time for the next iteration? Can we stop searching now?
if (limits.use_time_management() && !threads.stop && !mainThread->stopOnPonderhit)
{
int nodesEffort = rootMoves[0].effort * 100 / std::max(size_t(1), size_t(nodes));
double fallingEval = (11 + 2 * (mainThread->bestPreviousAverageScore - bestValue)
+ (mainThread->iterValue[iterIdx] - bestValue))
/ 100.0;
fallingEval = std::clamp(fallingEval, 0.580, 1.667);
// If the bestMove is stable over several iterations, reduce time accordingly
timeReduction = lastBestMoveDepth + 8 < completedDepth ? 1.495 : 0.687;
double reduction = (1.48 + mainThread->previousTimeReduction) / (2.17 * timeReduction);
double bestMoveInstability = 1 + 1.88 * totBestMoveChanges / threads.size();
double recapture = limits.capSq == rootMoves[0].pv[0].to_sq() ? 0.955 : 1.005;
double totalTime =
mainThread->tm.optimum() * fallingEval * reduction * bestMoveInstability * recapture;
// Cap used time in case of a single legal move for a better viewer experience
if (rootMoves.size() == 1)
totalTime = std::min(500.0, totalTime);
auto elapsedTime = elapsed();
if (completedDepth >= 10 && nodesEffort >= 97 && elapsedTime > totalTime * 0.739
&& !mainThread->ponder)
threads.stop = true;
// Stop the search if we have exceeded the totalTime
if (elapsedTime > totalTime)
{
// If we are allowed to ponder do not stop the search now but
// keep pondering until the GUI sends "ponderhit" or "stop".
if (mainThread->ponder)
mainThread->stopOnPonderhit = true;
else
threads.stop = true;
}
else
threads.increaseDepth = mainThread->ponder || elapsedTime <= totalTime * 0.506;
}
mainThread->iterValue[iterIdx] = bestValue;
iterIdx = (iterIdx + 1) & 3;
}
if (!mainThread)
return;
mainThread->previousTimeReduction = timeReduction;
// If the skill level is enabled, swap the best PV line with the sub-optimal one
if (skill.enabled())
std::swap(rootMoves[0],
*std::find(rootMoves.begin(), rootMoves.end(),
skill.best ? skill.best : skill.pick_best(rootMoves, multiPV)));
}
// Reset histories, usually before a new game
void Search::Worker::clear() {
mainHistory.fill(0);
lowPlyHistory.fill(0);
captureHistory.fill(-758);
pawnHistory.fill(-1158);
pawnCorrectionHistory.fill(0);
majorPieceCorrectionHistory.fill(0);
minorPieceCorrectionHistory.fill(0);
nonPawnCorrectionHistory[WHITE].fill(0);
nonPawnCorrectionHistory[BLACK].fill(0);
for (auto& to : continuationCorrectionHistory)
for (auto& h : to)
h->fill(0);
for (bool inCheck : {false, true})
for (StatsType c : {NoCaptures, Captures})
for (auto& to : continuationHistory[inCheck][c])
for (auto& h : to)
h->fill(-645);
for (size_t i = 1; i < reductions.size(); ++i)
reductions[i] = int((19.43 + std::log(size_t(options["Threads"])) / 2) * std::log(i));
refreshTable.clear(networks[numaAccessToken]);
}
// Main search function for both PV and non-PV nodes
template<NodeType nodeType>
Value Search::Worker::search(
Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode) {
constexpr bool PvNode = nodeType != NonPV;
constexpr bool rootNode = nodeType == Root;
const bool allNode = !(PvNode || cutNode);
// Dive into quiescence search when the depth reaches zero
if (depth <= 0)
return qsearch < PvNode ? PV : NonPV > (pos, ss, alpha, beta);
// Limit the depth if extensions made it too large
depth = std::min(depth, MAX_PLY - 1);
// Check if we have an upcoming move that draws by repetition
if (!rootNode && alpha < VALUE_DRAW && pos.upcoming_repetition(ss->ply))
{
alpha = value_draw(this->nodes);
if (alpha >= beta)
return alpha;
}
assert(-VALUE_INFINITE <= alpha && alpha < beta && beta <= VALUE_INFINITE);
assert(PvNode || (alpha == beta - 1));
assert(0 < depth && depth < MAX_PLY);
assert(!(PvNode && cutNode));
Move pv[MAX_PLY + 1];
StateInfo st;
ASSERT_ALIGNED(&st, Eval::NNUE::CacheLineSize);
Key posKey;
Move move, excludedMove, bestMove;
Depth extension, newDepth;
Value bestValue, value, eval, maxValue, probCutBeta;
bool givesCheck, improving, priorCapture, opponentWorsening;
bool capture, ttCapture;
Piece movedPiece;
ValueList<Move, 32> capturesSearched;
ValueList<Move, 32> quietsSearched;
// Step 1. Initialize node
Worker* thisThread = this;
ss->inCheck = pos.checkers();
priorCapture = pos.captured_piece();
Color us = pos.side_to_move();
ss->moveCount = 0;
bestValue = -VALUE_INFINITE;
maxValue = VALUE_INFINITE;
// Check for the available remaining time
if (is_mainthread())
main_manager()->check_time(*thisThread);
// Used to send selDepth info to GUI (selDepth counts from 1, ply from 0)
if (PvNode && thisThread->selDepth < ss->ply + 1)
thisThread->selDepth = ss->ply + 1;
if (!rootNode)
{
// Step 2. Check for aborted search and immediate draw
if (threads.stop.load(std::memory_order_relaxed) || pos.is_draw(ss->ply)
|| ss->ply >= MAX_PLY)
return (ss->ply >= MAX_PLY && !ss->inCheck)
? evaluate(networks[numaAccessToken], pos, refreshTable,
thisThread->optimism[us])
: value_draw(thisThread->nodes);
// Step 3. Mate distance pruning. Even if we mate at the next move our score
// would be at best mate_in(ss->ply + 1), but if alpha is already bigger because
// a shorter mate was found upward in the tree then there is no need to search
// because we will never beat the current alpha. Same logic but with reversed
// signs apply also in the opposite condition of being mated instead of giving
// mate. In this case, return a fail-high score.
alpha = std::max(mated_in(ss->ply), alpha);
beta = std::min(mate_in(ss->ply + 1), beta);
if (alpha >= beta)
return alpha;
}
assert(0 <= ss->ply && ss->ply < MAX_PLY);
bestMove = Move::none();
(ss + 2)->cutoffCnt = 0;
Square prevSq = ((ss - 1)->currentMove).is_ok() ? ((ss - 1)->currentMove).to_sq() : SQ_NONE;
ss->statScore = 0;
// Step 4. Transposition table lookup
excludedMove = ss->excludedMove;
posKey = pos.key();
auto [ttHit, ttData, ttWriter] = tt.probe(posKey);
// Need further processing of the saved data
ss->ttHit = ttHit;
ttData.move = rootNode ? thisThread->rootMoves[thisThread->pvIdx].pv[0]
: ttHit ? ttData.move
: Move::none();
ttData.value = ttHit ? value_from_tt(ttData.value, ss->ply, pos.rule50_count()) : VALUE_NONE;
ss->ttPv = excludedMove ? ss->ttPv : PvNode || (ttHit && ttData.is_pv);
ttCapture = ttData.move && pos.capture_stage(ttData.move);
// At this point, if excluded, skip straight to step 6, static eval. However,
// to save indentation, we list the condition in all code between here and there.
// At non-PV nodes we check for an early TT cutoff
if (!PvNode && !excludedMove && ttData.depth > depth - (ttData.value <= beta)
&& ttData.value != VALUE_NONE // Can happen when !ttHit or when access race in probe()
&& (ttData.bound & (ttData.value >= beta ? BOUND_LOWER : BOUND_UPPER))
&& (cutNode == (ttData.value >= beta) || depth > 8))
{
// If ttMove is quiet, update move sorting heuristics on TT hit (~2 Elo)
if (ttData.move && ttData.value >= beta)
{
// Bonus for a quiet ttMove that fails high (~2 Elo)
if (!ttCapture)
update_quiet_histories(pos, ss, *this, ttData.move, stat_bonus(depth));
// Extra penalty for early quiet moves of
// the previous ply (~1 Elo on STC, ~2 Elo on LTC)
if (prevSq != SQ_NONE && (ss - 1)->moveCount <= 2 && !priorCapture)
update_continuation_histories(ss - 1, pos.piece_on(prevSq), prevSq,
-stat_malus(depth + 1));
}
// Partial workaround for the graph history interaction problem
// For high rule50 counts don't produce transposition table cutoffs.
if (pos.rule50_count() < 90)
return ttData.value;
}
// Step 5. Tablebases probe
if (!rootNode && !excludedMove && tbConfig.cardinality)
{
int piecesCount = pos.count<ALL_PIECES>();
if (piecesCount <= tbConfig.cardinality
&& (piecesCount < tbConfig.cardinality || depth >= tbConfig.probeDepth)
&& pos.rule50_count() == 0 && !pos.can_castle(ANY_CASTLING))
{
TB::ProbeState err;
TB::WDLScore wdl = Tablebases::probe_wdl(pos, &err);
// Force check of time on the next occasion
if (is_mainthread())
main_manager()->callsCnt = 0;
if (err != TB::ProbeState::FAIL)
{
thisThread->tbHits.fetch_add(1, std::memory_order_relaxed);
int drawScore = tbConfig.useRule50 ? 1 : 0;
Value tbValue = VALUE_TB - ss->ply;
// Use the range VALUE_TB to VALUE_TB_WIN_IN_MAX_PLY to score
value = wdl < -drawScore ? -tbValue
: wdl > drawScore ? tbValue
: VALUE_DRAW + 2 * wdl * drawScore;
Bound b = wdl < -drawScore ? BOUND_UPPER
: wdl > drawScore ? BOUND_LOWER
: BOUND_EXACT;
if (b == BOUND_EXACT || (b == BOUND_LOWER ? value >= beta : value <= alpha))
{
ttWriter.write(posKey, value_to_tt(value, ss->ply), ss->ttPv, b,
std::min(MAX_PLY - 1, depth + 6), Move::none(), VALUE_NONE,
tt.generation());
return value;
}
if (PvNode)
{
if (b == BOUND_LOWER)
bestValue = value, alpha = std::max(alpha, bestValue);
else
maxValue = value;
}
}
}
}
// Step 6. Static evaluation of the position
Value unadjustedStaticEval = VALUE_NONE;
if (ss->inCheck)
{
// Skip early pruning when in check
ss->staticEval = eval = (ss - 2)->staticEval;
improving = false;
goto moves_loop;
}
else if (excludedMove)
{
// Providing the hint that this node's accumulator will be used often
// brings significant Elo gain (~13 Elo).
Eval::NNUE::hint_common_parent_position(pos, networks[numaAccessToken], refreshTable);
unadjustedStaticEval = eval = ss->staticEval;
}
else if (ss->ttHit)
{
// Never assume anything about values stored in TT
unadjustedStaticEval = ttData.eval;
if (unadjustedStaticEval == VALUE_NONE)
unadjustedStaticEval =
evaluate(networks[numaAccessToken], pos, refreshTable, thisThread->optimism[us]);
else if (PvNode)
Eval::NNUE::hint_common_parent_position(pos, networks[numaAccessToken], refreshTable);
ss->staticEval = eval =
to_corrected_static_eval(unadjustedStaticEval, *thisThread, pos, ss);
// ttValue can be used as a better position evaluation (~7 Elo)
if (ttData.value != VALUE_NONE
&& (ttData.bound & (ttData.value > eval ? BOUND_LOWER : BOUND_UPPER)))
eval = ttData.value;
}
else
{
unadjustedStaticEval =
evaluate(networks[numaAccessToken], pos, refreshTable, thisThread->optimism[us]);
ss->staticEval = eval =
to_corrected_static_eval(unadjustedStaticEval, *thisThread, pos, ss);
// Static evaluation is saved as it was before adjustment by correction history
ttWriter.write(posKey, VALUE_NONE, ss->ttPv, BOUND_NONE, DEPTH_UNSEARCHED, Move::none(),
unadjustedStaticEval, tt.generation());
}
// Use static evaluation difference to improve quiet move ordering (~9 Elo)
if (((ss - 1)->currentMove).is_ok() && !(ss - 1)->inCheck && !priorCapture)
{
int bonus = std::clamp(-10 * int((ss - 1)->staticEval + ss->staticEval), -1831, 1428) + 623;
thisThread->mainHistory[~us][((ss - 1)->currentMove).from_to()] << bonus;
if (type_of(pos.piece_on(prevSq)) != PAWN && ((ss - 1)->currentMove).type_of() != PROMOTION)
thisThread->pawnHistory[pawn_structure_index(pos)][pos.piece_on(prevSq)][prevSq]
<< bonus / 2;
}
// Set up the improving flag, which is true if current static evaluation is
// bigger than the previous static evaluation at our turn (if we were in
// check at our previous move we go back until we weren't in check) and is
// false otherwise. The improving flag is used in various pruning heuristics.
improving = ss->staticEval > (ss - 2)->staticEval;
opponentWorsening = ss->staticEval + (ss - 1)->staticEval > 2;
// Step 7. Razoring (~1 Elo)
// If eval is really low, check with qsearch if we can exceed alpha. If the
// search suggests we cannot exceed alpha, return a speculative fail low.
if (eval < alpha - 469 - 307 * depth * depth)
{
value = qsearch<NonPV>(pos, ss, alpha - 1, alpha);
if (value < alpha && std::abs(value) < VALUE_TB_WIN_IN_MAX_PLY)
return value;
}
// Step 8. Futility pruning: child node (~40 Elo)
// The depth condition is important for mate finding.
if (!ss->ttPv && depth < 14
&& eval - futility_margin(depth, cutNode && !ss->ttHit, improving, opponentWorsening)
- (ss - 1)->statScore / 290
>= beta
&& eval >= beta && (!ttData.move || ttCapture) && beta > VALUE_TB_LOSS_IN_MAX_PLY
&& eval < VALUE_TB_WIN_IN_MAX_PLY)
return beta + (eval - beta) / 3;
improving |= ss->staticEval >= beta + 100;
// Step 9. Null move search with verification search (~35 Elo)
if (cutNode && (ss - 1)->currentMove != Move::null() && eval >= beta
&& ss->staticEval >= beta - 21 * depth + 421 && !excludedMove && pos.non_pawn_material(us)
&& ss->ply >= thisThread->nmpMinPly && beta > VALUE_TB_LOSS_IN_MAX_PLY)
{
assert(eval - beta >= 0);
// Null move dynamic reduction based on depth and eval
Depth R = std::min(int(eval - beta) / 235, 7) + depth / 3 + 5;
ss->currentMove = Move::null();
ss->continuationHistory = &thisThread->continuationHistory[0][0][NO_PIECE][0];
ss->continuationCorrectionHistory = &thisThread->continuationCorrectionHistory[NO_PIECE][0];
pos.do_null_move(st, tt);
Value nullValue = -search<NonPV>(pos, ss + 1, -beta, -beta + 1, depth - R, false);
pos.undo_null_move();
// Do not return unproven mate or TB scores
if (nullValue >= beta && nullValue < VALUE_TB_WIN_IN_MAX_PLY)
{
if (thisThread->nmpMinPly || depth < 16)
return nullValue;
assert(!thisThread->nmpMinPly); // Recursive verification is not allowed
// Do verification search at high depths, with null move pruning disabled
// until ply exceeds nmpMinPly.
thisThread->nmpMinPly = ss->ply + 3 * (depth - R) / 4;
Value v = search<NonPV>(pos, ss, beta - 1, beta, depth - R, false);
thisThread->nmpMinPly = 0;
if (v >= beta)
return nullValue;
}
}
// Step 10. Internal iterative reductions (~9 Elo)
// For PV nodes without a ttMove, we decrease depth.
if (PvNode && !ttData.move)
depth -= 3;
// Use qsearch if depth <= 0
if (depth <= 0)
return qsearch<PV>(pos, ss, alpha, beta);
// For cutNodes, if depth is high enough, decrease depth by 2 if there is no ttMove,
// or by 1 if there is a ttMove with an upper bound.
if (cutNode && depth >= 7 && (!ttData.move || ttData.bound == BOUND_UPPER))
depth -= 1 + !ttData.move;
// Step 11. ProbCut (~10 Elo)
// If we have a good enough capture (or queen promotion) and a reduced search
// returns a value much above beta, we can (almost) safely prune the previous move.
probCutBeta = beta + 187 - 53 * improving - 27 * opponentWorsening;
if (!PvNode && depth > 3
&& std::abs(beta) < VALUE_TB_WIN_IN_MAX_PLY
// If value from transposition table is lower than probCutBeta, don't attempt
// probCut there and in further interactions with transposition table cutoff
// depth is set to depth - 3 because probCut search has depth set to depth - 4
// but we also do a move before it. So effective depth is equal to depth - 3.
&& !(ttData.depth >= depth - 3 && ttData.value != VALUE_NONE && ttData.value < probCutBeta))
{
assert(probCutBeta < VALUE_INFINITE && probCutBeta > beta);
MovePicker mp(pos, ttData.move, probCutBeta - ss->staticEval, &thisThread->captureHistory);
Piece captured;
while ((move = mp.next_move()) != Move::none())
{
assert(move.is_ok());
if (move == excludedMove)
continue;
if (!pos.legal(move))
continue;
assert(pos.capture_stage(move));
movedPiece = pos.moved_piece(move);
captured = pos.piece_on(move.to_sq());
// Prefetch the TT entry for the resulting position
prefetch(tt.first_entry(pos.key_after(move)));
ss->currentMove = move;
ss->continuationHistory =
&this->continuationHistory[ss->inCheck][true][pos.moved_piece(move)][move.to_sq()];
ss->continuationCorrectionHistory =
&this->continuationCorrectionHistory[pos.moved_piece(move)][move.to_sq()];
thisThread->nodes.fetch_add(1, std::memory_order_relaxed);
pos.do_move(move, st);
// Perform a preliminary qsearch to verify that the move holds
value = -qsearch<NonPV>(pos, ss + 1, -probCutBeta, -probCutBeta + 1);
// If the qsearch held, perform the regular search
if (value >= probCutBeta)
value =
-search<NonPV>(pos, ss + 1, -probCutBeta, -probCutBeta + 1, depth - 4, !cutNode);
pos.undo_move(move);
if (value >= probCutBeta)
{
thisThread->captureHistory[movedPiece][move.to_sq()][type_of(captured)]
<< stat_bonus(depth - 2);
// Save ProbCut data into transposition table
ttWriter.write(posKey, value_to_tt(value, ss->ply), ss->ttPv, BOUND_LOWER,
depth - 3, move, unadjustedStaticEval, tt.generation());
return std::abs(value) < VALUE_TB_WIN_IN_MAX_PLY ? value - (probCutBeta - beta)
: value;
}
}
Eval::NNUE::hint_common_parent_position(pos, networks[numaAccessToken], refreshTable);
}
moves_loop: // When in check, search starts here
// Step 12. A small Probcut idea (~4 Elo)
probCutBeta = beta + 417;
if ((ttData.bound & BOUND_LOWER) && ttData.depth >= depth - 4 && ttData.value >= probCutBeta
&& std::abs(beta) < VALUE_TB_WIN_IN_MAX_PLY
&& std::abs(ttData.value) < VALUE_TB_WIN_IN_MAX_PLY)
return probCutBeta;
const PieceToHistory* contHist[] = {(ss - 1)->continuationHistory,
(ss - 2)->continuationHistory,
(ss - 3)->continuationHistory,
(ss - 4)->continuationHistory,
nullptr,
(ss - 6)->continuationHistory};
MovePicker mp(pos, ttData.move, depth, &thisThread->mainHistory, &thisThread->lowPlyHistory,
&thisThread->captureHistory, contHist, &thisThread->pawnHistory, ss->ply);
value = bestValue;
int moveCount = 0;
// Step 13. Loop through all pseudo-legal moves until no moves remain
// or a beta cutoff occurs.
while ((move = mp.next_move()) != Move::none())
{
assert(move.is_ok());
if (move == excludedMove)
continue;
// Check for legality
if (!pos.legal(move))
continue;
// At root obey the "searchmoves" option and skip moves not listed in Root
// Move List. In MultiPV mode we also skip PV moves that have been already
// searched and those of lower "TB rank" if we are in a TB root position.
if (rootNode
&& !std::count(thisThread->rootMoves.begin() + thisThread->pvIdx,
thisThread->rootMoves.begin() + thisThread->pvLast, move))
continue;
ss->moveCount = ++moveCount;
if (rootNode && is_mainthread() && nodes > 10000000)
{
main_manager()->updates.onIter(
{depth, UCIEngine::move(move, pos.is_chess960()), moveCount + thisThread->pvIdx});
}
if (PvNode)
(ss + 1)->pv = nullptr;
extension = 0;
capture = pos.capture_stage(move);
movedPiece = pos.moved_piece(move);
givesCheck = pos.gives_check(move);
// Calculate new depth for this move
newDepth = depth - 1;
int delta = beta - alpha;
Depth r = reduction(improving, depth, moveCount, delta);
// Step 14. Pruning at shallow depth (~120 Elo).
// Depth conditions are important for mate finding.
if (!rootNode && pos.non_pawn_material(us) && bestValue > VALUE_TB_LOSS_IN_MAX_PLY)
{
// Skip quiet moves if movecount exceeds our FutilityMoveCount threshold (~8 Elo)
if (moveCount >= futility_move_count(improving, depth))
mp.skip_quiet_moves();
// Reduced depth of the next LMR search
int lmrDepth = newDepth - r / 1024;
if (capture || givesCheck)
{
Piece capturedPiece = pos.piece_on(move.to_sq());
int captHist =
thisThread->captureHistory[movedPiece][move.to_sq()][type_of(capturedPiece)];
// Futility pruning for captures (~2 Elo)
if (!givesCheck && lmrDepth < 7 && !ss->inCheck)
{
Value futilityValue = ss->staticEval + 287 + 253 * lmrDepth
+ PieceValue[capturedPiece] + captHist / 7;
if (futilityValue <= alpha)
continue;
}
// SEE based pruning for captures and checks (~11 Elo)
int seeHist = std::clamp(captHist / 33, -161 * depth, 156 * depth);
if (!pos.see_ge(move, -162 * depth - seeHist))
continue;
}
else
{
int history =
(*contHist[0])[movedPiece][move.to_sq()]
+ (*contHist[1])[movedPiece][move.to_sq()]
+ thisThread->pawnHistory[pawn_structure_index(pos)][movedPiece][move.to_sq()];
// Continuation history based pruning (~2 Elo)
if (history < -3884 * depth)
continue;
history += 2 * thisThread->mainHistory[us][move.from_to()];
lmrDepth += history / 3609;
Value futilityValue =
ss->staticEval + (bestValue < ss->staticEval - 45 ? 140 : 43) + 141 * lmrDepth;
// Futility pruning: parent node (~13 Elo)
if (!ss->inCheck && lmrDepth < 12 && futilityValue <= alpha)
{
if (bestValue <= futilityValue && std::abs(bestValue) < VALUE_TB_WIN_IN_MAX_PLY
&& futilityValue < VALUE_TB_WIN_IN_MAX_PLY)
bestValue = futilityValue;
continue;
}
lmrDepth = std::max(lmrDepth, 0);
// Prune moves with negative SEE (~4 Elo)
if (!pos.see_ge(move, -25 * lmrDepth * lmrDepth))
continue;
}
}
// Step 15. Extensions (~100 Elo)
// We take care to not overdo to avoid search getting stuck.
if (ss->ply < thisThread->rootDepth * 2)
{
// Singular extension search (~76 Elo, ~170 nElo). If all moves but one
// fail low on a search of (alpha-s, beta-s), and just one fails high on
// (alpha, beta), then that move is singular and should be extended. To
// verify this we do a reduced search on the position excluding the ttMove
// and if the result is lower than ttValue minus a margin, then we will
// extend the ttMove. Recursive singular search is avoided.
// Note: the depth margin and singularBeta margin are known for having
// non-linear scaling. Their values are optimized to time controls of
// 180+1.8 and longer so changing them requires tests at these types of
// time controls. Generally, higher singularBeta (i.e closer to ttValue)
// and lower extension margins scale well.
if (!rootNode && move == ttData.move && !excludedMove
&& depth >= 4 - (thisThread->completedDepth > 33) + ss->ttPv
&& std::abs(ttData.value) < VALUE_TB_WIN_IN_MAX_PLY && (ttData.bound & BOUND_LOWER)
&& ttData.depth >= depth - 3)
{
Value singularBeta = ttData.value - (56 + 79 * (ss->ttPv && !PvNode)) * depth / 64;
Depth singularDepth = newDepth / 2;
ss->excludedMove = move;
value =
search<NonPV>(pos, ss, singularBeta - 1, singularBeta, singularDepth, cutNode);
ss->excludedMove = Move::none();
if (value < singularBeta)
{
int doubleMargin = 249 * PvNode - 194 * !ttCapture;
int tripleMargin = 94 + 287 * PvNode - 249 * !ttCapture + 99 * ss->ttPv;
extension = 1 + (value < singularBeta - doubleMargin)
+ (value < singularBeta - tripleMargin);
depth += ((!PvNode) && (depth < 14));
}
// Multi-cut pruning
// Our ttMove is assumed to fail high based on the bound of the TT entry,
// and if after excluding the ttMove with a reduced search we fail high
// over the original beta, we assume this expected cut-node is not
// singular (multiple moves fail high), and we can prune the whole
// subtree by returning a softbound.
else if (value >= beta && std::abs(value) < VALUE_TB_WIN_IN_MAX_PLY)
return value;
// Negative extensions
// If other moves failed high over (ttValue - margin) without the
// ttMove on a reduced search, but we cannot do multi-cut because
// (ttValue - margin) is lower than the original beta, we do not know
// if the ttMove is singular or can do a multi-cut, so we reduce the
// ttMove in favor of other moves based on some conditions:
// If the ttMove is assumed to fail high over current beta (~7 Elo)
else if (ttData.value >= beta)
extension = -3;
// If we are on a cutNode but the ttMove is not assumed to fail high
// over current beta (~1 Elo)
else if (cutNode)
extension = -2;
}
// Extension for capturing the previous moved piece (~1 Elo at LTC)
else if (PvNode && move.to_sq() == prevSq
&& thisThread->captureHistory[movedPiece][move.to_sq()]
[type_of(pos.piece_on(move.to_sq()))]
> 4321)
extension = 1;
}
// Add extension to new depth
newDepth += extension;
// Speculative prefetch as early as possible
prefetch(tt.first_entry(pos.key_after(move)));
// Update the current move (this must be done after singular extension search)
ss->currentMove = move;
ss->continuationHistory =
&thisThread->continuationHistory[ss->inCheck][capture][movedPiece][move.to_sq()];
ss->continuationCorrectionHistory =
&thisThread->continuationCorrectionHistory[movedPiece][move.to_sq()];
uint64_t nodeCount = rootNode ? uint64_t(nodes) : 0;
// Step 16. Make the move
thisThread->nodes.fetch_add(1, std::memory_order_relaxed);
pos.do_move(move, st, givesCheck);
// These reduction adjustments have proven non-linear scaling.
// They are optimized to time controls of 180 + 1.8 and longer,
// so changing them or adding conditions that are similar requires
// tests at these types of time controls.
// Decrease reduction if position is or has been on the PV (~7 Elo)
if (ss->ttPv)
r -= 1024 + (ttData.value > alpha) * 1024 + (ttData.depth >= depth) * 1024;
// Decrease reduction for PvNodes (~0 Elo on STC, ~2 Elo on LTC)
if (PvNode)
r -= 1024;
// These reduction adjustments have no proven non-linear scaling
// Increase reduction for cut nodes (~4 Elo)
if (cutNode)
r += 2518 - (ttData.depth >= depth && ss->ttPv) * 991;
// Increase reduction if ttMove is a capture but the current move is not a capture (~3 Elo)
if (ttCapture && !capture)
r += 1043 + (depth < 8) * 999;
// Increase reduction if next ply has a lot of fail high (~5 Elo)
if ((ss + 1)->cutoffCnt > 3)
r += 938 + allNode * 960;
// For first picked move (ttMove) reduce reduction (~3 Elo)
else if (move == ttData.move)
r -= 1879;
if (capture)
ss->statScore =
thisThread->captureHistory[movedPiece][move.to_sq()][type_of(pos.captured_piece())]
- 13000;
else
ss->statScore = 2 * thisThread->mainHistory[us][move.from_to()]
+ (*contHist[0])[movedPiece][move.to_sq()]
+ (*contHist[1])[movedPiece][move.to_sq()] - 3996;
// Decrease/increase reduction for moves with a good/bad history (~8 Elo)
r -= ss->statScore * 1287 / 16384;
// Step 17. Late moves reduction / extension (LMR, ~117 Elo)
if (depth >= 2 && moveCount > 1)
{
// In general we want to cap the LMR depth search at newDepth, but when
// reduction is negative, we allow this move a limited search extension
// beyond the first move depth.
// To prevent problems when the max value is less than the min value,
// std::clamp has been replaced by a more robust implementation.
Depth d = std::max(1, std::min(newDepth - r / 1024, newDepth + !allNode));
value = -search<NonPV>(pos, ss + 1, -(alpha + 1), -alpha, d, true);
// Do a full-depth search when reduced LMR search fails high
if (value > alpha && d < newDepth)
{
// Adjust full-depth search based on LMR results - if the result was
// good enough search deeper, if it was bad enough search shallower.
const bool doDeeperSearch = value > (bestValue + 42 + 2 * newDepth); // (~1 Elo)
const bool doShallowerSearch = value < bestValue + 10; // (~2 Elo)
newDepth += doDeeperSearch - doShallowerSearch;
if (newDepth > d)
value = -search<NonPV>(pos, ss + 1, -(alpha + 1), -alpha, newDepth, !cutNode);
// Post LMR continuation history updates (~1 Elo)
int bonus = 2 * (value >= beta) * stat_bonus(newDepth);
update_continuation_histories(ss, movedPiece, move.to_sq(), bonus);
}
}
// Step 18. Full-depth search when LMR is skipped
else if (!PvNode || moveCount > 1)
{
// Increase reduction if ttMove is not present (~6 Elo)
if (!ttData.move)
r += 2037;
// Note that if expected reduction is high, we reduce search depth by 1 here (~9 Elo)
value =
-search<NonPV>(pos, ss + 1, -(alpha + 1), -alpha, newDepth - (r > 2983), !cutNode);
}
// For PV nodes only, do a full PV search on the first move or after a fail high,
// otherwise let the parent node fail low with value <= alpha and try another move.
if (PvNode && (moveCount == 1 || value > alpha))
{
(ss + 1)->pv = pv;
(ss + 1)->pv[0] = Move::none();
// Extend move from transposition table if we are about to dive into qsearch.
if (move == ttData.move && ss->ply <= thisThread->rootDepth * 2)
newDepth = std::max(newDepth, 1);
value = -search<PV>(pos, ss + 1, -beta, -alpha, newDepth, false);
}
// Step 19. Undo move
pos.undo_move(move);
assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
// Step 20. Check for a new best move
// Finished searching the move. If a stop occurred, the return value of
// the search cannot be trusted, and we return immediately without updating
// best move, principal variation nor transposition table.
if (threads.stop.load(std::memory_order_relaxed))
return VALUE_ZERO;
if (rootNode)
{
RootMove& rm =
*std::find(thisThread->rootMoves.begin(), thisThread->rootMoves.end(), move);
rm.effort += nodes - nodeCount;
rm.averageScore =
rm.averageScore != -VALUE_INFINITE ? (value + rm.averageScore) / 2 : value;
rm.meanSquaredScore = rm.meanSquaredScore != -VALUE_INFINITE * VALUE_INFINITE
? (value * std::abs(value) + rm.meanSquaredScore) / 2
: value * std::abs(value);
// PV move or new best move?
if (moveCount == 1 || value > alpha)
{
rm.score = rm.uciScore = value;
rm.selDepth = thisThread->selDepth;
rm.scoreLowerbound = rm.scoreUpperbound = false;
if (value >= beta)
{
rm.scoreLowerbound = true;
rm.uciScore = beta;
}
else if (value <= alpha)
{
rm.scoreUpperbound = true;
rm.uciScore = alpha;
}
rm.pv.resize(1);
assert((ss + 1)->pv);
for (Move* m = (ss + 1)->pv; *m != Move::none(); ++m)
rm.pv.push_back(*m);
// We record how often the best move has been changed in each iteration.
// This information is used for time management. In MultiPV mode,
// we must take care to only do this for the first PV line.
if (moveCount > 1 && !thisThread->pvIdx)
++thisThread->bestMoveChanges;
}
else
// All other moves but the PV, are set to the lowest value: this
// is not a problem when sorting because the sort is stable and the
// move position in the list is preserved - just the PV is pushed up.
rm.score = -VALUE_INFINITE;
}
// In case we have an alternative move equal in eval to the current bestmove,
// promote it to bestmove by pretending it just exceeds alpha (but not beta).
int inc =
(value == bestValue && (int(nodes) & 15) == 0 && ss->ply + 2 >= thisThread->rootDepth
&& std::abs(value) + 1 < VALUE_TB_WIN_IN_MAX_PLY);
if (value + inc > bestValue)
{
bestValue = value;
if (value + inc > alpha)
{
bestMove = move;
if (PvNode && !rootNode) // Update pv even in fail-high case
update_pv(ss->pv, move, (ss + 1)->pv);
if (value >= beta)
{
ss->cutoffCnt += !ttData.move + (extension < 2);
assert(value >= beta); // Fail high
break;
}
else
{
// Reduce other moves if we have found at least one score improvement (~2 Elo)
if (depth > 2 && depth < 14 && std::abs(value) < VALUE_TB_WIN_IN_MAX_PLY)
depth -= 2;
assert(depth > 0);
alpha = value; // Update alpha! Always alpha < beta
}
}
}
// If the move is worse than some previously searched move,
// remember it, to update its stats later.
if (move != bestMove && moveCount <= 32)
{
if (capture)
capturesSearched.push_back(move);
else
quietsSearched.push_back(move);
}
}
// Step 21. Check for mate and stalemate
// All legal moves have been searched and if there are no legal moves, it
// must be a mate or a stalemate. If we are in a singular extension search then
// return a fail low score.
assert(moveCount || !ss->inCheck || excludedMove || !MoveList<LEGAL>(pos).size());
// Adjust best value for fail high cases at non-pv nodes
if (!PvNode && bestValue >= beta && std::abs(bestValue) < VALUE_TB_WIN_IN_MAX_PLY
&& std::abs(beta) < VALUE_TB_WIN_IN_MAX_PLY && std::abs(alpha) < VALUE_TB_WIN_IN_MAX_PLY)
bestValue = (bestValue * depth + beta) / (depth + 1);
if (!moveCount)
bestValue = excludedMove ? alpha : ss->inCheck ? mated_in(ss->ply) : VALUE_DRAW;
// If there is a move that produces search value greater than alpha,
// we update the stats of searched moves.
else if (bestMove)
update_all_stats(pos, ss, *this, bestMove, prevSq, quietsSearched, capturesSearched, depth);
// Bonus for prior countermove that caused the fail low
else if (!priorCapture && prevSq != SQ_NONE)
{
int bonus = (117 * (depth > 5) + 39 * !allNode + 168 * ((ss - 1)->moveCount > 8)
+ 115 * (!ss->inCheck && bestValue <= ss->staticEval - 108)
+ 119 * (!(ss - 1)->inCheck && bestValue <= -(ss - 1)->staticEval - 83));
// Proportional to "how much damage we have to undo"
bonus += std::min(-(ss - 1)->statScore / 113, 300);
bonus = std::max(bonus, 0);
update_continuation_histories(ss - 1, pos.piece_on(prevSq), prevSq,
stat_bonus(depth) * bonus / 93);
thisThread->mainHistory[~us][((ss - 1)->currentMove).from_to()]
<< stat_bonus(depth) * bonus / 179;
if (type_of(pos.piece_on(prevSq)) != PAWN && ((ss - 1)->currentMove).type_of() != PROMOTION)
thisThread->pawnHistory[pawn_structure_index(pos)][pos.piece_on(prevSq)][prevSq]
<< stat_bonus(depth) * bonus / 24;
}
// Bonus when search fails low and there is a TT move
else if (ttData.move && !allNode)
thisThread->mainHistory[us][ttData.move.from_to()] << stat_bonus(depth) * 23 / 100;
if (PvNode)
bestValue = std::min(bestValue, maxValue);
// If no good move is found and the previous position was ttPv, then the previous
// opponent move is probably good and the new position is added to the search tree. (~7 Elo)
if (bestValue <= alpha)
ss->ttPv = ss->ttPv || ((ss - 1)->ttPv && depth > 3);
// Write gathered information in transposition table. Note that the
// static evaluation is saved as it was before correction history.
if (!excludedMove && !(rootNode && thisThread->pvIdx))
ttWriter.write(posKey, value_to_tt(bestValue, ss->ply), ss->ttPv,
bestValue >= beta ? BOUND_LOWER
: PvNode && bestMove ? BOUND_EXACT
: BOUND_UPPER,
depth, bestMove, unadjustedStaticEval, tt.generation());
// Adjust correction history
if (!ss->inCheck && (!bestMove || !pos.capture(bestMove))
&& !(bestValue >= beta && bestValue <= ss->staticEval)
&& !(!bestMove && bestValue >= ss->staticEval))
{
const auto m = (ss - 1)->currentMove;
auto bonus = std::clamp(int(bestValue - ss->staticEval) * depth / 8,
-CORRECTION_HISTORY_LIMIT / 4, CORRECTION_HISTORY_LIMIT / 4);
thisThread->pawnCorrectionHistory[us][pawn_structure_index<Correction>(pos)]
<< bonus * 107 / 128;
thisThread->majorPieceCorrectionHistory[us][major_piece_index(pos)] << bonus * 162 / 128;
thisThread->minorPieceCorrectionHistory[us][minor_piece_index(pos)] << bonus * 148 / 128;
thisThread->nonPawnCorrectionHistory[WHITE][us][non_pawn_index<WHITE>(pos)]
<< bonus * 122 / 128;
thisThread->nonPawnCorrectionHistory[BLACK][us][non_pawn_index<BLACK>(pos)]
<< bonus * 185 / 128;
if (m.is_ok())
(*(ss - 2)->continuationCorrectionHistory)[pos.piece_on(m.to_sq())][m.to_sq()] << bonus;
}
assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
return bestValue;
}
// Quiescence search function, which is called by the main search function with
// depth zero, or recursively with further decreasing depth. With depth <= 0, we
// "should" be using static eval only, but tactical moves may confuse the static eval.
// To fight this horizon effect, we implement this qsearch of tactical moves (~155 Elo).
// See https://www.chessprogramming.org/Horizon_Effect
// and https://www.chessprogramming.org/Quiescence_Search
template<NodeType nodeType>
Value Search::Worker::qsearch(Position& pos, Stack* ss, Value alpha, Value beta) {
static_assert(nodeType != Root);
constexpr bool PvNode = nodeType == PV;
assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
assert(PvNode || (alpha == beta - 1));
// Check if we have an upcoming move that draws by repetition (~1 Elo)
if (alpha < VALUE_DRAW && pos.upcoming_repetition(ss->ply))
{
alpha = value_draw(this->nodes);
if (alpha >= beta)
return alpha;
}
Move pv[MAX_PLY + 1];
StateInfo st;
ASSERT_ALIGNED(&st, Eval::NNUE::CacheLineSize);
Key posKey;
Move move, bestMove;
Value bestValue, value, futilityBase;
bool pvHit, givesCheck, capture;
int moveCount;
Color us = pos.side_to_move();
// Step 1. Initialize node
if (PvNode)
{
(ss + 1)->pv = pv;
ss->pv[0] = Move::none();
}
Worker* thisThread = this;
bestMove = Move::none();
ss->inCheck = pos.checkers();
moveCount = 0;
// Used to send selDepth info to GUI (selDepth counts from 1, ply from 0)
if (PvNode && thisThread->selDepth < ss->ply + 1)
thisThread->selDepth = ss->ply + 1;
// Step 2. Check for an immediate draw or maximum ply reached
if (pos.is_draw(ss->ply) || ss->ply >= MAX_PLY)
return (ss->ply >= MAX_PLY && !ss->inCheck)
? evaluate(networks[numaAccessToken], pos, refreshTable, thisThread->optimism[us])
: VALUE_DRAW;
assert(0 <= ss->ply && ss->ply < MAX_PLY);
// Step 3. Transposition table lookup
posKey = pos.key();
auto [ttHit, ttData, ttWriter] = tt.probe(posKey);
// Need further processing of the saved data
ss->ttHit = ttHit;
ttData.move = ttHit ? ttData.move : Move::none();
ttData.value = ttHit ? value_from_tt(ttData.value, ss->ply, pos.rule50_count()) : VALUE_NONE;
pvHit = ttHit && ttData.is_pv;
// At non-PV nodes we check for an early TT cutoff
if (!PvNode && ttData.depth >= DEPTH_QS
&& ttData.value != VALUE_NONE // Can happen when !ttHit or when access race in probe()
&& (ttData.bound & (ttData.value >= beta ? BOUND_LOWER : BOUND_UPPER)))
return ttData.value;
// Step 4. Static evaluation of the position
Value unadjustedStaticEval = VALUE_NONE;
if (ss->inCheck)
bestValue = futilityBase = -VALUE_INFINITE;
else
{
if (ss->ttHit)
{
// Never assume anything about values stored in TT
unadjustedStaticEval = ttData.eval;
if (unadjustedStaticEval == VALUE_NONE)
unadjustedStaticEval =
evaluate(networks[numaAccessToken], pos, refreshTable, thisThread->optimism[us]);
ss->staticEval = bestValue =
to_corrected_static_eval(unadjustedStaticEval, *thisThread, pos, ss);
// ttValue can be used as a better position evaluation (~13 Elo)
if (std::abs(ttData.value) < VALUE_TB_WIN_IN_MAX_PLY
&& (ttData.bound & (ttData.value > bestValue ? BOUND_LOWER : BOUND_UPPER)))
bestValue = ttData.value;
}
else
{
// In case of null move search, use previous static eval with opposite sign
unadjustedStaticEval =
(ss - 1)->currentMove != Move::null()
? evaluate(networks[numaAccessToken], pos, refreshTable, thisThread->optimism[us])
: -(ss - 1)->staticEval;
ss->staticEval = bestValue =
to_corrected_static_eval(unadjustedStaticEval, *thisThread, pos, ss);
}
// Stand pat. Return immediately if static value is at least beta
if (bestValue >= beta)
{
if (std::abs(bestValue) < VALUE_TB_WIN_IN_MAX_PLY)
bestValue = (bestValue + beta) / 2;
if (!ss->ttHit)
ttWriter.write(posKey, value_to_tt(bestValue, ss->ply), false, BOUND_LOWER,
DEPTH_UNSEARCHED, Move::none(), unadjustedStaticEval,
tt.generation());
return bestValue;
}
if (bestValue > alpha)
alpha = bestValue;
futilityBase = ss->staticEval + 306;
}
const PieceToHistory* contHist[] = {(ss - 1)->continuationHistory,
(ss - 2)->continuationHistory};
Square prevSq = ((ss - 1)->currentMove).is_ok() ? ((ss - 1)->currentMove).to_sq() : SQ_NONE;
// Initialize a MovePicker object for the current position, and prepare to search
// the moves. We presently use two stages of move generator in quiescence search:
// captures, or evasions only when in check.
MovePicker mp(pos, ttData.move, DEPTH_QS, &thisThread->mainHistory, &thisThread->lowPlyHistory,
&thisThread->captureHistory, contHist, &thisThread->pawnHistory, ss->ply);
// Step 5. Loop through all pseudo-legal moves until no moves remain or a beta
// cutoff occurs.
while ((move = mp.next_move()) != Move::none())
{
assert(move.is_ok());
if (!pos.legal(move))
continue;
givesCheck = pos.gives_check(move);
capture = pos.capture_stage(move);
moveCount++;
// Step 6. Pruning
if (bestValue > VALUE_TB_LOSS_IN_MAX_PLY && pos.non_pawn_material(us))
{
// Futility pruning and moveCount pruning (~10 Elo)
if (!givesCheck && move.to_sq() != prevSq && futilityBase > VALUE_TB_LOSS_IN_MAX_PLY
&& move.type_of() != PROMOTION)
{
if (moveCount > 2)
continue;
Value futilityValue = futilityBase + PieceValue[pos.piece_on(move.to_sq())];
// If static eval + value of piece we are going to capture is
// much lower than alpha, we can prune this move. (~2 Elo)
if (futilityValue <= alpha)
{
bestValue = std::max(bestValue, futilityValue);
continue;
}
// If static exchange evaluation is low enough
// we can prune this move. (~2 Elo)
if (!pos.see_ge(move, alpha - futilityBase))
{
bestValue = std::min(alpha, futilityBase);
continue;
}
}
// Continuation history based pruning (~3 Elo)
if (!capture
&& (*contHist[0])[pos.moved_piece(move)][move.to_sq()]
+ (*contHist[1])[pos.moved_piece(move)][move.to_sq()]
+ thisThread->pawnHistory[pawn_structure_index(pos)][pos.moved_piece(move)]
[move.to_sq()]
<= 5095)
continue;
// Do not search moves with bad enough SEE values (~5 Elo)
if (!pos.see_ge(move, -83))
continue;
}
// Speculative prefetch as early as possible
prefetch(tt.first_entry(pos.key_after(move)));
// Update the current move
ss->currentMove = move;
ss->continuationHistory =
&thisThread
->continuationHistory[ss->inCheck][capture][pos.moved_piece(move)][move.to_sq()];
ss->continuationCorrectionHistory =
&thisThread->continuationCorrectionHistory[pos.moved_piece(move)][move.to_sq()];
// Step 7. Make and search the move
thisThread->nodes.fetch_add(1, std::memory_order_relaxed);
pos.do_move(move, st, givesCheck);
value = -qsearch<nodeType>(pos, ss + 1, -beta, -alpha);
pos.undo_move(move);
assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
// Step 8. Check for a new best move
if (value > bestValue)
{
bestValue = value;
if (value > alpha)
{
bestMove = move;
if (PvNode) // Update pv even in fail-high case
update_pv(ss->pv, move, (ss + 1)->pv);
if (value < beta) // Update alpha here!
alpha = value;
else
break; // Fail high
}
}
}
// Step 9. Check for mate
// All legal moves have been searched. A special case: if we are
// in check and no legal moves were found, it is checkmate.
if (ss->inCheck && bestValue == -VALUE_INFINITE)
{
assert(!MoveList<LEGAL>(pos).size());
return mated_in(ss->ply); // Plies to mate from the root
}
if (std::abs(bestValue) < VALUE_TB_WIN_IN_MAX_PLY && bestValue >= beta)
bestValue = (3 * bestValue + beta) / 4;
// Save gathered info in transposition table. The static evaluation
// is saved as it was before adjustment by correction history.
ttWriter.write(posKey, value_to_tt(bestValue, ss->ply), pvHit,
bestValue >= beta ? BOUND_LOWER : BOUND_UPPER, DEPTH_QS, bestMove,
unadjustedStaticEval, tt.generation());
assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
return bestValue;
}
Depth Search::Worker::reduction(bool i, Depth d, int mn, int delta) const {
int reductionScale = reductions[d] * reductions[mn];
return (reductionScale + 1304 - delta * 814 / rootDelta) + (!i && reductionScale > 1423) * 1135;
}
// elapsed() returns the time elapsed since the search started. If the
// 'nodestime' option is enabled, it will return the count of nodes searched
// instead. This function is called to check whether the search should be
// stopped based on predefined thresholds like time limits or nodes searched.
//
// elapsed_time() returns the actual time elapsed since the start of the search.
// This function is intended for use only when printing PV outputs, and not used
// for making decisions within the search algorithm itself.
TimePoint Search::Worker::elapsed() const {
return main_manager()->tm.elapsed([this]() { return threads.nodes_searched(); });
}
TimePoint Search::Worker::elapsed_time() const { return main_manager()->tm.elapsed_time(); }
namespace {
// Adjusts a mate or TB score from "plies to mate from the root" to
// "plies to mate from the current position". Standard scores are unchanged.
// The function is called before storing a value in the transposition table.
Value value_to_tt(Value v, int ply) {
assert(v != VALUE_NONE);
return v >= VALUE_TB_WIN_IN_MAX_PLY ? v + ply : v <= VALUE_TB_LOSS_IN_MAX_PLY ? v - ply : v;
}
// Inverse of value_to_tt(): it adjusts a mate or TB score from the transposition
// table (which refers to the plies to mate/be mated from current position) to
// "plies to mate/be mated (TB win/loss) from the root". However, to avoid
// potentially false mate or TB scores related to the 50 moves rule and the
// graph history interaction, we return the highest non-TB score instead.
Value value_from_tt(Value v, int ply, int r50c) {
if (v == VALUE_NONE)
return VALUE_NONE;
// handle TB win or better
if (v >= VALUE_TB_WIN_IN_MAX_PLY)
{
// Downgrade a potentially false mate score
if (v >= VALUE_MATE_IN_MAX_PLY && VALUE_MATE - v > 100 - r50c)
return VALUE_TB_WIN_IN_MAX_PLY - 1;
// Downgrade a potentially false TB score.
if (VALUE_TB - v > 100 - r50c)
return VALUE_TB_WIN_IN_MAX_PLY - 1;
return v - ply;
}
// handle TB loss or worse
if (v <= VALUE_TB_LOSS_IN_MAX_PLY)
{
// Downgrade a potentially false mate score.
if (v <= VALUE_MATED_IN_MAX_PLY && VALUE_MATE + v > 100 - r50c)
return VALUE_TB_LOSS_IN_MAX_PLY + 1;
// Downgrade a potentially false TB score.
if (VALUE_TB + v > 100 - r50c)
return VALUE_TB_LOSS_IN_MAX_PLY + 1;
return v + ply;
}
return v;
}
// Adds current move and appends child pv[]
void update_pv(Move* pv, Move move, const Move* childPv) {
for (*pv++ = move; childPv && *childPv != Move::none();)
*pv++ = *childPv++;
*pv = Move::none();
}
// Updates stats at the end of search() when a bestMove is found
void update_all_stats(const Position& pos,
Stack* ss,
Search::Worker& workerThread,
Move bestMove,
Square prevSq,
ValueList<Move, 32>& quietsSearched,
ValueList<Move, 32>& capturesSearched,
Depth depth) {
CapturePieceToHistory& captureHistory = workerThread.captureHistory;
Piece moved_piece = pos.moved_piece(bestMove);
PieceType captured;
int bonus = stat_bonus(depth);
int malus = stat_malus(depth);
if (!pos.capture_stage(bestMove))
{
update_quiet_histories(pos, ss, workerThread, bestMove, bonus);
// Decrease stats for all non-best quiet moves
for (Move move : quietsSearched)
update_quiet_histories(pos, ss, workerThread, move, -malus);
}
else
{
// Increase stats for the best move in case it was a capture move
captured = type_of(pos.piece_on(bestMove.to_sq()));
captureHistory[moved_piece][bestMove.to_sq()][captured] << bonus;
}
// Extra penalty for a quiet early move that was not a TT move in
// previous ply when it gets refuted.
if (prevSq != SQ_NONE && ((ss - 1)->moveCount == 1 + (ss - 1)->ttHit) && !pos.captured_piece())
update_continuation_histories(ss - 1, pos.piece_on(prevSq), prevSq, -malus);
// Decrease stats for all non-best capture moves
for (Move move : capturesSearched)
{
moved_piece = pos.moved_piece(move);
captured = type_of(pos.piece_on(move.to_sq()));
captureHistory[moved_piece][move.to_sq()][captured] << -malus;
}
}
// Updates histories of the move pairs formed by moves
// at ply -1, -2, -3, -4, and -6 with current move.
void update_continuation_histories(Stack* ss, Piece pc, Square to, int bonus) {
bonus = bonus * 50 / 64;
for (int i : {1, 2, 3, 4, 6})
{
// Only update the first 2 continuation histories if we are in check
if (ss->inCheck && i > 2)
break;
if (((ss - i)->currentMove).is_ok())
(*(ss - i)->continuationHistory)[pc][to] << bonus / (1 + (i == 3));
}
}
// Updates move sorting heuristics
void update_quiet_histories(
const Position& pos, Stack* ss, Search::Worker& workerThread, Move move, int bonus) {
Color us = pos.side_to_move();
workerThread.mainHistory[us][move.from_to()] << bonus;
if (ss->ply < LOW_PLY_HISTORY_SIZE)
workerThread.lowPlyHistory[ss->ply][move.from_to()] << bonus;
update_continuation_histories(ss, pos.moved_piece(move), move.to_sq(), bonus);
int pIndex = pawn_structure_index(pos);
workerThread.pawnHistory[pIndex][pos.moved_piece(move)][move.to_sq()] << bonus / 2;
}
}
// When playing with strength handicap, choose the best move among a set of
// RootMoves using a statistical rule dependent on 'level'. Idea by Heinz van Saanen.
Move Skill::pick_best(const RootMoves& rootMoves, size_t multiPV) {
static PRNG rng(now()); // PRNG sequence should be non-deterministic
// RootMoves are already sorted by score in descending order
Value topScore = rootMoves[0].score;
int delta = std::min(topScore - rootMoves[multiPV - 1].score, int(PawnValue));
int maxScore = -VALUE_INFINITE;
double weakness = 120 - 2 * level;
// Choose best move. For each move score we add two terms, both dependent on
// weakness. One is deterministic and bigger for weaker levels, and one is
// random. Then we choose the move with the resulting highest score.
for (size_t i = 0; i < multiPV; ++i)
{
// This is our magic formula
int push = (weakness * int(topScore - rootMoves[i].score)
+ delta * (rng.rand<unsigned>() % int(weakness)))
/ 128;
if (rootMoves[i].score + push >= maxScore)
{
maxScore = rootMoves[i].score + push;
best = rootMoves[i].pv[0];
}
}
return best;
}
// Used to print debug info and, more importantly, to detect
// when we are out of available time and thus stop the search.
void SearchManager::check_time(Search::Worker& worker) {
if (--callsCnt > 0)
return;
// When using nodes, ensure checking rate is not lower than 0.1% of nodes
callsCnt = worker.limits.nodes ? std::min(512, int(worker.limits.nodes / 1024)) : 512;
static TimePoint lastInfoTime = now();
TimePoint elapsed = tm.elapsed([&worker]() { return worker.threads.nodes_searched(); });
TimePoint tick = worker.limits.startTime + elapsed;
if (tick - lastInfoTime >= 1000)
{
lastInfoTime = tick;
dbg_print();
}
// We should not stop pondering until told so by the GUI
if (ponder)
return;
if (
// Later we rely on the fact that we can at least use the mainthread previous
// root-search score and PV in a multithreaded environment to prove mated-in scores.
worker.completedDepth >= 1
&& ((worker.limits.use_time_management() && (elapsed > tm.maximum() || stopOnPonderhit))
|| (worker.limits.movetime && elapsed >= worker.limits.movetime)
|| (worker.limits.nodes && worker.threads.nodes_searched() >= worker.limits.nodes)))
worker.threads.stop = worker.threads.abortedSearch = true;
}
// Used to correct and extend PVs for moves that have a TB (but not a mate) score.
// Keeps the search based PV for as long as it is verified to maintain the game
// outcome, truncates afterwards. Finally, extends to mate the PV, providing a
// possible continuation (but not a proven mating line).
void syzygy_extend_pv(const OptionsMap& options,
const Search::LimitsType& limits,
Position& pos,
RootMove& rootMove,
Value& v) {
auto t_start = std::chrono::steady_clock::now();
int moveOverhead = int(options["Move Overhead"]);
// Do not use more than moveOverhead / 2 time, if time management is active
auto time_abort = [&t_start, &moveOverhead, &limits]() -> bool {
auto t_end = std::chrono::steady_clock::now();
return limits.use_time_management()
&& 2 * std::chrono::duration<double, std::milli>(t_end - t_start).count()
> moveOverhead;
};
std::list<StateInfo> sts;
// Step 0, do the rootMove, no correction allowed, as needed for MultiPV in TB.
auto& stRoot = sts.emplace_back();
pos.do_move(rootMove.pv[0], stRoot);
int ply = 1;
// Step 1, walk the PV to the last position in TB with correct decisive score
while (size_t(ply) < rootMove.pv.size())
{
Move& pvMove = rootMove.pv[ply];
RootMoves legalMoves;
for (const auto& m : MoveList<LEGAL>(pos))
legalMoves.emplace_back(m);
Tablebases::Config config = Tablebases::rank_root_moves(options, pos, legalMoves);
RootMove& rm = *std::find(legalMoves.begin(), legalMoves.end(), pvMove);
if (legalMoves[0].tbRank != rm.tbRank)
break;
ply++;
auto& st = sts.emplace_back();
pos.do_move(pvMove, st);
// Do not allow for repetitions or drawing moves along the PV in TB regime
if (config.rootInTB && pos.is_draw(ply))
{
pos.undo_move(pvMove);
ply--;
break;
}
// Full PV shown will thus be validated and end in TB.
// If we cannot validate the full PV in time, we do not show it.
if (config.rootInTB && time_abort())
break;
}
// Resize the PV to the correct part
rootMove.pv.resize(ply);
// Step 2, now extend the PV to mate, as if the user explored syzygy-tables.info
// using top ranked moves (minimal DTZ), which gives optimal mates only for simple
// endgames e.g. KRvK.
while (!pos.is_draw(0))
{
if (time_abort())
break;
RootMoves legalMoves;
for (const auto& m : MoveList<LEGAL>(pos))
{
auto& rm = legalMoves.emplace_back(m);
StateInfo tmpSI;
pos.do_move(m, tmpSI);
// Give a score of each move to break DTZ ties restricting opponent mobility,
// but not giving the opponent a capture.
for (const auto& mOpp : MoveList<LEGAL>(pos))
rm.tbRank -= pos.capture(mOpp) ? 100 : 1;
pos.undo_move(m);
}
// Mate found
if (legalMoves.size() == 0)
break;
// Sort moves according to their above assigned rank.
// This will break ties for moves with equal DTZ in rank_root_moves.
std::stable_sort(
legalMoves.begin(), legalMoves.end(),
[](const Search::RootMove& a, const Search::RootMove& b) { return a.tbRank > b.tbRank; });
// The winning side tries to minimize DTZ, the losing side maximizes it
Tablebases::Config config = Tablebases::rank_root_moves(options, pos, legalMoves, true);
// If DTZ is not available we might not find a mate, so we bail out
if (!config.rootInTB || config.cardinality > 0)
break;
ply++;
Move& pvMove = legalMoves[0].pv[0];
rootMove.pv.push_back(pvMove);
auto& st = sts.emplace_back();
pos.do_move(pvMove, st);
}
// Finding a draw in this function is an exceptional case, that cannot happen
// during engine game play, since we have a winning score, and play correctly
// with TB support. However, it can be that a position is draw due to the 50 move
// rule if it has been been reached on the board with a non-optimal 50 move counter
// (e.g. 8/8/6k1/3B4/3K4/4N3/8/8 w - - 54 106 ) which TB with dtz counter rounding
// cannot always correctly rank. See also
// https://github.com/official-stockfish/Stockfish/issues/5175#issuecomment-2058893495
// We adjust the score to match the found PV. Note that a TB loss score can be
// displayed if the engine did not find a drawing move yet, but eventually search
// will figure it out (e.g. 1kq5/q2r4/5K2/8/8/8/8/7Q w - - 96 1 )
if (pos.is_draw(0))
v = VALUE_DRAW;
// Undo the PV moves
for (auto it = rootMove.pv.rbegin(); it != rootMove.pv.rend(); ++it)
pos.undo_move(*it);
// Inform if we couldn't get a full extension in time
if (time_abort())
sync_cout
<< "info string Syzygy based PV extension requires more time, increase Move Overhead as needed."
<< sync_endl;
}
void SearchManager::pv(Search::Worker& worker,
const ThreadPool& threads,
const TranspositionTable& tt,
Depth depth) {
const auto nodes = threads.nodes_searched();
auto& rootMoves = worker.rootMoves;
auto& pos = worker.rootPos;
size_t pvIdx = worker.pvIdx;
size_t multiPV = std::min(size_t(worker.options["MultiPV"]), rootMoves.size());
uint64_t tbHits = threads.tb_hits() + (worker.tbConfig.rootInTB ? rootMoves.size() : 0);
for (size_t i = 0; i < multiPV; ++i)
{
bool updated = rootMoves[i].score != -VALUE_INFINITE;
if (depth == 1 && !updated && i > 0)
continue;
Depth d = updated ? depth : std::max(1, depth - 1);
Value v = updated ? rootMoves[i].uciScore : rootMoves[i].previousScore;
if (v == -VALUE_INFINITE)
v = VALUE_ZERO;
bool tb = worker.tbConfig.rootInTB && std::abs(v) <= VALUE_TB;
v = tb ? rootMoves[i].tbScore : v;
bool isExact = i != pvIdx || tb || !updated; // tablebase- and previous-scores are exact
// Potentially correct and extend the PV, and in exceptional cases v
if (std::abs(v) >= VALUE_TB_WIN_IN_MAX_PLY && std::abs(v) < VALUE_MATE_IN_MAX_PLY
&& ((!rootMoves[i].scoreLowerbound && !rootMoves[i].scoreUpperbound) || isExact))
syzygy_extend_pv(worker.options, worker.limits, pos, rootMoves[i], v);
std::string pv;
for (Move m : rootMoves[i].pv)
pv += UCIEngine::move(m, pos.is_chess960()) + " ";
// Remove last whitespace
if (!pv.empty())
pv.pop_back();
auto wdl = worker.options["UCI_ShowWDL"] ? UCIEngine::wdl(v, pos) : "";
auto bound = rootMoves[i].scoreLowerbound
? "lowerbound"
: (rootMoves[i].scoreUpperbound ? "upperbound" : "");
InfoFull info;
info.depth = d;
info.selDepth = rootMoves[i].selDepth;
info.multiPV = i + 1;
info.score = {v, pos};
info.wdl = wdl;
if (!isExact)
info.bound = bound;
TimePoint time = tm.elapsed_time() + 1;
info.timeMs = time;
info.nodes = nodes;
info.nps = nodes * 1000 / time;
info.tbHits = tbHits;
info.pv = pv;
info.hashfull = tt.hashfull();
updates.onUpdateFull(info);
}
}
// Called in case we have no ponder move before exiting the search,
// for instance, in case we stop the search during a fail high at root.
// We try hard to have a ponder move to return to the GUI,
// otherwise in case of 'ponder on' we have nothing to think about.
bool RootMove::extract_ponder_from_tt(const TranspositionTable& tt, Position& pos) {
StateInfo st;
ASSERT_ALIGNED(&st, Eval::NNUE::CacheLineSize);
assert(pv.size() == 1);
if (pv[0] == Move::none())
return false;
pos.do_move(pv[0], st);
auto [ttHit, ttData, ttWriter] = tt.probe(pos.key());
if (ttHit)
{
if (MoveList<LEGAL>(pos).contains(ttData.move))
pv.push_back(ttData.move);
}
pos.undo_move(pv[0]);
return pv.size() > 1;
}
} // namespace Stockfish
| 87,802
|
C++
|
.cpp
| 1,749
| 39.691824
| 106
| 0.58303
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,033
|
movegen.cpp
|
official-stockfish_Stockfish/src/movegen.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "movegen.h"
#include <cassert>
#include <initializer_list>
#include "bitboard.h"
#include "position.h"
namespace Stockfish {
namespace {
template<GenType Type, Direction D, bool Enemy>
ExtMove* make_promotions(ExtMove* moveList, [[maybe_unused]] Square to) {
constexpr bool all = Type == EVASIONS || Type == NON_EVASIONS;
if constexpr (Type == CAPTURES || all)
*moveList++ = Move::make<PROMOTION>(to - D, to, QUEEN);
if constexpr ((Type == CAPTURES && Enemy) || (Type == QUIETS && !Enemy) || all)
{
*moveList++ = Move::make<PROMOTION>(to - D, to, ROOK);
*moveList++ = Move::make<PROMOTION>(to - D, to, BISHOP);
*moveList++ = Move::make<PROMOTION>(to - D, to, KNIGHT);
}
return moveList;
}
template<Color Us, GenType Type>
ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
constexpr Color Them = ~Us;
constexpr Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
constexpr Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
constexpr Direction Up = pawn_push(Us);
constexpr Direction UpRight = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
constexpr Direction UpLeft = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
const Bitboard emptySquares = ~pos.pieces();
const Bitboard enemies = Type == EVASIONS ? pos.checkers() : pos.pieces(Them);
Bitboard pawnsOn7 = pos.pieces(Us, PAWN) & TRank7BB;
Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
// Single and double pawn pushes, no promotions
if constexpr (Type != CAPTURES)
{
Bitboard b1 = shift<Up>(pawnsNotOn7) & emptySquares;
Bitboard b2 = shift<Up>(b1 & TRank3BB) & emptySquares;
if constexpr (Type == EVASIONS) // Consider only blocking squares
{
b1 &= target;
b2 &= target;
}
while (b1)
{
Square to = pop_lsb(b1);
*moveList++ = Move(to - Up, to);
}
while (b2)
{
Square to = pop_lsb(b2);
*moveList++ = Move(to - Up - Up, to);
}
}
// Promotions and underpromotions
if (pawnsOn7)
{
Bitboard b1 = shift<UpRight>(pawnsOn7) & enemies;
Bitboard b2 = shift<UpLeft>(pawnsOn7) & enemies;
Bitboard b3 = shift<Up>(pawnsOn7) & emptySquares;
if constexpr (Type == EVASIONS)
b3 &= target;
while (b1)
moveList = make_promotions<Type, UpRight, true>(moveList, pop_lsb(b1));
while (b2)
moveList = make_promotions<Type, UpLeft, true>(moveList, pop_lsb(b2));
while (b3)
moveList = make_promotions<Type, Up, false>(moveList, pop_lsb(b3));
}
// Standard and en passant captures
if constexpr (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
{
Bitboard b1 = shift<UpRight>(pawnsNotOn7) & enemies;
Bitboard b2 = shift<UpLeft>(pawnsNotOn7) & enemies;
while (b1)
{
Square to = pop_lsb(b1);
*moveList++ = Move(to - UpRight, to);
}
while (b2)
{
Square to = pop_lsb(b2);
*moveList++ = Move(to - UpLeft, to);
}
if (pos.ep_square() != SQ_NONE)
{
assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
// An en passant capture cannot resolve a discovered check
if (Type == EVASIONS && (target & (pos.ep_square() + Up)))
return moveList;
b1 = pawnsNotOn7 & pawn_attacks_bb(Them, pos.ep_square());
assert(b1);
while (b1)
*moveList++ = Move::make<EN_PASSANT>(pop_lsb(b1), pos.ep_square());
}
}
return moveList;
}
template<Color Us, PieceType Pt>
ExtMove* generate_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
static_assert(Pt != KING && Pt != PAWN, "Unsupported piece type in generate_moves()");
Bitboard bb = pos.pieces(Us, Pt);
while (bb)
{
Square from = pop_lsb(bb);
Bitboard b = attacks_bb<Pt>(from, pos.pieces()) & target;
while (b)
*moveList++ = Move(from, pop_lsb(b));
}
return moveList;
}
template<Color Us, GenType Type>
ExtMove* generate_all(const Position& pos, ExtMove* moveList) {
static_assert(Type != LEGAL, "Unsupported type in generate_all()");
const Square ksq = pos.square<KING>(Us);
Bitboard target;
// Skip generating non-king moves when in double check
if (Type != EVASIONS || !more_than_one(pos.checkers()))
{
target = Type == EVASIONS ? between_bb(ksq, lsb(pos.checkers()))
: Type == NON_EVASIONS ? ~pos.pieces(Us)
: Type == CAPTURES ? pos.pieces(~Us)
: ~pos.pieces(); // QUIETS
moveList = generate_pawn_moves<Us, Type>(pos, moveList, target);
moveList = generate_moves<Us, KNIGHT>(pos, moveList, target);
moveList = generate_moves<Us, BISHOP>(pos, moveList, target);
moveList = generate_moves<Us, ROOK>(pos, moveList, target);
moveList = generate_moves<Us, QUEEN>(pos, moveList, target);
}
Bitboard b = attacks_bb<KING>(ksq) & (Type == EVASIONS ? ~pos.pieces(Us) : target);
while (b)
*moveList++ = Move(ksq, pop_lsb(b));
if ((Type == QUIETS || Type == NON_EVASIONS) && pos.can_castle(Us & ANY_CASTLING))
for (CastlingRights cr : {Us & KING_SIDE, Us & QUEEN_SIDE})
if (!pos.castling_impeded(cr) && pos.can_castle(cr))
*moveList++ = Move::make<CASTLING>(ksq, pos.castling_rook_square(cr));
return moveList;
}
} // namespace
// <CAPTURES> Generates all pseudo-legal captures plus queen promotions
// <QUIETS> Generates all pseudo-legal non-captures and underpromotions
// <EVASIONS> Generates all pseudo-legal check evasions
// <NON_EVASIONS> Generates all pseudo-legal captures and non-captures
//
// Returns a pointer to the end of the move list.
template<GenType Type>
ExtMove* generate(const Position& pos, ExtMove* moveList) {
static_assert(Type != LEGAL, "Unsupported type in generate()");
assert((Type == EVASIONS) == bool(pos.checkers()));
Color us = pos.side_to_move();
return us == WHITE ? generate_all<WHITE, Type>(pos, moveList)
: generate_all<BLACK, Type>(pos, moveList);
}
// Explicit template instantiations
template ExtMove* generate<CAPTURES>(const Position&, ExtMove*);
template ExtMove* generate<QUIETS>(const Position&, ExtMove*);
template ExtMove* generate<EVASIONS>(const Position&, ExtMove*);
template ExtMove* generate<NON_EVASIONS>(const Position&, ExtMove*);
// generate<LEGAL> generates all the legal moves in the given position
template<>
ExtMove* generate<LEGAL>(const Position& pos, ExtMove* moveList) {
Color us = pos.side_to_move();
Bitboard pinned = pos.blockers_for_king(us) & pos.pieces(us);
Square ksq = pos.square<KING>(us);
ExtMove* cur = moveList;
moveList =
pos.checkers() ? generate<EVASIONS>(pos, moveList) : generate<NON_EVASIONS>(pos, moveList);
while (cur != moveList)
if (((pinned & cur->from_sq()) || cur->from_sq() == ksq || cur->type_of() == EN_PASSANT)
&& !pos.legal(*cur))
*cur = *(--moveList);
else
++cur;
return moveList;
}
} // namespace Stockfish
| 8,293
|
C++
|
.cpp
| 189
| 36.888889
| 97
| 0.62486
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
12,034
|
ucioption.cpp
|
official-stockfish_Stockfish/src/ucioption.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ucioption.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <iostream>
#include <sstream>
#include <utility>
#include "misc.h"
namespace Stockfish {
bool CaseInsensitiveLess::operator()(const std::string& s1, const std::string& s2) const {
return std::lexicographical_compare(
s1.begin(), s1.end(), s2.begin(), s2.end(),
[](char c1, char c2) { return std::tolower(c1) < std::tolower(c2); });
}
void OptionsMap::add_info_listener(InfoListener&& message_func) { info = std::move(message_func); }
void OptionsMap::setoption(std::istringstream& is) {
std::string token, name, value;
is >> token; // Consume the "name" token
// Read the option name (can contain spaces)
while (is >> token && token != "value")
name += (name.empty() ? "" : " ") + token;
// Read the option value (can contain spaces)
while (is >> token)
value += (value.empty() ? "" : " ") + token;
if (options_map.count(name))
options_map[name] = value;
else
sync_cout << "No such option: " << name << sync_endl;
}
Option OptionsMap::operator[](const std::string& name) const {
auto it = options_map.find(name);
return it != options_map.end() ? it->second : Option(this);
}
Option& OptionsMap::operator[](const std::string& name) {
if (!options_map.count(name))
options_map[name] = Option(this);
return options_map[name];
}
std::size_t OptionsMap::count(const std::string& name) const { return options_map.count(name); }
Option::Option(const OptionsMap* map) :
parent(map) {}
Option::Option(const char* v, OnChange f) :
type("string"),
min(0),
max(0),
on_change(std::move(f)) {
defaultValue = currentValue = v;
}
Option::Option(bool v, OnChange f) :
type("check"),
min(0),
max(0),
on_change(std::move(f)) {
defaultValue = currentValue = (v ? "true" : "false");
}
Option::Option(OnChange f) :
type("button"),
min(0),
max(0),
on_change(std::move(f)) {}
Option::Option(double v, int minv, int maxv, OnChange f) :
type("spin"),
min(minv),
max(maxv),
on_change(std::move(f)) {
defaultValue = currentValue = std::to_string(v);
}
Option::Option(const char* v, const char* cur, OnChange f) :
type("combo"),
min(0),
max(0),
on_change(std::move(f)) {
defaultValue = v;
currentValue = cur;
}
Option::operator int() const {
assert(type == "check" || type == "spin");
return (type == "spin" ? std::stoi(currentValue) : currentValue == "true");
}
Option::operator std::string() const {
assert(type == "string");
return currentValue;
}
bool Option::operator==(const char* s) const {
assert(type == "combo");
return !CaseInsensitiveLess()(currentValue, s) && !CaseInsensitiveLess()(s, currentValue);
}
bool Option::operator!=(const char* s) const { return !(*this == s); }
// Inits options and assigns idx in the correct printing order
void Option::operator<<(const Option& o) {
static size_t insert_order = 0;
auto p = this->parent;
*this = o;
this->parent = p;
idx = insert_order++;
}
// Updates currentValue and triggers on_change() action. It's up to
// the GUI to check for option's limits, but we could receive the new value
// from the user by console window, so let's check the bounds anyway.
Option& Option::operator=(const std::string& v) {
assert(!type.empty());
if ((type != "button" && type != "string" && v.empty())
|| (type == "check" && v != "true" && v != "false")
|| (type == "spin" && (std::stof(v) < min || std::stof(v) > max)))
return *this;
if (type == "combo")
{
OptionsMap comboMap; // To have case insensitive compare
std::string token;
std::istringstream ss(defaultValue);
while (ss >> token)
comboMap[token] << Option();
if (!comboMap.count(v) || v == "var")
return *this;
}
if (type == "string")
currentValue = v == "<empty>" ? "" : v;
else if (type != "button")
currentValue = v;
if (on_change)
{
const auto ret = on_change(*this);
if (ret && parent != nullptr && parent->info != nullptr)
parent->info(ret);
}
return *this;
}
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
for (size_t idx = 0; idx < om.options_map.size(); ++idx)
for (const auto& it : om.options_map)
if (it.second.idx == idx)
{
const Option& o = it.second;
os << "\noption name " << it.first << " type " << o.type;
if (o.type == "check" || o.type == "combo")
os << " default " << o.defaultValue;
else if (o.type == "string")
{
std::string defaultValue = o.defaultValue.empty() ? "<empty>" : o.defaultValue;
os << " default " << defaultValue;
}
else if (o.type == "spin")
os << " default " << int(stof(o.defaultValue)) << " min " << o.min << " max "
<< o.max;
break;
}
return os;
}
}
| 6,027
|
C++
|
.cpp
| 163
| 31.171779
| 99
| 0.603508
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,036
|
thread.cpp
|
official-stockfish_Stockfish/src/thread.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "thread.h"
#include <algorithm>
#include <cassert>
#include <deque>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include "movegen.h"
#include "search.h"
#include "syzygy/tbprobe.h"
#include "timeman.h"
#include "types.h"
#include "uci.h"
#include "ucioption.h"
namespace Stockfish {
// Constructor launches the thread and waits until it goes to sleep
// in idle_loop(). Note that 'searching' and 'exit' should be already set.
Thread::Thread(Search::SharedState& sharedState,
std::unique_ptr<Search::ISearchManager> sm,
size_t n,
OptionalThreadToNumaNodeBinder binder) :
idx(n),
nthreads(sharedState.options["Threads"]),
stdThread(&Thread::idle_loop, this) {
wait_for_search_finished();
run_custom_job([this, &binder, &sharedState, &sm, n]() {
// Use the binder to [maybe] bind the threads to a NUMA node before doing
// the Worker allocation. Ideally we would also allocate the SearchManager
// here, but that's minor.
this->numaAccessToken = binder();
this->worker =
std::make_unique<Search::Worker>(sharedState, std::move(sm), n, this->numaAccessToken);
});
wait_for_search_finished();
}
// Destructor wakes up the thread in idle_loop() and waits
// for its termination. Thread should be already waiting.
Thread::~Thread() {
assert(!searching);
exit = true;
start_searching();
stdThread.join();
}
// Wakes up the thread that will start the search
void Thread::start_searching() {
assert(worker != nullptr);
run_custom_job([this]() { worker->start_searching(); });
}
// Clears the histories for the thread worker (usually before a new game)
void Thread::clear_worker() {
assert(worker != nullptr);
run_custom_job([this]() { worker->clear(); });
}
// Blocks on the condition variable until the thread has finished searching
void Thread::wait_for_search_finished() {
std::unique_lock<std::mutex> lk(mutex);
cv.wait(lk, [&] { return !searching; });
}
// Launching a function in the thread
void Thread::run_custom_job(std::function<void()> f) {
{
std::unique_lock<std::mutex> lk(mutex);
cv.wait(lk, [&] { return !searching; });
jobFunc = std::move(f);
searching = true;
}
cv.notify_one();
}
void Thread::ensure_network_replicated() { worker->ensure_network_replicated(); }
// Thread gets parked here, blocked on the condition variable
// when the thread has no work to do.
void Thread::idle_loop() {
while (true)
{
std::unique_lock<std::mutex> lk(mutex);
searching = false;
cv.notify_one(); // Wake up anyone waiting for search finished
cv.wait(lk, [&] { return searching; });
if (exit)
return;
std::function<void()> job = std::move(jobFunc);
jobFunc = nullptr;
lk.unlock();
if (job)
job();
}
}
Search::SearchManager* ThreadPool::main_manager() { return main_thread()->worker->main_manager(); }
uint64_t ThreadPool::nodes_searched() const { return accumulate(&Search::Worker::nodes); }
uint64_t ThreadPool::tb_hits() const { return accumulate(&Search::Worker::tbHits); }
// Creates/destroys threads to match the requested number.
// Created and launched threads will immediately go to sleep in idle_loop.
// Upon resizing, threads are recreated to allow for binding if necessary.
void ThreadPool::set(const NumaConfig& numaConfig,
Search::SharedState sharedState,
const Search::SearchManager::UpdateContext& updateContext) {
if (threads.size() > 0) // destroy any existing thread(s)
{
main_thread()->wait_for_search_finished();
threads.clear();
boundThreadToNumaNode.clear();
}
const size_t requested = sharedState.options["Threads"];
if (requested > 0) // create new thread(s)
{
// Binding threads may be problematic when there's multiple NUMA nodes and
// multiple Stockfish instances running. In particular, if each instance
// runs a single thread then they would all be mapped to the first NUMA node.
// This is undesirable, and so the default behaviour (i.e. when the user does not
// change the NumaConfig UCI setting) is to not bind the threads to processors
// unless we know for sure that we span NUMA nodes and replication is required.
const std::string numaPolicy(sharedState.options["NumaPolicy"]);
const bool doBindThreads = [&]() {
if (numaPolicy == "none")
return false;
if (numaPolicy == "auto")
return numaConfig.suggests_binding_threads(requested);
// numaPolicy == "system", or explicitly set by the user
return true;
}();
boundThreadToNumaNode = doBindThreads
? numaConfig.distribute_threads_among_numa_nodes(requested)
: std::vector<NumaIndex>{};
while (threads.size() < requested)
{
const size_t threadId = threads.size();
const NumaIndex numaId = doBindThreads ? boundThreadToNumaNode[threadId] : 0;
auto manager = threadId == 0 ? std::unique_ptr<Search::ISearchManager>(
std::make_unique<Search::SearchManager>(updateContext))
: std::make_unique<Search::NullSearchManager>();
// When not binding threads we want to force all access to happen
// from the same NUMA node, because in case of NUMA replicated memory
// accesses we don't want to trash cache in case the threads get scheduled
// on the same NUMA node.
auto binder = doBindThreads ? OptionalThreadToNumaNodeBinder(numaConfig, numaId)
: OptionalThreadToNumaNodeBinder(numaId);
threads.emplace_back(
std::make_unique<Thread>(sharedState, std::move(manager), threadId, binder));
}
clear();
main_thread()->wait_for_search_finished();
}
}
// Sets threadPool data to initial values
void ThreadPool::clear() {
if (threads.size() == 0)
return;
for (auto&& th : threads)
th->clear_worker();
for (auto&& th : threads)
th->wait_for_search_finished();
// These two affect the time taken on the first move of a game:
main_manager()->bestPreviousAverageScore = VALUE_INFINITE;
main_manager()->previousTimeReduction = 0.85;
main_manager()->callsCnt = 0;
main_manager()->bestPreviousScore = VALUE_INFINITE;
main_manager()->originalTimeAdjust = -1;
main_manager()->tm.clear();
}
void ThreadPool::run_on_thread(size_t threadId, std::function<void()> f) {
assert(threads.size() > threadId);
threads[threadId]->run_custom_job(std::move(f));
}
void ThreadPool::wait_on_thread(size_t threadId) {
assert(threads.size() > threadId);
threads[threadId]->wait_for_search_finished();
}
size_t ThreadPool::num_threads() const { return threads.size(); }
// Wakes up main thread waiting in idle_loop() and returns immediately.
// Main thread will wake up other threads and start the search.
void ThreadPool::start_thinking(const OptionsMap& options,
Position& pos,
StateListPtr& states,
Search::LimitsType limits) {
main_thread()->wait_for_search_finished();
main_manager()->stopOnPonderhit = stop = abortedSearch = false;
main_manager()->ponder = limits.ponderMode;
increaseDepth = true;
Search::RootMoves rootMoves;
const auto legalmoves = MoveList<LEGAL>(pos);
for (const auto& uciMove : limits.searchmoves)
{
auto move = UCIEngine::to_move(pos, uciMove);
if (std::find(legalmoves.begin(), legalmoves.end(), move) != legalmoves.end())
rootMoves.emplace_back(move);
}
if (rootMoves.empty())
for (const auto& m : legalmoves)
rootMoves.emplace_back(m);
Tablebases::Config tbConfig = Tablebases::rank_root_moves(options, pos, rootMoves);
// After ownership transfer 'states' becomes empty, so if we stop the search
// and call 'go' again without setting a new position states.get() == nullptr.
assert(states.get() || setupStates.get());
if (states.get())
setupStates = std::move(states); // Ownership transfer, states is now empty
// We use Position::set() to set root position across threads. But there are
// some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
// be deduced from a fen string, so set() clears them and they are set from
// setupStates->back() later. The rootState is per thread, earlier states are
// shared since they are read-only.
for (auto&& th : threads)
{
th->run_custom_job([&]() {
th->worker->limits = limits;
th->worker->nodes = th->worker->tbHits = th->worker->nmpMinPly =
th->worker->bestMoveChanges = 0;
th->worker->rootDepth = th->worker->completedDepth = 0;
th->worker->rootMoves = rootMoves;
th->worker->rootPos.set(pos.fen(), pos.is_chess960(), &th->worker->rootState);
th->worker->rootState = setupStates->back();
th->worker->tbConfig = tbConfig;
});
}
for (auto&& th : threads)
th->wait_for_search_finished();
main_thread()->start_searching();
}
Thread* ThreadPool::get_best_thread() const {
Thread* bestThread = threads.front().get();
Value minScore = VALUE_NONE;
std::unordered_map<Move, int64_t, Move::MoveHash> votes(
2 * std::min(size(), bestThread->worker->rootMoves.size()));
// Find the minimum score of all threads
for (auto&& th : threads)
minScore = std::min(minScore, th->worker->rootMoves[0].score);
// Vote according to score and depth, and select the best thread
auto thread_voting_value = [minScore](Thread* th) {
return (th->worker->rootMoves[0].score - minScore + 14) * int(th->worker->completedDepth);
};
for (auto&& th : threads)
votes[th->worker->rootMoves[0].pv[0]] += thread_voting_value(th.get());
for (auto&& th : threads)
{
const auto bestThreadScore = bestThread->worker->rootMoves[0].score;
const auto newThreadScore = th->worker->rootMoves[0].score;
const auto& bestThreadPV = bestThread->worker->rootMoves[0].pv;
const auto& newThreadPV = th->worker->rootMoves[0].pv;
const auto bestThreadMoveVote = votes[bestThreadPV[0]];
const auto newThreadMoveVote = votes[newThreadPV[0]];
const bool bestThreadInProvenWin = bestThreadScore >= VALUE_TB_WIN_IN_MAX_PLY;
const bool newThreadInProvenWin = newThreadScore >= VALUE_TB_WIN_IN_MAX_PLY;
const bool bestThreadInProvenLoss =
bestThreadScore != -VALUE_INFINITE && bestThreadScore <= VALUE_TB_LOSS_IN_MAX_PLY;
const bool newThreadInProvenLoss =
newThreadScore != -VALUE_INFINITE && newThreadScore <= VALUE_TB_LOSS_IN_MAX_PLY;
// We make sure not to pick a thread with truncated principal variation
const bool betterVotingValue =
thread_voting_value(th.get()) * int(newThreadPV.size() > 2)
> thread_voting_value(bestThread) * int(bestThreadPV.size() > 2);
if (bestThreadInProvenWin)
{
// Make sure we pick the shortest mate / TB conversion
if (newThreadScore > bestThreadScore)
bestThread = th.get();
}
else if (bestThreadInProvenLoss)
{
// Make sure we pick the shortest mated / TB conversion
if (newThreadInProvenLoss && newThreadScore < bestThreadScore)
bestThread = th.get();
}
else if (newThreadInProvenWin || newThreadInProvenLoss
|| (newThreadScore > VALUE_TB_LOSS_IN_MAX_PLY
&& (newThreadMoveVote > bestThreadMoveVote
|| (newThreadMoveVote == bestThreadMoveVote && betterVotingValue))))
bestThread = th.get();
}
return bestThread;
}
// Start non-main threads.
// Will be invoked by main thread after it has started searching.
void ThreadPool::start_searching() {
for (auto&& th : threads)
if (th != threads.front())
th->start_searching();
}
// Wait for non-main threads
void ThreadPool::wait_for_search_finished() const {
for (auto&& th : threads)
if (th != threads.front())
th->wait_for_search_finished();
}
std::vector<size_t> ThreadPool::get_bound_thread_count_by_numa_node() const {
std::vector<size_t> counts;
if (!boundThreadToNumaNode.empty())
{
NumaIndex highestNumaNode = 0;
for (NumaIndex n : boundThreadToNumaNode)
if (n > highestNumaNode)
highestNumaNode = n;
counts.resize(highestNumaNode + 1, 0);
for (NumaIndex n : boundThreadToNumaNode)
counts[n] += 1;
}
return counts;
}
void ThreadPool::ensure_network_replicated() {
for (auto&& th : threads)
th->ensure_network_replicated();
}
} // namespace Stockfish
| 14,459
|
C++
|
.cpp
| 316
| 38.155063
| 101
| 0.63549
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,037
|
misc.cpp
|
official-stockfish_Stockfish/src/misc.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "misc.h"
#include <atomic>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <mutex>
#include <sstream>
#include <string_view>
#include "types.h"
namespace Stockfish {
namespace {
// Version number or dev.
constexpr std::string_view version = "dev";
// Our fancy logging facility. The trick here is to replace cin.rdbuf() and
// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
// can toggle the logging of std::cout and std:cin at runtime whilst preserving
// usual I/O functionality, all without changing a single line of code!
// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout
Tie(std::streambuf* b, std::streambuf* l) :
buf(b),
logBuf(l) {}
int sync() override { return logBuf->pubsync(), buf->pubsync(); }
int overflow(int c) override { return log(buf->sputc(char(c)), "<< "); }
int underflow() override { return buf->sgetc(); }
int uflow() override { return log(buf->sbumpc(), ">> "); }
std::streambuf *buf, *logBuf;
int log(int c, const char* prefix) {
static int last = '\n'; // Single log file
if (last == '\n')
logBuf->sputn(prefix, 3);
return last = logBuf->sputc(char(c));
}
};
class Logger {
Logger() :
in(std::cin.rdbuf(), file.rdbuf()),
out(std::cout.rdbuf(), file.rdbuf()) {}
~Logger() { start(""); }
std::ofstream file;
Tie in, out;
public:
static void start(const std::string& fname) {
static Logger l;
if (l.file.is_open())
{
std::cout.rdbuf(l.out.buf);
std::cin.rdbuf(l.in.buf);
l.file.close();
}
if (!fname.empty())
{
l.file.open(fname, std::ifstream::out);
if (!l.file.is_open())
{
std::cerr << "Unable to open debug log file " << fname << std::endl;
exit(EXIT_FAILURE);
}
std::cin.rdbuf(&l.in);
std::cout.rdbuf(&l.out);
}
}
};
} // namespace
// Returns the full name of the current Stockfish version.
//
// For local dev compiles we try to append the commit SHA and
// commit date from git. If that fails only the local compilation
// date is set and "nogit" is specified:
// Stockfish dev-YYYYMMDD-SHA
// or
// Stockfish dev-YYYYMMDD-nogit
//
// For releases (non-dev builds) we only include the version number:
// Stockfish version
std::string engine_version_info() {
std::stringstream ss;
ss << "Stockfish " << version << std::setfill('0');
if constexpr (version == "dev")
{
ss << "-";
#ifdef GIT_DATE
ss << stringify(GIT_DATE);
#else
constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
std::string month, day, year;
std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
date >> month >> day >> year;
ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4)
<< std::setw(2) << std::setfill('0') << day;
#endif
ss << "-";
#ifdef GIT_SHA
ss << stringify(GIT_SHA);
#else
ss << "nogit";
#endif
}
return ss.str();
}
std::string engine_info(bool to_uci) {
return engine_version_info() + (to_uci ? "\nid author " : " by ")
+ "the Stockfish developers (see AUTHORS file)";
}
// Returns a string trying to describe the compiler we use
std::string compiler_info() {
#define make_version_string(major, minor, patch) \
stringify(major) "." stringify(minor) "." stringify(patch)
// Predefined macros hell:
//
// __GNUC__ Compiler is GCC, Clang or ICX
// __clang__ Compiler is Clang or ICX
// __INTEL_LLVM_COMPILER Compiler is ICX
// _MSC_VER Compiler is MSVC
// _WIN32 Building on Windows (any)
// _WIN64 Building on Windows 64 bit
std::string compiler = "\nCompiled by : ";
#if defined(__INTEL_LLVM_COMPILER)
compiler += "ICX ";
compiler += stringify(__INTEL_LLVM_COMPILER);
#elif defined(__clang__)
compiler += "clang++ ";
compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
#elif _MSC_VER
compiler += "MSVC ";
compiler += "(version ";
compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
compiler += ")";
#elif defined(__e2k__) && defined(__LCC__)
#define dot_ver2(n) \
compiler += char('.'); \
compiler += char('0' + (n) / 10); \
compiler += char('0' + (n) % 10);
compiler += "MCST LCC ";
compiler += "(version ";
compiler += std::to_string(__LCC__ / 100);
dot_ver2(__LCC__ % 100) dot_ver2(__LCC_MINOR__) compiler += ")";
#elif __GNUC__
compiler += "g++ (GNUC) ";
compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#else
compiler += "Unknown compiler ";
compiler += "(unknown version)";
#endif
#if defined(__APPLE__)
compiler += " on Apple";
#elif defined(__CYGWIN__)
compiler += " on Cygwin";
#elif defined(__MINGW64__)
compiler += " on MinGW64";
#elif defined(__MINGW32__)
compiler += " on MinGW32";
#elif defined(__ANDROID__)
compiler += " on Android";
#elif defined(__linux__)
compiler += " on Linux";
#elif defined(_WIN64)
compiler += " on Microsoft Windows 64-bit";
#elif defined(_WIN32)
compiler += " on Microsoft Windows 32-bit";
#else
compiler += " on unknown system";
#endif
compiler += "\nCompilation architecture : ";
#if defined(ARCH)
compiler += stringify(ARCH);
#else
compiler += "(undefined architecture)";
#endif
compiler += "\nCompilation settings : ";
compiler += (Is64Bit ? "64bit" : "32bit");
#if defined(USE_VNNI)
compiler += " VNNI";
#endif
#if defined(USE_AVX512)
compiler += " AVX512";
#endif
compiler += (HasPext ? " BMI2" : "");
#if defined(USE_AVX2)
compiler += " AVX2";
#endif
#if defined(USE_SSE41)
compiler += " SSE41";
#endif
#if defined(USE_SSSE3)
compiler += " SSSE3";
#endif
#if defined(USE_SSE2)
compiler += " SSE2";
#endif
compiler += (HasPopCnt ? " POPCNT" : "");
#if defined(USE_NEON_DOTPROD)
compiler += " NEON_DOTPROD";
#elif defined(USE_NEON)
compiler += " NEON";
#endif
#if !defined(NDEBUG)
compiler += " DEBUG";
#endif
compiler += "\nCompiler __VERSION__ macro : ";
#ifdef __VERSION__
compiler += __VERSION__;
#else
compiler += "(undefined macro)";
#endif
compiler += "\n";
return compiler;
}
// Debug functions used mainly to collect run-time statistics
constexpr int MaxDebugSlots = 32;
namespace {
template<size_t N>
struct DebugInfo {
std::atomic<int64_t> data[N] = {0};
constexpr std::atomic<int64_t>& operator[](int index) { return data[index]; }
};
struct DebugExtremes: public DebugInfo<3> {
DebugExtremes() {
data[1] = std::numeric_limits<int64_t>::min();
data[2] = std::numeric_limits<int64_t>::max();
}
};
DebugInfo<2> hit[MaxDebugSlots];
DebugInfo<2> mean[MaxDebugSlots];
DebugInfo<3> stdev[MaxDebugSlots];
DebugInfo<6> correl[MaxDebugSlots];
DebugExtremes extremes[MaxDebugSlots];
} // namespace
void dbg_hit_on(bool cond, int slot) {
++hit[slot][0];
if (cond)
++hit[slot][1];
}
void dbg_mean_of(int64_t value, int slot) {
++mean[slot][0];
mean[slot][1] += value;
}
void dbg_stdev_of(int64_t value, int slot) {
++stdev[slot][0];
stdev[slot][1] += value;
stdev[slot][2] += value * value;
}
void dbg_extremes_of(int64_t value, int slot) {
++extremes[slot][0];
int64_t current_max = extremes[slot][1].load();
while (current_max < value && !extremes[slot][1].compare_exchange_weak(current_max, value))
{}
int64_t current_min = extremes[slot][2].load();
while (current_min > value && !extremes[slot][2].compare_exchange_weak(current_min, value))
{}
}
void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
++correl[slot][0];
correl[slot][1] += value1;
correl[slot][2] += value1 * value1;
correl[slot][3] += value2;
correl[slot][4] += value2 * value2;
correl[slot][5] += value1 * value2;
}
void dbg_print() {
int64_t n;
auto E = [&n](int64_t x) { return double(x) / n; };
auto sqr = [](double x) { return x * x; };
for (int i = 0; i < MaxDebugSlots; ++i)
if ((n = hit[i][0]))
std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1]
<< " Hit Rate (%) " << 100.0 * E(hit[i][1]) << std::endl;
for (int i = 0; i < MaxDebugSlots; ++i)
if ((n = mean[i][0]))
{
std::cerr << "Mean #" << i << ": Total " << n << " Mean " << E(mean[i][1]) << std::endl;
}
for (int i = 0; i < MaxDebugSlots; ++i)
if ((n = stdev[i][0]))
{
double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
std::cerr << "Stdev #" << i << ": Total " << n << " Stdev " << r << std::endl;
}
for (int i = 0; i < MaxDebugSlots; ++i)
if ((n = extremes[i][0]))
{
std::cerr << "Extremity #" << i << ": Total " << n << " Min " << extremes[i][2]
<< " Max " << extremes[i][1] << std::endl;
}
for (int i = 0; i < MaxDebugSlots; ++i)
if ((n = correl[i][0]))
{
double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
/ (sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
* sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
std::cerr << "Correl. #" << i << ": Total " << n << " Coefficient " << r << std::endl;
}
}
// Used to serialize access to std::cout
// to avoid multiple threads writing at the same time.
std::ostream& operator<<(std::ostream& os, SyncCout sc) {
static std::mutex m;
if (sc == IO_LOCK)
m.lock();
if (sc == IO_UNLOCK)
m.unlock();
return os;
}
void sync_cout_start() { std::cout << IO_LOCK; }
void sync_cout_end() { std::cout << IO_UNLOCK; }
// Trampoline helper to avoid moving Logger to misc.h
void start_logger(const std::string& fname) { Logger::start(fname); }
#ifdef NO_PREFETCH
void prefetch(const void*) {}
#else
void prefetch(const void* addr) {
#if defined(_MSC_VER)
_mm_prefetch((char const*) addr, _MM_HINT_T0);
#else
__builtin_prefetch(addr);
#endif
}
#endif
#ifdef _WIN32
#include <direct.h>
#define GETCWD _getcwd
#else
#include <unistd.h>
#define GETCWD getcwd
#endif
size_t str_to_size_t(const std::string& s) {
unsigned long long value = std::stoull(s);
if (value > std::numeric_limits<size_t>::max())
std::exit(EXIT_FAILURE);
return static_cast<size_t>(value);
}
std::optional<std::string> read_file_to_string(const std::string& path) {
std::ifstream f(path, std::ios_base::binary);
if (!f)
return std::nullopt;
return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
}
void remove_whitespace(std::string& s) {
s.erase(std::remove_if(s.begin(), s.end(), [](char c) { return std::isspace(c); }), s.end());
}
bool is_whitespace(std::string_view s) {
return std::all_of(s.begin(), s.end(), [](char c) { return std::isspace(c); });
}
std::string CommandLine::get_binary_directory(std::string argv0) {
std::string pathSeparator;
#ifdef _WIN32
pathSeparator = "\\";
#ifdef _MSC_VER
// Under windows argv[0] may not have the extension. Also _get_pgmptr() had
// issues in some Windows 10 versions, so check returned values carefully.
char* pgmptr = nullptr;
if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
argv0 = pgmptr;
#endif
#else
pathSeparator = "/";
#endif
// Extract the working directory
auto workingDirectory = CommandLine::get_working_directory();
// Extract the binary directory path from argv0
auto binaryDirectory = argv0;
size_t pos = binaryDirectory.find_last_of("\\/");
if (pos == std::string::npos)
binaryDirectory = "." + pathSeparator;
else
binaryDirectory.resize(pos + 1);
// Pattern replacement: "./" at the start of path is replaced by the working directory
if (binaryDirectory.find("." + pathSeparator) == 0)
binaryDirectory.replace(0, 1, workingDirectory);
return binaryDirectory;
}
std::string CommandLine::get_working_directory() {
std::string workingDirectory = "";
char buff[40000];
char* cwd = GETCWD(buff, 40000);
if (cwd)
workingDirectory = cwd;
return workingDirectory;
}
} // namespace Stockfish
| 13,797
|
C++
|
.cpp
| 399
| 29.781955
| 100
| 0.604921
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,038
|
bitboard.cpp
|
official-stockfish_Stockfish/src/bitboard.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bitboard.h"
#include <algorithm>
#include <bitset>
#include <initializer_list>
#include "misc.h"
namespace Stockfish {
uint8_t PopCnt16[1 << 16];
uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
Bitboard LineBB[SQUARE_NB][SQUARE_NB];
Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
alignas(64) Magic Magics[SQUARE_NB][2];
namespace {
Bitboard RookTable[0x19000]; // To store rook attacks
Bitboard BishopTable[0x1480]; // To store bishop attacks
void init_magics(PieceType pt, Bitboard table[], Magic magics[][2]);
// Returns the bitboard of target square for the given step
// from the given square. If the step is off the board, returns empty bitboard.
Bitboard safe_destination(Square s, int step) {
Square to = Square(s + step);
return is_ok(to) && distance(s, to) <= 2 ? square_bb(to) : Bitboard(0);
}
}
// Returns an ASCII representation of a bitboard suitable
// to be printed to standard output. Useful for debugging.
std::string Bitboards::pretty(Bitboard b) {
std::string s = "+---+---+---+---+---+---+---+---+\n";
for (Rank r = RANK_8; r >= RANK_1; --r)
{
for (File f = FILE_A; f <= FILE_H; ++f)
s += b & make_square(f, r) ? "| X " : "| ";
s += "| " + std::to_string(1 + r) + "\n+---+---+---+---+---+---+---+---+\n";
}
s += " a b c d e f g h\n";
return s;
}
// Initializes various bitboard tables. It is called at
// startup and relies on global objects to be already zero-initialized.
void Bitboards::init() {
for (unsigned i = 0; i < (1 << 16); ++i)
PopCnt16[i] = uint8_t(std::bitset<16>(i).count());
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
SquareDistance[s1][s2] = std::max(distance<File>(s1, s2), distance<Rank>(s1, s2));
init_magics(ROOK, RookTable, Magics);
init_magics(BISHOP, BishopTable, Magics);
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
{
PawnAttacks[WHITE][s1] = pawn_attacks_bb<WHITE>(square_bb(s1));
PawnAttacks[BLACK][s1] = pawn_attacks_bb<BLACK>(square_bb(s1));
for (int step : {-9, -8, -7, -1, 1, 7, 8, 9})
PseudoAttacks[KING][s1] |= safe_destination(s1, step);
for (int step : {-17, -15, -10, -6, 6, 10, 15, 17})
PseudoAttacks[KNIGHT][s1] |= safe_destination(s1, step);
PseudoAttacks[QUEEN][s1] = PseudoAttacks[BISHOP][s1] = attacks_bb<BISHOP>(s1, 0);
PseudoAttacks[QUEEN][s1] |= PseudoAttacks[ROOK][s1] = attacks_bb<ROOK>(s1, 0);
for (PieceType pt : {BISHOP, ROOK})
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
{
if (PseudoAttacks[pt][s1] & s2)
{
LineBB[s1][s2] = (attacks_bb(pt, s1, 0) & attacks_bb(pt, s2, 0)) | s1 | s2;
BetweenBB[s1][s2] =
(attacks_bb(pt, s1, square_bb(s2)) & attacks_bb(pt, s2, square_bb(s1)));
}
BetweenBB[s1][s2] |= s2;
}
}
}
namespace {
Bitboard sliding_attack(PieceType pt, Square sq, Bitboard occupied) {
Bitboard attacks = 0;
Direction RookDirections[4] = {NORTH, SOUTH, EAST, WEST};
Direction BishopDirections[4] = {NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST};
for (Direction d : (pt == ROOK ? RookDirections : BishopDirections))
{
Square s = sq;
while (safe_destination(s, d))
{
attacks |= (s += d);
if (occupied & s)
{
break;
}
}
}
return attacks;
}
// Computes all rook and bishop attacks at startup. Magic
// bitboards are used to look up attacks of sliding pieces. As a reference see
// https://www.chessprogramming.org/Magic_Bitboards. In particular, here we use
// the so called "fancy" approach.
void init_magics(PieceType pt, Bitboard table[], Magic magics[][2]) {
#ifndef USE_PEXT
// Optimal PRNG seeds to pick the correct magics in the shortest time
int seeds[][RANK_NB] = {{8977, 44560, 54343, 38998, 5731, 95205, 104912, 17020},
{728, 10316, 55013, 32803, 12281, 15100, 16645, 255}};
Bitboard occupancy[4096];
int epoch[4096] = {}, cnt = 0;
#endif
Bitboard reference[4096];
int size = 0;
for (Square s = SQ_A1; s <= SQ_H8; ++s)
{
// Board edges are not considered in the relevant occupancies
Bitboard edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
// Given a square 's', the mask is the bitboard of sliding attacks from
// 's' computed on an empty board. The index must be big enough to contain
// all the attacks for each possible subset of the mask and so is 2 power
// the number of 1s of the mask. Hence we deduce the size of the shift to
// apply to the 64 or 32 bits word to get the index.
Magic& m = magics[s][pt - BISHOP];
m.mask = sliding_attack(pt, s, 0) & ~edges;
#ifndef USE_PEXT
m.shift = (Is64Bit ? 64 : 32) - popcount(m.mask);
#endif
// Set the offset for the attacks table of the square. We have individual
// table sizes for each square with "Fancy Magic Bitboards".
m.attacks = s == SQ_A1 ? table : magics[s - 1][pt - BISHOP].attacks + size;
size = 0;
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
// store the corresponding sliding attack bitboard in reference[].
Bitboard b = 0;
do
{
#ifndef USE_PEXT
occupancy[size] = b;
#endif
reference[size] = sliding_attack(pt, s, b);
if (HasPext)
m.attacks[pext(b, m.mask)] = reference[size];
size++;
b = (b - m.mask) & m.mask;
} while (b);
#ifndef USE_PEXT
PRNG rng(seeds[Is64Bit][rank_of(s)]);
// Find a magic for square 's' picking up an (almost) random number
// until we find the one that passes the verification test.
for (int i = 0; i < size;)
{
for (m.magic = 0; popcount((m.magic * m.mask) >> 56) < 6;)
m.magic = rng.sparse_rand<Bitboard>();
// A good magic must map every possible occupancy to an index that
// looks up the correct sliding attack in the attacks[s] database.
// Note that we build up the database for square 's' as a side
// effect of verifying the magic. Keep track of the attempt count
// and save it in epoch[], little speed-up trick to avoid resetting
// m.attacks[] after every failed attempt.
for (++cnt, i = 0; i < size; ++i)
{
unsigned idx = m.index(occupancy[i]);
if (epoch[idx] < cnt)
{
epoch[idx] = cnt;
m.attacks[idx] = reference[i];
}
else if (m.attacks[idx] != reference[i])
break;
}
}
#endif
}
}
}
} // namespace Stockfish
| 7,972
|
C++
|
.cpp
| 180
| 36.744444
| 99
| 0.596462
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
12,039
|
uci.cpp
|
official-stockfish_Stockfish/src/uci.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "uci.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <iterator>
#include <optional>
#include <sstream>
#include <string_view>
#include <utility>
#include <vector>
#include "benchmark.h"
#include "engine.h"
#include "memory.h"
#include "movegen.h"
#include "position.h"
#include "score.h"
#include "search.h"
#include "types.h"
#include "ucioption.h"
namespace Stockfish {
constexpr auto BenchmarkCommand = "speedtest";
constexpr auto StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
template<typename... Ts>
struct overload: Ts... {
using Ts::operator()...;
};
template<typename... Ts>
overload(Ts...) -> overload<Ts...>;
void UCIEngine::print_info_string(std::string_view str) {
sync_cout_start();
for (auto& line : split(str, "\n"))
{
if (!is_whitespace(line))
{
std::cout << "info string " << line << '\n';
}
}
sync_cout_end();
}
UCIEngine::UCIEngine(int argc, char** argv) :
engine(argv[0]),
cli(argc, argv) {
engine.get_options().add_info_listener([](const std::optional<std::string>& str) {
if (str.has_value())
print_info_string(*str);
});
init_search_update_listeners();
}
void UCIEngine::init_search_update_listeners() {
engine.set_on_iter([](const auto& i) { on_iter(i); });
engine.set_on_update_no_moves([](const auto& i) { on_update_no_moves(i); });
engine.set_on_update_full(
[this](const auto& i) { on_update_full(i, engine.get_options()["UCI_ShowWDL"]); });
engine.set_on_bestmove([](const auto& bm, const auto& p) { on_bestmove(bm, p); });
engine.set_on_verify_networks([](const auto& s) { print_info_string(s); });
}
void UCIEngine::loop() {
std::string token, cmd;
for (int i = 1; i < cli.argc; ++i)
cmd += std::string(cli.argv[i]) + " ";
do
{
if (cli.argc == 1
&& !getline(std::cin, cmd)) // Wait for an input or an end-of-file (EOF) indication
cmd = "quit";
std::istringstream is(cmd);
token.clear(); // Avoid a stale if getline() returns nothing or a blank line
is >> std::skipws >> token;
if (token == "quit" || token == "stop")
engine.stop();
// The GUI sends 'ponderhit' to tell that the user has played the expected move.
// So, 'ponderhit' is sent if pondering was done on the same move that the user
// has played. The search should continue, but should also switch from pondering
// to the normal search.
else if (token == "ponderhit")
engine.set_ponderhit(false);
else if (token == "uci")
{
sync_cout << "id name " << engine_info(true) << "\n"
<< engine.get_options() << sync_endl;
sync_cout << "uciok" << sync_endl;
}
else if (token == "setoption")
setoption(is);
else if (token == "go")
{
// send info strings after the go command is sent for old GUIs and python-chess
print_info_string(engine.numa_config_information_as_string());
print_info_string(engine.thread_allocation_information_as_string());
go(is);
}
else if (token == "position")
position(is);
else if (token == "ucinewgame")
engine.search_clear();
else if (token == "isready")
sync_cout << "readyok" << sync_endl;
// Add custom non-UCI commands, mainly for debugging purposes.
// These commands must not be used during a search!
else if (token == "flip")
engine.flip();
else if (token == "bench")
bench(is);
else if (token == BenchmarkCommand)
benchmark(is);
else if (token == "d")
sync_cout << engine.visualize() << sync_endl;
else if (token == "eval")
engine.trace_eval();
else if (token == "compiler")
sync_cout << compiler_info() << sync_endl;
else if (token == "export_net")
{
std::pair<std::optional<std::string>, std::string> files[2];
if (is >> std::skipws >> files[0].second)
files[0].first = files[0].second;
if (is >> std::skipws >> files[1].second)
files[1].first = files[1].second;
engine.save_network(files);
}
else if (token == "--help" || token == "help" || token == "--license" || token == "license")
sync_cout
<< "\nStockfish is a powerful chess engine for playing and analyzing."
"\nIt is released as free software licensed under the GNU GPLv3 License."
"\nStockfish is normally used with a graphical user interface (GUI) and implements"
"\nthe Universal Chess Interface (UCI) protocol to communicate with a GUI, an API, etc."
"\nFor any further information, visit https://github.com/official-stockfish/Stockfish#readme"
"\nor read the corresponding README.md and Copying.txt files distributed along with this program.\n"
<< sync_endl;
else if (!token.empty() && token[0] != '#')
sync_cout << "Unknown command: '" << cmd << "'. Type help for more information."
<< sync_endl;
} while (token != "quit" && cli.argc == 1); // The command-line arguments are one-shot
}
Search::LimitsType UCIEngine::parse_limits(std::istream& is) {
Search::LimitsType limits;
std::string token;
limits.startTime = now(); // The search starts as early as possible
while (is >> token)
if (token == "searchmoves") // Needs to be the last command on the line
while (is >> token)
limits.searchmoves.push_back(to_lower(token));
else if (token == "wtime")
is >> limits.time[WHITE];
else if (token == "btime")
is >> limits.time[BLACK];
else if (token == "winc")
is >> limits.inc[WHITE];
else if (token == "binc")
is >> limits.inc[BLACK];
else if (token == "movestogo")
is >> limits.movestogo;
else if (token == "depth")
is >> limits.depth;
else if (token == "nodes")
is >> limits.nodes;
else if (token == "movetime")
is >> limits.movetime;
else if (token == "mate")
is >> limits.mate;
else if (token == "perft")
is >> limits.perft;
else if (token == "infinite")
limits.infinite = 1;
else if (token == "ponder")
limits.ponderMode = true;
return limits;
}
void UCIEngine::go(std::istringstream& is) {
Search::LimitsType limits = parse_limits(is);
if (limits.perft)
perft(limits);
else
engine.go(limits);
}
void UCIEngine::bench(std::istream& args) {
std::string token;
uint64_t num, nodes = 0, cnt = 1;
uint64_t nodesSearched = 0;
const auto& options = engine.get_options();
engine.set_on_update_full([&](const auto& i) {
nodesSearched = i.nodes;
on_update_full(i, options["UCI_ShowWDL"]);
});
std::vector<std::string> list = Benchmark::setup_bench(engine.fen(), args);
num = count_if(list.begin(), list.end(),
[](const std::string& s) { return s.find("go ") == 0 || s.find("eval") == 0; });
TimePoint elapsed = now();
for (const auto& cmd : list)
{
std::istringstream is(cmd);
is >> std::skipws >> token;
if (token == "go" || token == "eval")
{
std::cerr << "\nPosition: " << cnt++ << '/' << num << " (" << engine.fen() << ")"
<< std::endl;
if (token == "go")
{
Search::LimitsType limits = parse_limits(is);
if (limits.perft)
nodesSearched = perft(limits);
else
{
engine.go(limits);
engine.wait_for_search_finished();
}
nodes += nodesSearched;
nodesSearched = 0;
}
else
engine.trace_eval();
}
else if (token == "setoption")
setoption(is);
else if (token == "position")
position(is);
else if (token == "ucinewgame")
{
engine.search_clear(); // search_clear may take a while
elapsed = now();
}
}
elapsed = now() - elapsed + 1; // Ensure positivity to avoid a 'divide by zero'
dbg_print();
std::cerr << "\n===========================" //
<< "\nTotal time (ms) : " << elapsed //
<< "\nNodes searched : " << nodes //
<< "\nNodes/second : " << 1000 * nodes / elapsed << std::endl;
// reset callback, to not capture a dangling reference to nodesSearched
engine.set_on_update_full([&](const auto& i) { on_update_full(i, options["UCI_ShowWDL"]); });
}
void UCIEngine::benchmark(std::istream& args) {
// Probably not very important for a test this long, but include for completeness and sanity.
static constexpr int NUM_WARMUP_POSITIONS = 3;
std::string token;
uint64_t nodes = 0, cnt = 1;
uint64_t nodesSearched = 0;
engine.set_on_update_full([&](const Engine::InfoFull& i) { nodesSearched = i.nodes; });
engine.set_on_iter([](const auto&) {});
engine.set_on_update_no_moves([](const auto&) {});
engine.set_on_bestmove([](const auto&, const auto&) {});
engine.set_on_verify_networks([](const auto&) {});
Benchmark::BenchmarkSetup setup = Benchmark::setup_benchmark(args);
const int numGoCommands = count_if(setup.commands.begin(), setup.commands.end(),
[](const std::string& s) { return s.find("go ") == 0; });
TimePoint totalTime = 0;
// Set options once at the start.
auto ss = std::istringstream("name Threads value " + std::to_string(setup.threads));
setoption(ss);
ss = std::istringstream("name Hash value " + std::to_string(setup.ttSize));
setoption(ss);
ss = std::istringstream("name UCI_Chess960 value false");
setoption(ss);
// Warmup
for (const auto& cmd : setup.commands)
{
std::istringstream is(cmd);
is >> std::skipws >> token;
if (token == "go")
{
// One new line is produced by the search, so omit it here
std::cerr << "\rWarmup position " << cnt++ << '/' << NUM_WARMUP_POSITIONS;
Search::LimitsType limits = parse_limits(is);
TimePoint elapsed = now();
// Run with silenced network verification
engine.go(limits);
engine.wait_for_search_finished();
totalTime += now() - elapsed;
nodes += nodesSearched;
nodesSearched = 0;
}
else if (token == "position")
position(is);
else if (token == "ucinewgame")
{
engine.search_clear(); // search_clear may take a while
}
if (cnt > NUM_WARMUP_POSITIONS)
break;
}
std::cerr << "\n";
cnt = 1;
nodes = 0;
int numHashfullReadings = 0;
constexpr int hashfullAges[] = {0, 999}; // Only normal hashfull and touched hash.
int totalHashfull[std::size(hashfullAges)] = {0};
int maxHashfull[std::size(hashfullAges)] = {0};
auto updateHashfullReadings = [&]() {
numHashfullReadings += 1;
for (int i = 0; i < static_cast<int>(std::size(hashfullAges)); ++i)
{
const int hashfull = engine.get_hashfull(hashfullAges[i]);
maxHashfull[i] = std::max(maxHashfull[i], hashfull);
totalHashfull[i] += hashfull;
}
};
engine.search_clear(); // search_clear may take a while
for (const auto& cmd : setup.commands)
{
std::istringstream is(cmd);
is >> std::skipws >> token;
if (token == "go")
{
// One new line is produced by the search, so omit it here
std::cerr << "\rPosition " << cnt++ << '/' << numGoCommands;
Search::LimitsType limits = parse_limits(is);
TimePoint elapsed = now();
// Run with silenced network verification
engine.go(limits);
engine.wait_for_search_finished();
totalTime += now() - elapsed;
updateHashfullReadings();
nodes += nodesSearched;
nodesSearched = 0;
}
else if (token == "position")
position(is);
else if (token == "ucinewgame")
{
engine.search_clear(); // search_clear may take a while
}
}
totalTime = std::max<TimePoint>(totalTime, 1); // Ensure positivity to avoid a 'divide by zero'
dbg_print();
std::cerr << "\n";
static_assert(
std::size(hashfullAges) == 2 && hashfullAges[0] == 0 && hashfullAges[1] == 999,
"Hardcoded for display. Would complicate the code needlessly in the current state.");
std::string threadBinding = engine.thread_binding_information_as_string();
if (threadBinding.empty())
threadBinding = "none";
// clang-format off
std::cerr << "==========================="
<< "\nVersion : "
<< engine_version_info()
// "\nCompiled by : "
<< compiler_info()
<< "Large pages : " << (has_large_pages() ? "yes" : "no")
<< "\nUser invocation : " << BenchmarkCommand << " "
<< setup.originalInvocation << "\nFilled invocation : " << BenchmarkCommand
<< " " << setup.filledInvocation
<< "\nAvailable processors : " << engine.get_numa_config_as_string()
<< "\nThread count : " << setup.threads
<< "\nThread binding : " << threadBinding
<< "\nTT size [MiB] : " << setup.ttSize
<< "\nHash max, avg [per mille] : "
<< "\n single search : " << maxHashfull[0] << ", "
<< totalHashfull[0] / numHashfullReadings
<< "\n single game : " << maxHashfull[1] << ", "
<< totalHashfull[1] / numHashfullReadings
<< "\nTotal nodes searched : " << nodes
<< "\nTotal search time [s] : " << totalTime / 1000.0
<< "\nNodes/second : " << 1000 * nodes / totalTime << std::endl;
// clang-format on
init_search_update_listeners();
}
void UCIEngine::setoption(std::istringstream& is) {
engine.wait_for_search_finished();
engine.get_options().setoption(is);
}
std::uint64_t UCIEngine::perft(const Search::LimitsType& limits) {
auto nodes = engine.perft(engine.fen(), limits.perft, engine.get_options()["UCI_Chess960"]);
sync_cout << "\nNodes searched: " << nodes << "\n" << sync_endl;
return nodes;
}
void UCIEngine::position(std::istringstream& is) {
std::string token, fen;
is >> token;
if (token == "startpos")
{
fen = StartFEN;
is >> token; // Consume the "moves" token, if any
}
else if (token == "fen")
while (is >> token && token != "moves")
fen += token + " ";
else
return;
std::vector<std::string> moves;
while (is >> token)
{
moves.push_back(token);
}
engine.set_position(fen, moves);
}
namespace {
struct WinRateParams {
double a;
double b;
};
WinRateParams win_rate_params(const Position& pos) {
int material = pos.count<PAWN>() + 3 * pos.count<KNIGHT>() + 3 * pos.count<BISHOP>()
+ 5 * pos.count<ROOK>() + 9 * pos.count<QUEEN>();
// The fitted model only uses data for material counts in [17, 78], and is anchored at count 58.
double m = std::clamp(material, 17, 78) / 58.0;
// Return a = p_a(material) and b = p_b(material), see github.com/official-stockfish/WDL_model
constexpr double as[] = {-37.45051876, 121.19101539, -132.78783573, 420.70576692};
constexpr double bs[] = {90.26261072, -137.26549898, 71.10130540, 51.35259597};
double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
return {a, b};
}
// The win rate model is 1 / (1 + exp((a - eval) / b)), where a = p_a(material) and b = p_b(material).
// It fits the LTC fishtest statistics rather accurately.
int win_rate_model(Value v, const Position& pos) {
auto [a, b] = win_rate_params(pos);
// Return the win rate in per mille units, rounded to the nearest integer.
return int(0.5 + 1000 / (1 + std::exp((a - double(v)) / b)));
}
}
std::string UCIEngine::format_score(const Score& s) {
constexpr int TB_CP = 20000;
const auto format =
overload{[](Score::Mate mate) -> std::string {
auto m = (mate.plies > 0 ? (mate.plies + 1) : mate.plies) / 2;
return std::string("mate ") + std::to_string(m);
},
[](Score::Tablebase tb) -> std::string {
return std::string("cp ")
+ std::to_string((tb.win ? TB_CP - tb.plies : -TB_CP - tb.plies));
},
[](Score::InternalUnits units) -> std::string {
return std::string("cp ") + std::to_string(units.value);
}};
return s.visit(format);
}
// Turns a Value to an integer centipawn number,
// without treatment of mate and similar special scores.
int UCIEngine::to_cp(Value v, const Position& pos) {
// In general, the score can be defined via the WDL as
// (log(1/L - 1) - log(1/W - 1)) / (log(1/L - 1) + log(1/W - 1)).
// Based on our win_rate_model, this simply yields v / a.
auto [a, b] = win_rate_params(pos);
return std::round(100 * int(v) / a);
}
std::string UCIEngine::wdl(Value v, const Position& pos) {
std::stringstream ss;
int wdl_w = win_rate_model(v, pos);
int wdl_l = win_rate_model(-v, pos);
int wdl_d = 1000 - wdl_w - wdl_l;
ss << wdl_w << " " << wdl_d << " " << wdl_l;
return ss.str();
}
std::string UCIEngine::square(Square s) {
return std::string{char('a' + file_of(s)), char('1' + rank_of(s))};
}
std::string UCIEngine::move(Move m, bool chess960) {
if (m == Move::none())
return "(none)";
if (m == Move::null())
return "0000";
Square from = m.from_sq();
Square to = m.to_sq();
if (m.type_of() == CASTLING && !chess960)
to = make_square(to > from ? FILE_G : FILE_C, rank_of(from));
std::string move = square(from) + square(to);
if (m.type_of() == PROMOTION)
move += " pnbrqk"[m.promotion_type()];
return move;
}
std::string UCIEngine::to_lower(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return std::tolower(c); });
return str;
}
Move UCIEngine::to_move(const Position& pos, std::string str) {
str = to_lower(str);
for (const auto& m : MoveList<LEGAL>(pos))
if (str == move(m, pos.is_chess960()))
return m;
return Move::none();
}
void UCIEngine::on_update_no_moves(const Engine::InfoShort& info) {
sync_cout << "info depth " << info.depth << " score " << format_score(info.score) << sync_endl;
}
void UCIEngine::on_update_full(const Engine::InfoFull& info, bool showWDL) {
std::stringstream ss;
ss << "info";
ss << " depth " << info.depth //
<< " seldepth " << info.selDepth //
<< " multipv " << info.multiPV //
<< " score " << format_score(info.score); //
if (showWDL)
ss << " wdl " << info.wdl;
if (!info.bound.empty())
ss << " " << info.bound;
ss << " nodes " << info.nodes //
<< " nps " << info.nps //
<< " hashfull " << info.hashfull //
<< " tbhits " << info.tbHits //
<< " time " << info.timeMs //
<< " pv " << info.pv; //
sync_cout << ss.str() << sync_endl;
}
void UCIEngine::on_iter(const Engine::InfoIter& info) {
std::stringstream ss;
ss << "info";
ss << " depth " << info.depth //
<< " currmove " << info.currmove //
<< " currmovenumber " << info.currmovenumber; //
sync_cout << ss.str() << sync_endl;
}
void UCIEngine::on_bestmove(std::string_view bestmove, std::string_view ponder) {
sync_cout << "bestmove " << bestmove;
if (!ponder.empty())
std::cout << " ponder " << ponder;
std::cout << sync_endl;
}
} // namespace Stockfish
| 21,780
|
C++
|
.cpp
| 523
| 33.560229
| 117
| 0.556434
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,040
|
tune.cpp
|
official-stockfish_Stockfish/src/tune.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tune.h"
#include <algorithm>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include "ucioption.h"
using std::string;
namespace Stockfish {
bool Tune::update_on_last;
const Option* LastOption = nullptr;
OptionsMap* Tune::options;
namespace {
std::map<std::string, int> TuneResults;
std::optional<std::string> on_tune(const Option& o) {
if (!Tune::update_on_last || LastOption == &o)
Tune::read_options();
return std::nullopt;
}
}
void Tune::make_option(OptionsMap* opts, const string& n, int v, const SetRange& r) {
// Do not generate option when there is nothing to tune (ie. min = max)
if (r(v).first == r(v).second)
return;
if (TuneResults.count(n))
v = TuneResults[n];
(*opts)[n] << Option(v, r(v).first, r(v).second, on_tune);
LastOption = &((*opts)[n]);
// Print formatted parameters, ready to be copy-pasted in Fishtest
std::cout << n << "," //
<< v << "," //
<< r(v).first << "," //
<< r(v).second << "," //
<< (r(v).second - r(v).first) / 20.0 << "," //
<< "0.0020" << std::endl;
}
string Tune::next(string& names, bool pop) {
string name;
do
{
string token = names.substr(0, names.find(','));
if (pop)
names.erase(0, token.size() + 1);
std::stringstream ws(token);
name += (ws >> token, token); // Remove trailing whitespace
} while (std::count(name.begin(), name.end(), '(') - std::count(name.begin(), name.end(), ')'));
return name;
}
template<>
void Tune::Entry<int>::init_option() {
make_option(options, name, value, range);
}
template<>
void Tune::Entry<int>::read_option() {
if (options->count(name))
value = int((*options)[name]);
}
// Instead of a variable here we have a PostUpdate function: just call it
template<>
void Tune::Entry<Tune::PostUpdate>::init_option() {}
template<>
void Tune::Entry<Tune::PostUpdate>::read_option() {
value();
}
} // namespace Stockfish
// Init options with tuning session results instead of default values. Useful to
// get correct bench signature after a tuning session or to test tuned values.
// Just copy fishtest tuning results in a result.txt file and extract the
// values with:
//
// cat results.txt | sed 's/^param: \([^,]*\), best: \([^,]*\).*/ TuneResults["\1"] = int(round(\2));/'
//
// Then paste the output below, as the function body
namespace Stockfish {
void Tune::read_results() { /* ...insert your values here... */ }
} // namespace Stockfish
| 3,512
|
C++
|
.cpp
| 91
| 34.593407
| 104
| 0.634968
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,042
|
network.cpp
|
official-stockfish_Stockfish/src/nnue/network.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "network.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <memory>
#include <optional>
#include <type_traits>
#include <vector>
#include "../evaluate.h"
#include "../incbin/incbin.h"
#include "../memory.h"
#include "../misc.h"
#include "../position.h"
#include "../types.h"
#include "nnue_architecture.h"
#include "nnue_common.h"
#include "nnue_misc.h"
namespace {
// Macro to embed the default efficiently updatable neural network (NNUE) file
// data in the engine binary (using incbin.h, by Dale Weiler).
// This macro invocation will declare the following three variables
// const unsigned char gEmbeddedNNUEData[]; // a pointer to the embedded data
// const unsigned char *const gEmbeddedNNUEEnd; // a marker to the end
// const unsigned int gEmbeddedNNUESize; // the size of the embedded file
// Note that this does not work in Microsoft Visual Studio.
#if !defined(_MSC_VER) && !defined(NNUE_EMBEDDING_OFF)
INCBIN(EmbeddedNNUEBig, EvalFileDefaultNameBig);
INCBIN(EmbeddedNNUESmall, EvalFileDefaultNameSmall);
#else
const unsigned char gEmbeddedNNUEBigData[1] = {0x0};
const unsigned char* const gEmbeddedNNUEBigEnd = &gEmbeddedNNUEBigData[1];
const unsigned int gEmbeddedNNUEBigSize = 1;
const unsigned char gEmbeddedNNUESmallData[1] = {0x0};
const unsigned char* const gEmbeddedNNUESmallEnd = &gEmbeddedNNUESmallData[1];
const unsigned int gEmbeddedNNUESmallSize = 1;
#endif
struct EmbeddedNNUE {
EmbeddedNNUE(const unsigned char* embeddedData,
const unsigned char* embeddedEnd,
const unsigned int embeddedSize) :
data(embeddedData),
end(embeddedEnd),
size(embeddedSize) {}
const unsigned char* data;
const unsigned char* end;
const unsigned int size;
};
using namespace Stockfish::Eval::NNUE;
EmbeddedNNUE get_embedded(EmbeddedNNUEType type) {
if (type == EmbeddedNNUEType::BIG)
return EmbeddedNNUE(gEmbeddedNNUEBigData, gEmbeddedNNUEBigEnd, gEmbeddedNNUEBigSize);
else
return EmbeddedNNUE(gEmbeddedNNUESmallData, gEmbeddedNNUESmallEnd, gEmbeddedNNUESmallSize);
}
}
namespace Stockfish::Eval::NNUE {
namespace Detail {
// Read evaluation function parameters
template<typename T>
bool read_parameters(std::istream& stream, T& reference) {
std::uint32_t header;
header = read_little_endian<std::uint32_t>(stream);
if (!stream || header != T::get_hash_value())
return false;
return reference.read_parameters(stream);
}
// Write evaluation function parameters
template<typename T>
bool write_parameters(std::ostream& stream, const T& reference) {
write_little_endian<std::uint32_t>(stream, T::get_hash_value());
return reference.write_parameters(stream);
}
} // namespace Detail
template<typename Arch, typename Transformer>
Network<Arch, Transformer>::Network(const Network<Arch, Transformer>& other) :
evalFile(other.evalFile),
embeddedType(other.embeddedType) {
if (other.featureTransformer)
featureTransformer = make_unique_large_page<Transformer>(*other.featureTransformer);
network = make_unique_aligned<Arch[]>(LayerStacks);
if (!other.network)
return;
for (std::size_t i = 0; i < LayerStacks; ++i)
network[i] = other.network[i];
}
template<typename Arch, typename Transformer>
Network<Arch, Transformer>&
Network<Arch, Transformer>::operator=(const Network<Arch, Transformer>& other) {
evalFile = other.evalFile;
embeddedType = other.embeddedType;
if (other.featureTransformer)
featureTransformer = make_unique_large_page<Transformer>(*other.featureTransformer);
network = make_unique_aligned<Arch[]>(LayerStacks);
if (!other.network)
return *this;
for (std::size_t i = 0; i < LayerStacks; ++i)
network[i] = other.network[i];
return *this;
}
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::load(const std::string& rootDirectory, std::string evalfilePath) {
#if defined(DEFAULT_NNUE_DIRECTORY)
std::vector<std::string> dirs = {"<internal>", "", rootDirectory,
stringify(DEFAULT_NNUE_DIRECTORY)};
#else
std::vector<std::string> dirs = {"<internal>", "", rootDirectory};
#endif
if (evalfilePath.empty())
evalfilePath = evalFile.defaultName;
for (const auto& directory : dirs)
{
if (evalFile.current != evalfilePath)
{
if (directory != "<internal>")
{
load_user_net(directory, evalfilePath);
}
if (directory == "<internal>" && evalfilePath == evalFile.defaultName)
{
load_internal();
}
}
}
}
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::save(const std::optional<std::string>& filename) const {
std::string actualFilename;
std::string msg;
if (filename.has_value())
actualFilename = filename.value();
else
{
if (evalFile.current != evalFile.defaultName)
{
msg = "Failed to export a net. "
"A non-embedded net can only be saved if the filename is specified";
sync_cout << msg << sync_endl;
return false;
}
actualFilename = evalFile.defaultName;
}
std::ofstream stream(actualFilename, std::ios_base::binary);
bool saved = save(stream, evalFile.current, evalFile.netDescription);
msg = saved ? "Network saved successfully to " + actualFilename : "Failed to export a net";
sync_cout << msg << sync_endl;
return saved;
}
template<typename Arch, typename Transformer>
NetworkOutput
Network<Arch, Transformer>::evaluate(const Position& pos,
AccumulatorCaches::Cache<FTDimensions>* cache) const {
// We manually align the arrays on the stack because with gcc < 9.3
// overaligning stack variables with alignas() doesn't work correctly.
constexpr uint64_t alignment = CacheLineSize;
#if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
TransformedFeatureType
transformedFeaturesUnaligned[FeatureTransformer<FTDimensions, nullptr>::BufferSize
+ alignment / sizeof(TransformedFeatureType)];
auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
#else
alignas(alignment) TransformedFeatureType
transformedFeatures[FeatureTransformer<FTDimensions, nullptr>::BufferSize];
#endif
ASSERT_ALIGNED(transformedFeatures, alignment);
const int bucket = (pos.count<ALL_PIECES>() - 1) / 4;
const auto psqt = featureTransformer->transform(pos, cache, transformedFeatures, bucket);
const auto positional = network[bucket].propagate(transformedFeatures);
return {static_cast<Value>(psqt / OutputScale), static_cast<Value>(positional / OutputScale)};
}
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::verify(std::string evalfilePath,
const std::function<void(std::string_view)>& f) const {
if (evalfilePath.empty())
evalfilePath = evalFile.defaultName;
if (evalFile.current != evalfilePath)
{
if (f)
{
std::string msg1 =
"Network evaluation parameters compatible with the engine must be available.";
std::string msg2 = "The network file " + evalfilePath + " was not loaded successfully.";
std::string msg3 = "The UCI option EvalFile might need to specify the full path, "
"including the directory name, to the network file.";
std::string msg4 = "The default net can be downloaded from: "
"https://tests.stockfishchess.org/api/nn/"
+ evalFile.defaultName;
std::string msg5 = "The engine will be terminated now.";
std::string msg = "ERROR: " + msg1 + '\n' + "ERROR: " + msg2 + '\n' + "ERROR: " + msg3
+ '\n' + "ERROR: " + msg4 + '\n' + "ERROR: " + msg5 + '\n';
f(msg);
}
exit(EXIT_FAILURE);
}
if (f)
{
size_t size = sizeof(*featureTransformer) + sizeof(Arch) * LayerStacks;
f("info string NNUE evaluation using " + evalfilePath + " ("
+ std::to_string(size / (1024 * 1024)) + "MiB, ("
+ std::to_string(featureTransformer->InputDimensions) + ", "
+ std::to_string(network[0].TransformedFeatureDimensions) + ", "
+ std::to_string(network[0].FC_0_OUTPUTS) + ", " + std::to_string(network[0].FC_1_OUTPUTS)
+ ", 1))");
}
}
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::hint_common_access(
const Position& pos, AccumulatorCaches::Cache<FTDimensions>* cache) const {
featureTransformer->hint_common_access(pos, cache);
}
template<typename Arch, typename Transformer>
NnueEvalTrace
Network<Arch, Transformer>::trace_evaluate(const Position& pos,
AccumulatorCaches::Cache<FTDimensions>* cache) const {
// We manually align the arrays on the stack because with gcc < 9.3
// overaligning stack variables with alignas() doesn't work correctly.
constexpr uint64_t alignment = CacheLineSize;
#if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
TransformedFeatureType
transformedFeaturesUnaligned[FeatureTransformer<FTDimensions, nullptr>::BufferSize
+ alignment / sizeof(TransformedFeatureType)];
auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
#else
alignas(alignment) TransformedFeatureType
transformedFeatures[FeatureTransformer<FTDimensions, nullptr>::BufferSize];
#endif
ASSERT_ALIGNED(transformedFeatures, alignment);
NnueEvalTrace t{};
t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
for (IndexType bucket = 0; bucket < LayerStacks; ++bucket)
{
const auto materialist =
featureTransformer->transform(pos, cache, transformedFeatures, bucket);
const auto positional = network[bucket].propagate(transformedFeatures);
t.psqt[bucket] = static_cast<Value>(materialist / OutputScale);
t.positional[bucket] = static_cast<Value>(positional / OutputScale);
}
return t;
}
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::load_user_net(const std::string& dir,
const std::string& evalfilePath) {
std::ifstream stream(dir + evalfilePath, std::ios::binary);
auto description = load(stream);
if (description.has_value())
{
evalFile.current = evalfilePath;
evalFile.netDescription = description.value();
}
}
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::load_internal() {
// C++ way to prepare a buffer for a memory stream
class MemoryBuffer: public std::basic_streambuf<char> {
public:
MemoryBuffer(char* p, size_t n) {
setg(p, p, p + n);
setp(p, p + n);
}
};
const auto embedded = get_embedded(embeddedType);
MemoryBuffer buffer(const_cast<char*>(reinterpret_cast<const char*>(embedded.data)),
size_t(embedded.size));
std::istream stream(&buffer);
auto description = load(stream);
if (description.has_value())
{
evalFile.current = evalFile.defaultName;
evalFile.netDescription = description.value();
}
}
template<typename Arch, typename Transformer>
void Network<Arch, Transformer>::initialize() {
featureTransformer = make_unique_large_page<Transformer>();
network = make_unique_aligned<Arch[]>(LayerStacks);
}
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::save(std::ostream& stream,
const std::string& name,
const std::string& netDescription) const {
if (name.empty() || name == "None")
return false;
return write_parameters(stream, netDescription);
}
template<typename Arch, typename Transformer>
std::optional<std::string> Network<Arch, Transformer>::load(std::istream& stream) {
initialize();
std::string description;
return read_parameters(stream, description) ? std::make_optional(description) : std::nullopt;
}
// Read network header
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::read_header(std::istream& stream,
std::uint32_t* hashValue,
std::string* desc) const {
std::uint32_t version, size;
version = read_little_endian<std::uint32_t>(stream);
*hashValue = read_little_endian<std::uint32_t>(stream);
size = read_little_endian<std::uint32_t>(stream);
if (!stream || version != Version)
return false;
desc->resize(size);
stream.read(&(*desc)[0], size);
return !stream.fail();
}
// Write network header
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::write_header(std::ostream& stream,
std::uint32_t hashValue,
const std::string& desc) const {
write_little_endian<std::uint32_t>(stream, Version);
write_little_endian<std::uint32_t>(stream, hashValue);
write_little_endian<std::uint32_t>(stream, std::uint32_t(desc.size()));
stream.write(&desc[0], desc.size());
return !stream.fail();
}
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::read_parameters(std::istream& stream,
std::string& netDescription) const {
std::uint32_t hashValue;
if (!read_header(stream, &hashValue, &netDescription))
return false;
if (hashValue != Network::hash)
return false;
if (!Detail::read_parameters(stream, *featureTransformer))
return false;
for (std::size_t i = 0; i < LayerStacks; ++i)
{
if (!Detail::read_parameters(stream, network[i]))
return false;
}
return stream && stream.peek() == std::ios::traits_type::eof();
}
template<typename Arch, typename Transformer>
bool Network<Arch, Transformer>::write_parameters(std::ostream& stream,
const std::string& netDescription) const {
if (!write_header(stream, Network::hash, netDescription))
return false;
if (!Detail::write_parameters(stream, *featureTransformer))
return false;
for (std::size_t i = 0; i < LayerStacks; ++i)
{
if (!Detail::write_parameters(stream, network[i]))
return false;
}
return bool(stream);
}
// Explicit template instantiation
template class Network<
NetworkArchitecture<TransformedFeatureDimensionsBig, L2Big, L3Big>,
FeatureTransformer<TransformedFeatureDimensionsBig, &StateInfo::accumulatorBig>>;
template class Network<
NetworkArchitecture<TransformedFeatureDimensionsSmall, L2Small, L3Small>,
FeatureTransformer<TransformedFeatureDimensionsSmall, &StateInfo::accumulatorSmall>>;
} // namespace Stockfish::Eval::NNUE
| 16,379
|
C++
|
.cpp
| 368
| 37.527174
| 100
| 0.664719
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,043
|
nnue_misc.cpp
|
official-stockfish_Stockfish/src/nnue/nnue_misc.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Code for calculating NNUE evaluation function
#include "nnue_misc.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iosfwd>
#include <iostream>
#include <sstream>
#include <string_view>
#include <tuple>
#include "../evaluate.h"
#include "../position.h"
#include "../types.h"
#include "../uci.h"
#include "network.h"
#include "nnue_accumulator.h"
namespace Stockfish::Eval::NNUE {
constexpr std::string_view PieceToChar(" PNBRQK pnbrqk");
void hint_common_parent_position(const Position& pos,
const Networks& networks,
AccumulatorCaches& caches) {
if (Eval::use_smallnet(pos))
networks.small.hint_common_access(pos, &caches.small);
else
networks.big.hint_common_access(pos, &caches.big);
}
namespace {
// Converts a Value into (centi)pawns and writes it in a buffer.
// The buffer must have capacity for at least 5 chars.
void format_cp_compact(Value v, char* buffer, const Position& pos) {
buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
int cp = std::abs(UCIEngine::to_cp(v, pos));
if (cp >= 10000)
{
buffer[1] = '0' + cp / 10000;
cp %= 10000;
buffer[2] = '0' + cp / 1000;
cp %= 1000;
buffer[3] = '0' + cp / 100;
buffer[4] = ' ';
}
else if (cp >= 1000)
{
buffer[1] = '0' + cp / 1000;
cp %= 1000;
buffer[2] = '0' + cp / 100;
cp %= 100;
buffer[3] = '.';
buffer[4] = '0' + cp / 10;
}
else
{
buffer[1] = '0' + cp / 100;
cp %= 100;
buffer[2] = '.';
buffer[3] = '0' + cp / 10;
cp %= 10;
buffer[4] = '0' + cp / 1;
}
}
// Converts a Value into pawns, always keeping two decimals
void format_cp_aligned_dot(Value v, std::stringstream& stream, const Position& pos) {
const double pawns = std::abs(0.01 * UCIEngine::to_cp(v, pos));
stream << (v < 0 ? '-'
: v > 0 ? '+'
: ' ')
<< std::setiosflags(std::ios::fixed) << std::setw(6) << std::setprecision(2) << pawns;
}
}
// Returns a string with the value of each piece on a board,
// and a table for (PSQT, Layers) values bucket by bucket.
std::string
trace(Position& pos, const Eval::NNUE::Networks& networks, Eval::NNUE::AccumulatorCaches& caches) {
std::stringstream ss;
char board[3 * 8 + 1][8 * 8 + 2];
std::memset(board, ' ', sizeof(board));
for (int row = 0; row < 3 * 8 + 1; ++row)
board[row][8 * 8 + 1] = '\0';
// A lambda to output one box of the board
auto writeSquare = [&board, &pos](File file, Rank rank, Piece pc, Value value) {
const int x = int(file) * 8;
const int y = (7 - int(rank)) * 3;
for (int i = 1; i < 8; ++i)
board[y][x + i] = board[y + 3][x + i] = '-';
for (int i = 1; i < 3; ++i)
board[y + i][x] = board[y + i][x + 8] = '|';
board[y][x] = board[y][x + 8] = board[y + 3][x + 8] = board[y + 3][x] = '+';
if (pc != NO_PIECE)
board[y + 1][x + 4] = PieceToChar[pc];
if (value != VALUE_NONE)
format_cp_compact(value, &board[y + 2][x + 2], pos);
};
// We estimate the value of each piece by doing a differential evaluation from
// the current base eval, simulating the removal of the piece from its square.
auto [psqt, positional] = networks.big.evaluate(pos, &caches.big);
Value base = psqt + positional;
base = pos.side_to_move() == WHITE ? base : -base;
for (File f = FILE_A; f <= FILE_H; ++f)
for (Rank r = RANK_1; r <= RANK_8; ++r)
{
Square sq = make_square(f, r);
Piece pc = pos.piece_on(sq);
Value v = VALUE_NONE;
if (pc != NO_PIECE && type_of(pc) != KING)
{
auto st = pos.state();
pos.remove_piece(sq);
st->accumulatorBig.computed[WHITE] = st->accumulatorBig.computed[BLACK] = false;
std::tie(psqt, positional) = networks.big.evaluate(pos, &caches.big);
Value eval = psqt + positional;
eval = pos.side_to_move() == WHITE ? eval : -eval;
v = base - eval;
pos.put_piece(pc, sq);
st->accumulatorBig.computed[WHITE] = st->accumulatorBig.computed[BLACK] = false;
}
writeSquare(f, r, pc, v);
}
ss << " NNUE derived piece values:\n";
for (int row = 0; row < 3 * 8 + 1; ++row)
ss << board[row] << '\n';
ss << '\n';
auto t = networks.big.trace_evaluate(pos, &caches.big);
ss << " NNUE network contributions "
<< (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
<< "+------------+------------+------------+------------+\n"
<< "| Bucket | Material | Positional | Total |\n"
<< "| | (PSQT) | (Layers) | |\n"
<< "+------------+------------+------------+------------+\n";
for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
{
ss << "| " << bucket << " " //
<< " | ";
format_cp_aligned_dot(t.psqt[bucket], ss, pos);
ss << " " //
<< " | ";
format_cp_aligned_dot(t.positional[bucket], ss, pos);
ss << " " //
<< " | ";
format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], ss, pos);
ss << " " //
<< " |";
if (bucket == t.correctBucket)
ss << " <-- this bucket is used";
ss << '\n';
}
ss << "+------------+------------+------------+------------+\n";
return ss.str();
}
} // namespace Stockfish::Eval::NNUE
| 6,675
|
C++
|
.cpp
| 164
| 33.45122
| 99
| 0.525649
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,044
|
half_ka_v2_hm.cpp
|
official-stockfish_Stockfish/src/nnue/features/half_ka_v2_hm.cpp
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//Definition of input features HalfKAv2_hm of NNUE evaluation function
#include "half_ka_v2_hm.h"
#include "../../bitboard.h"
#include "../../position.h"
#include "../../types.h"
#include "../nnue_accumulator.h"
namespace Stockfish::Eval::NNUE::Features {
// Index of a feature for a given king position and another piece on some square
template<Color Perspective>
inline IndexType HalfKAv2_hm::make_index(Square s, Piece pc, Square ksq) {
return IndexType((int(s) ^ OrientTBL[Perspective][ksq]) + PieceSquareIndex[Perspective][pc]
+ KingBuckets[Perspective][ksq]);
}
// Get a list of indices for active features
template<Color Perspective>
void HalfKAv2_hm::append_active_indices(const Position& pos, IndexList& active) {
Square ksq = pos.square<KING>(Perspective);
Bitboard bb = pos.pieces();
while (bb)
{
Square s = pop_lsb(bb);
active.push_back(make_index<Perspective>(s, pos.piece_on(s), ksq));
}
}
// Explicit template instantiations
template void HalfKAv2_hm::append_active_indices<WHITE>(const Position& pos, IndexList& active);
template void HalfKAv2_hm::append_active_indices<BLACK>(const Position& pos, IndexList& active);
template IndexType HalfKAv2_hm::make_index<WHITE>(Square s, Piece pc, Square ksq);
template IndexType HalfKAv2_hm::make_index<BLACK>(Square s, Piece pc, Square ksq);
// Get a list of indices for recently changed features
template<Color Perspective>
void HalfKAv2_hm::append_changed_indices(Square ksq,
const DirtyPiece& dp,
IndexList& removed,
IndexList& added) {
for (int i = 0; i < dp.dirty_num; ++i)
{
if (dp.from[i] != SQ_NONE)
removed.push_back(make_index<Perspective>(dp.from[i], dp.piece[i], ksq));
if (dp.to[i] != SQ_NONE)
added.push_back(make_index<Perspective>(dp.to[i], dp.piece[i], ksq));
}
}
// Explicit template instantiations
template void HalfKAv2_hm::append_changed_indices<WHITE>(Square ksq,
const DirtyPiece& dp,
IndexList& removed,
IndexList& added);
template void HalfKAv2_hm::append_changed_indices<BLACK>(Square ksq,
const DirtyPiece& dp,
IndexList& removed,
IndexList& added);
int HalfKAv2_hm::update_cost(const StateInfo* st) { return st->dirtyPiece.dirty_num; }
int HalfKAv2_hm::refresh_cost(const Position& pos) { return pos.count<ALL_PIECES>(); }
bool HalfKAv2_hm::requires_refresh(const StateInfo* st, Color perspective) {
return st->dirtyPiece.piece[0] == make_piece(perspective, KING);
}
} // namespace Stockfish::Eval::NNUE::Features
| 3,843
|
C++
|
.cpp
| 72
| 43.736111
| 96
| 0.633289
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
12,045
|
benchmark.h
|
official-stockfish_Stockfish/src/benchmark.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BENCHMARK_H_INCLUDED
#define BENCHMARK_H_INCLUDED
#include <iosfwd>
#include <string>
#include <vector>
namespace Stockfish::Benchmark {
std::vector<std::string> setup_bench(const std::string&, std::istream&);
struct BenchmarkSetup {
int ttSize;
int threads;
std::vector<std::string> commands;
std::string originalInvocation;
std::string filledInvocation;
};
BenchmarkSetup setup_benchmark(std::istream&);
} // namespace Stockfish
#endif // #ifndef BENCHMARK_H_INCLUDED
| 1,345
|
C++
|
.h
| 31
| 40.612903
| 72
| 0.733691
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,046
|
perft.h
|
official-stockfish_Stockfish/src/perft.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PERFT_H_INCLUDED
#define PERFT_H_INCLUDED
#include <cstdint>
#include "movegen.h"
#include "position.h"
#include "types.h"
#include "uci.h"
namespace Stockfish::Benchmark {
// Utility to verify move generation. All the leaf nodes up
// to the given depth are generated and counted, and the sum is returned.
template<bool Root>
uint64_t perft(Position& pos, Depth depth) {
StateInfo st;
ASSERT_ALIGNED(&st, Eval::NNUE::CacheLineSize);
uint64_t cnt, nodes = 0;
const bool leaf = (depth == 2);
for (const auto& m : MoveList<LEGAL>(pos))
{
if (Root && depth <= 1)
cnt = 1, nodes++;
else
{
pos.do_move(m, st);
cnt = leaf ? MoveList<LEGAL>(pos).size() : perft<false>(pos, depth - 1);
nodes += cnt;
pos.undo_move(m);
}
if (Root)
sync_cout << UCIEngine::move(m, pos.is_chess960()) << ": " << cnt << sync_endl;
}
return nodes;
}
inline uint64_t perft(const std::string& fen, Depth depth, bool isChess960) {
StateListPtr states(new std::deque<StateInfo>(1));
Position p;
p.set(fen, isChess960, &states->back());
return perft<true>(p, depth);
}
}
#endif // PERFT_H_INCLUDED
| 2,018
|
C++
|
.h
| 54
| 32.703704
| 91
| 0.68
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,047
|
engine.h
|
official-stockfish_Stockfish/src/engine.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ENGINE_H_INCLUDED
#define ENGINE_H_INCLUDED
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "nnue/network.h"
#include "numa.h"
#include "position.h"
#include "search.h"
#include "syzygy/tbprobe.h" // for Stockfish::Depth
#include "thread.h"
#include "tt.h"
#include "ucioption.h"
namespace Stockfish {
enum Square : int;
class Engine {
public:
using InfoShort = Search::InfoShort;
using InfoFull = Search::InfoFull;
using InfoIter = Search::InfoIteration;
Engine(std::optional<std::string> path = std::nullopt);
// Cannot be movable due to components holding backreferences to fields
Engine(const Engine&) = delete;
Engine(Engine&&) = delete;
Engine& operator=(const Engine&) = delete;
Engine& operator=(Engine&&) = delete;
~Engine() { wait_for_search_finished(); }
std::uint64_t perft(const std::string& fen, Depth depth, bool isChess960);
// non blocking call to start searching
void go(Search::LimitsType&);
// non blocking call to stop searching
void stop();
// blocking call to wait for search to finish
void wait_for_search_finished();
// set a new position, moves are in UCI format
void set_position(const std::string& fen, const std::vector<std::string>& moves);
// modifiers
void set_numa_config_from_option(const std::string& o);
void resize_threads();
void set_tt_size(size_t mb);
void set_ponderhit(bool);
void search_clear();
void set_on_update_no_moves(std::function<void(const InfoShort&)>&&);
void set_on_update_full(std::function<void(const InfoFull&)>&&);
void set_on_iter(std::function<void(const InfoIter&)>&&);
void set_on_bestmove(std::function<void(std::string_view, std::string_view)>&&);
void set_on_verify_networks(std::function<void(std::string_view)>&&);
// network related
void verify_networks() const;
void load_networks();
void load_big_network(const std::string& file);
void load_small_network(const std::string& file);
void save_network(const std::pair<std::optional<std::string>, std::string> files[2]);
// utility functions
void trace_eval() const;
const OptionsMap& get_options() const;
OptionsMap& get_options();
int get_hashfull(int maxAge = 0) const;
std::string fen() const;
void flip();
std::string visualize() const;
std::vector<std::pair<size_t, size_t>> get_bound_thread_count_by_numa_node() const;
std::string get_numa_config_as_string() const;
std::string numa_config_information_as_string() const;
std::string thread_allocation_information_as_string() const;
std::string thread_binding_information_as_string() const;
private:
const std::string binaryDirectory;
NumaReplicationContext numaContext;
Position pos;
StateListPtr states;
Square capSq;
OptionsMap options;
ThreadPool threads;
TranspositionTable tt;
LazyNumaReplicated<Eval::NNUE::Networks> networks;
Search::SearchManager::UpdateContext updateContext;
std::function<void(std::string_view)> onVerifyNetworks;
};
} // namespace Stockfish
#endif // #ifndef ENGINE_H_INCLUDED
| 4,383
|
C++
|
.h
| 100
| 39.8
| 91
| 0.668235
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,048
|
uci.h
|
official-stockfish_Stockfish/src/uci.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UCI_H_INCLUDED
#define UCI_H_INCLUDED
#include <cstdint>
#include <iostream>
#include <string>
#include <string_view>
#include "engine.h"
#include "misc.h"
#include "search.h"
namespace Stockfish {
class Position;
class Move;
class Score;
enum Square : int;
using Value = int;
class UCIEngine {
public:
UCIEngine(int argc, char** argv);
void loop();
static int to_cp(Value v, const Position& pos);
static std::string format_score(const Score& s);
static std::string square(Square s);
static std::string move(Move m, bool chess960);
static std::string wdl(Value v, const Position& pos);
static std::string to_lower(std::string str);
static Move to_move(const Position& pos, std::string str);
static Search::LimitsType parse_limits(std::istream& is);
auto& engine_options() { return engine.get_options(); }
private:
Engine engine;
CommandLine cli;
static void print_info_string(std::string_view str);
void go(std::istringstream& is);
void bench(std::istream& args);
void benchmark(std::istream& args);
void position(std::istringstream& is);
void setoption(std::istringstream& is);
std::uint64_t perft(const Search::LimitsType&);
static void on_update_no_moves(const Engine::InfoShort& info);
static void on_update_full(const Engine::InfoFull& info, bool showWDL);
static void on_iter(const Engine::InfoIter& info);
static void on_bestmove(std::string_view bestmove, std::string_view ponder);
void init_search_update_listeners();
};
} // namespace Stockfish
#endif // #ifndef UCI_H_INCLUDED
| 2,455
|
C++
|
.h
| 60
| 37.416667
| 80
| 0.719158
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,050
|
memory.h
|
official-stockfish_Stockfish/src/memory.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MEMORY_H_INCLUDED
#define MEMORY_H_INCLUDED
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "types.h"
namespace Stockfish {
void* std_aligned_alloc(size_t alignment, size_t size);
void std_aligned_free(void* ptr);
// Memory aligned by page size, min alignment: 4096 bytes
void* aligned_large_pages_alloc(size_t size);
void aligned_large_pages_free(void* mem);
bool has_large_pages();
// Frees memory which was placed there with placement new.
// Works for both single objects and arrays of unknown bound.
template<typename T, typename FREE_FUNC>
void memory_deleter(T* ptr, FREE_FUNC free_func) {
if (!ptr)
return;
// Explicitly needed to call the destructor
if constexpr (!std::is_trivially_destructible_v<T>)
ptr->~T();
free_func(ptr);
return;
}
// Frees memory which was placed there with placement new.
// Works for both single objects and arrays of unknown bound.
template<typename T, typename FREE_FUNC>
void memory_deleter_array(T* ptr, FREE_FUNC free_func) {
if (!ptr)
return;
// Move back on the pointer to where the size is allocated
const size_t array_offset = std::max(sizeof(size_t), alignof(T));
char* raw_memory = reinterpret_cast<char*>(ptr) - array_offset;
if constexpr (!std::is_trivially_destructible_v<T>)
{
const size_t size = *reinterpret_cast<size_t*>(raw_memory);
// Explicitly call the destructor for each element in reverse order
for (size_t i = size; i-- > 0;)
ptr[i].~T();
}
free_func(raw_memory);
}
// Allocates memory for a single object and places it there with placement new
template<typename T, typename ALLOC_FUNC, typename... Args>
inline std::enable_if_t<!std::is_array_v<T>, T*> memory_allocator(ALLOC_FUNC alloc_func,
Args&&... args) {
void* raw_memory = alloc_func(sizeof(T));
ASSERT_ALIGNED(raw_memory, alignof(T));
return new (raw_memory) T(std::forward<Args>(args)...);
}
// Allocates memory for an array of unknown bound and places it there with placement new
template<typename T, typename ALLOC_FUNC>
inline std::enable_if_t<std::is_array_v<T>, std::remove_extent_t<T>*>
memory_allocator(ALLOC_FUNC alloc_func, size_t num) {
using ElementType = std::remove_extent_t<T>;
const size_t array_offset = std::max(sizeof(size_t), alignof(ElementType));
// Save the array size in the memory location
char* raw_memory =
reinterpret_cast<char*>(alloc_func(array_offset + num * sizeof(ElementType)));
ASSERT_ALIGNED(raw_memory, alignof(T));
new (raw_memory) size_t(num);
for (size_t i = 0; i < num; ++i)
new (raw_memory + array_offset + i * sizeof(ElementType)) ElementType();
// Need to return the pointer at the start of the array so that
// the indexing in unique_ptr<T[]> works.
return reinterpret_cast<ElementType*>(raw_memory + array_offset);
}
//
//
// aligned large page unique ptr
//
//
template<typename T>
struct LargePageDeleter {
void operator()(T* ptr) const { return memory_deleter<T>(ptr, aligned_large_pages_free); }
};
template<typename T>
struct LargePageArrayDeleter {
void operator()(T* ptr) const { return memory_deleter_array<T>(ptr, aligned_large_pages_free); }
};
template<typename T>
using LargePagePtr =
std::conditional_t<std::is_array_v<T>,
std::unique_ptr<T, LargePageArrayDeleter<std::remove_extent_t<T>>>,
std::unique_ptr<T, LargePageDeleter<T>>>;
// make_unique_large_page for single objects
template<typename T, typename... Args>
std::enable_if_t<!std::is_array_v<T>, LargePagePtr<T>> make_unique_large_page(Args&&... args) {
static_assert(alignof(T) <= 4096,
"aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
T* obj = memory_allocator<T>(aligned_large_pages_alloc, std::forward<Args>(args)...);
return LargePagePtr<T>(obj);
}
// make_unique_large_page for arrays of unknown bound
template<typename T>
std::enable_if_t<std::is_array_v<T>, LargePagePtr<T>> make_unique_large_page(size_t num) {
using ElementType = std::remove_extent_t<T>;
static_assert(alignof(ElementType) <= 4096,
"aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
ElementType* memory = memory_allocator<T>(aligned_large_pages_alloc, num);
return LargePagePtr<T>(memory);
}
//
//
// aligned unique ptr
//
//
template<typename T>
struct AlignedDeleter {
void operator()(T* ptr) const { return memory_deleter<T>(ptr, std_aligned_free); }
};
template<typename T>
struct AlignedArrayDeleter {
void operator()(T* ptr) const { return memory_deleter_array<T>(ptr, std_aligned_free); }
};
template<typename T>
using AlignedPtr =
std::conditional_t<std::is_array_v<T>,
std::unique_ptr<T, AlignedArrayDeleter<std::remove_extent_t<T>>>,
std::unique_ptr<T, AlignedDeleter<T>>>;
// make_unique_aligned for single objects
template<typename T, typename... Args>
std::enable_if_t<!std::is_array_v<T>, AlignedPtr<T>> make_unique_aligned(Args&&... args) {
const auto func = [](size_t size) { return std_aligned_alloc(alignof(T), size); };
T* obj = memory_allocator<T>(func, std::forward<Args>(args)...);
return AlignedPtr<T>(obj);
}
// make_unique_aligned for arrays of unknown bound
template<typename T>
std::enable_if_t<std::is_array_v<T>, AlignedPtr<T>> make_unique_aligned(size_t num) {
using ElementType = std::remove_extent_t<T>;
const auto func = [](size_t size) { return std_aligned_alloc(alignof(ElementType), size); };
ElementType* memory = memory_allocator<T>(func, num);
return AlignedPtr<T>(memory);
}
// Get the first aligned element of an array.
// ptr must point to an array of size at least `sizeof(T) * N + alignment` bytes,
// where N is the number of elements in the array.
template<uintptr_t Alignment, typename T>
T* align_ptr_up(T* ptr) {
static_assert(alignof(T) < Alignment);
const uintptr_t ptrint = reinterpret_cast<uintptr_t>(reinterpret_cast<char*>(ptr));
return reinterpret_cast<T*>(
reinterpret_cast<char*>((ptrint + (Alignment - 1)) / Alignment * Alignment));
}
} // namespace Stockfish
#endif // #ifndef MEMORY_H_INCLUDED
| 7,242
|
C++
|
.h
| 166
| 39.409639
| 100
| 0.697751
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,051
|
position.h
|
official-stockfish_Stockfish/src/position.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef POSITION_H_INCLUDED
#define POSITION_H_INCLUDED
#include <cassert>
#include <deque>
#include <iosfwd>
#include <memory>
#include <string>
#include "bitboard.h"
#include "nnue/nnue_accumulator.h"
#include "nnue/nnue_architecture.h"
#include "types.h"
namespace Stockfish {
class TranspositionTable;
// StateInfo struct stores information needed to restore a Position object to
// its previous state when we retract a move. Whenever a move is made on the
// board (by calling Position::do_move), a StateInfo object must be passed.
struct StateInfo {
// Copied when making a move
Key materialKey;
Key pawnKey;
Key majorPieceKey;
Key minorPieceKey;
Key nonPawnKey[COLOR_NB];
Value nonPawnMaterial[COLOR_NB];
int castlingRights;
int rule50;
int pliesFromNull;
Square epSquare;
// Not copied when making a move (will be recomputed anyhow)
Key key;
Bitboard checkersBB;
StateInfo* previous;
StateInfo* next;
Bitboard blockersForKing[COLOR_NB];
Bitboard pinners[COLOR_NB];
Bitboard checkSquares[PIECE_TYPE_NB];
Piece capturedPiece;
int repetition;
// Used by NNUE
Eval::NNUE::Accumulator<Eval::NNUE::TransformedFeatureDimensionsBig> accumulatorBig;
Eval::NNUE::Accumulator<Eval::NNUE::TransformedFeatureDimensionsSmall> accumulatorSmall;
DirtyPiece dirtyPiece;
};
// A list to keep track of the position states along the setup moves (from the
// start position to the position just before the search starts). Needed by
// 'draw by repetition' detection. Use a std::deque because pointers to
// elements are not invalidated upon list resizing.
using StateListPtr = std::unique_ptr<std::deque<StateInfo>>;
// Position class stores information regarding the board representation as
// pieces, side to move, hash keys, castling info, etc. Important methods are
// do_move() and undo_move(), used by the search to update node info when
// traversing the search tree.
class Position {
public:
static void init();
Position() = default;
Position(const Position&) = delete;
Position& operator=(const Position&) = delete;
// FEN string input/output
Position& set(const std::string& fenStr, bool isChess960, StateInfo* si);
Position& set(const std::string& code, Color c, StateInfo* si);
std::string fen() const;
// Position representation
Bitboard pieces(PieceType pt = ALL_PIECES) const;
template<typename... PieceTypes>
Bitboard pieces(PieceType pt, PieceTypes... pts) const;
Bitboard pieces(Color c) const;
template<typename... PieceTypes>
Bitboard pieces(Color c, PieceTypes... pts) const;
Piece piece_on(Square s) const;
Square ep_square() const;
bool empty(Square s) const;
template<PieceType Pt>
int count(Color c) const;
template<PieceType Pt>
int count() const;
template<PieceType Pt>
Square square(Color c) const;
// Castling
CastlingRights castling_rights(Color c) const;
bool can_castle(CastlingRights cr) const;
bool castling_impeded(CastlingRights cr) const;
Square castling_rook_square(CastlingRights cr) const;
// Checking
Bitboard checkers() const;
Bitboard blockers_for_king(Color c) const;
Bitboard check_squares(PieceType pt) const;
Bitboard pinners(Color c) const;
// Attacks to/from a given square
Bitboard attackers_to(Square s) const;
Bitboard attackers_to(Square s, Bitboard occupied) const;
void update_slider_blockers(Color c) const;
template<PieceType Pt>
Bitboard attacks_by(Color c) const;
// Properties of moves
bool legal(Move m) const;
bool pseudo_legal(const Move m) const;
bool capture(Move m) const;
bool capture_stage(Move m) const;
bool gives_check(Move m) const;
Piece moved_piece(Move m) const;
Piece captured_piece() const;
// Doing and undoing moves
void do_move(Move m, StateInfo& newSt);
void do_move(Move m, StateInfo& newSt, bool givesCheck);
void undo_move(Move m);
void do_null_move(StateInfo& newSt, TranspositionTable& tt);
void undo_null_move();
// Static Exchange Evaluation
bool see_ge(Move m, int threshold = 0) const;
// Accessing hash keys
Key key() const;
Key key_after(Move m) const;
Key material_key() const;
Key pawn_key() const;
Key major_piece_key() const;
Key minor_piece_key() const;
Key non_pawn_key(Color c) const;
// Other properties of the position
Color side_to_move() const;
int game_ply() const;
bool is_chess960() const;
bool is_draw(int ply) const;
bool upcoming_repetition(int ply) const;
bool has_repeated() const;
int rule50_count() const;
Value non_pawn_material(Color c) const;
Value non_pawn_material() const;
// Position consistency check, for debugging
bool pos_is_ok() const;
void flip();
// Used by NNUE
StateInfo* state() const;
void put_piece(Piece pc, Square s);
void remove_piece(Square s);
private:
// Initialization helpers (used while setting up a position)
void set_castling_right(Color c, Square rfrom);
void set_state() const;
void set_check_info() const;
// Other helpers
void move_piece(Square from, Square to);
template<bool Do>
void do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto);
template<bool AfterMove>
Key adjust_key50(Key k) const;
// Data members
Piece board[SQUARE_NB];
Bitboard byTypeBB[PIECE_TYPE_NB];
Bitboard byColorBB[COLOR_NB];
int pieceCount[PIECE_NB];
int castlingRightsMask[SQUARE_NB];
Square castlingRookSquare[CASTLING_RIGHT_NB];
Bitboard castlingPath[CASTLING_RIGHT_NB];
StateInfo* st;
int gamePly;
Color sideToMove;
bool chess960;
};
std::ostream& operator<<(std::ostream& os, const Position& pos);
inline Color Position::side_to_move() const { return sideToMove; }
inline Piece Position::piece_on(Square s) const {
assert(is_ok(s));
return board[s];
}
inline bool Position::empty(Square s) const { return piece_on(s) == NO_PIECE; }
inline Piece Position::moved_piece(Move m) const { return piece_on(m.from_sq()); }
inline Bitboard Position::pieces(PieceType pt) const { return byTypeBB[pt]; }
template<typename... PieceTypes>
inline Bitboard Position::pieces(PieceType pt, PieceTypes... pts) const {
return pieces(pt) | pieces(pts...);
}
inline Bitboard Position::pieces(Color c) const { return byColorBB[c]; }
template<typename... PieceTypes>
inline Bitboard Position::pieces(Color c, PieceTypes... pts) const {
return pieces(c) & pieces(pts...);
}
template<PieceType Pt>
inline int Position::count(Color c) const {
return pieceCount[make_piece(c, Pt)];
}
template<PieceType Pt>
inline int Position::count() const {
return count<Pt>(WHITE) + count<Pt>(BLACK);
}
template<PieceType Pt>
inline Square Position::square(Color c) const {
assert(count<Pt>(c) == 1);
return lsb(pieces(c, Pt));
}
inline Square Position::ep_square() const { return st->epSquare; }
inline bool Position::can_castle(CastlingRights cr) const { return st->castlingRights & cr; }
inline CastlingRights Position::castling_rights(Color c) const {
return c & CastlingRights(st->castlingRights);
}
inline bool Position::castling_impeded(CastlingRights cr) const {
assert(cr == WHITE_OO || cr == WHITE_OOO || cr == BLACK_OO || cr == BLACK_OOO);
return pieces() & castlingPath[cr];
}
inline Square Position::castling_rook_square(CastlingRights cr) const {
assert(cr == WHITE_OO || cr == WHITE_OOO || cr == BLACK_OO || cr == BLACK_OOO);
return castlingRookSquare[cr];
}
inline Bitboard Position::attackers_to(Square s) const { return attackers_to(s, pieces()); }
template<PieceType Pt>
inline Bitboard Position::attacks_by(Color c) const {
if constexpr (Pt == PAWN)
return c == WHITE ? pawn_attacks_bb<WHITE>(pieces(WHITE, PAWN))
: pawn_attacks_bb<BLACK>(pieces(BLACK, PAWN));
else
{
Bitboard threats = 0;
Bitboard attackers = pieces(c, Pt);
while (attackers)
threats |= attacks_bb<Pt>(pop_lsb(attackers), pieces());
return threats;
}
}
inline Bitboard Position::checkers() const { return st->checkersBB; }
inline Bitboard Position::blockers_for_king(Color c) const { return st->blockersForKing[c]; }
inline Bitboard Position::pinners(Color c) const { return st->pinners[c]; }
inline Bitboard Position::check_squares(PieceType pt) const { return st->checkSquares[pt]; }
inline Key Position::key() const { return adjust_key50<false>(st->key); }
template<bool AfterMove>
inline Key Position::adjust_key50(Key k) const {
return st->rule50 < 14 - AfterMove ? k : k ^ make_key((st->rule50 - (14 - AfterMove)) / 8);
}
inline Key Position::pawn_key() const { return st->pawnKey; }
inline Key Position::material_key() const { return st->materialKey; }
inline Key Position::major_piece_key() const { return st->majorPieceKey; }
inline Key Position::minor_piece_key() const { return st->minorPieceKey; }
inline Key Position::non_pawn_key(Color c) const { return st->nonPawnKey[c]; }
inline Value Position::non_pawn_material(Color c) const { return st->nonPawnMaterial[c]; }
inline Value Position::non_pawn_material() const {
return non_pawn_material(WHITE) + non_pawn_material(BLACK);
}
inline int Position::game_ply() const { return gamePly; }
inline int Position::rule50_count() const { return st->rule50; }
inline bool Position::is_chess960() const { return chess960; }
inline bool Position::capture(Move m) const {
assert(m.is_ok());
return (!empty(m.to_sq()) && m.type_of() != CASTLING) || m.type_of() == EN_PASSANT;
}
// Returns true if a move is generated from the capture stage, having also
// queen promotions covered, i.e. consistency with the capture stage move
// generation is needed to avoid the generation of duplicate moves.
inline bool Position::capture_stage(Move m) const {
assert(m.is_ok());
return capture(m) || m.promotion_type() == QUEEN;
}
inline Piece Position::captured_piece() const { return st->capturedPiece; }
inline void Position::put_piece(Piece pc, Square s) {
board[s] = pc;
byTypeBB[ALL_PIECES] |= byTypeBB[type_of(pc)] |= s;
byColorBB[color_of(pc)] |= s;
pieceCount[pc]++;
pieceCount[make_piece(color_of(pc), ALL_PIECES)]++;
}
inline void Position::remove_piece(Square s) {
Piece pc = board[s];
byTypeBB[ALL_PIECES] ^= s;
byTypeBB[type_of(pc)] ^= s;
byColorBB[color_of(pc)] ^= s;
board[s] = NO_PIECE;
pieceCount[pc]--;
pieceCount[make_piece(color_of(pc), ALL_PIECES)]--;
}
inline void Position::move_piece(Square from, Square to) {
Piece pc = board[from];
Bitboard fromTo = from | to;
byTypeBB[ALL_PIECES] ^= fromTo;
byTypeBB[type_of(pc)] ^= fromTo;
byColorBB[color_of(pc)] ^= fromTo;
board[from] = NO_PIECE;
board[to] = pc;
}
inline void Position::do_move(Move m, StateInfo& newSt) { do_move(m, newSt, gives_check(m)); }
inline StateInfo* Position::state() const { return st; }
} // namespace Stockfish
#endif // #ifndef POSITION_H_INCLUDED
| 12,250
|
C++
|
.h
| 294
| 37.704082
| 95
| 0.698728
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,052
|
misc.h
|
official-stockfish_Stockfish/src/misc.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MISC_H_INCLUDED
#define MISC_H_INCLUDED
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <iosfwd>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#define stringify2(x) #x
#define stringify(x) stringify2(x)
namespace Stockfish {
std::string engine_version_info();
std::string engine_info(bool to_uci = false);
std::string compiler_info();
// Preloads the given address in L1/L2 cache. This is a non-blocking
// function that doesn't stall the CPU waiting for data to be loaded from memory,
// which can be quite slow.
void prefetch(const void* addr);
void start_logger(const std::string& fname);
size_t str_to_size_t(const std::string& s);
#if defined(__linux__)
struct PipeDeleter {
void operator()(FILE* file) const {
if (file != nullptr)
{
pclose(file);
}
}
};
#endif
// Reads the file as bytes.
// Returns std::nullopt if the file does not exist.
std::optional<std::string> read_file_to_string(const std::string& path);
void dbg_hit_on(bool cond, int slot = 0);
void dbg_mean_of(int64_t value, int slot = 0);
void dbg_stdev_of(int64_t value, int slot = 0);
void dbg_extremes_of(int64_t value, int slot = 0);
void dbg_correl_of(int64_t value1, int64_t value2, int slot = 0);
void dbg_print();
using TimePoint = std::chrono::milliseconds::rep; // A value in milliseconds
static_assert(sizeof(TimePoint) == sizeof(int64_t), "TimePoint should be 64 bits");
inline TimePoint now() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
inline std::vector<std::string_view> split(std::string_view s, std::string_view delimiter) {
std::vector<std::string_view> res;
if (s.empty())
return res;
size_t begin = 0;
for (;;)
{
const size_t end = s.find(delimiter, begin);
if (end == std::string::npos)
break;
res.emplace_back(s.substr(begin, end - begin));
begin = end + delimiter.size();
}
res.emplace_back(s.substr(begin));
return res;
}
void remove_whitespace(std::string& s);
bool is_whitespace(std::string_view s);
enum SyncCout {
IO_LOCK,
IO_UNLOCK
};
std::ostream& operator<<(std::ostream&, SyncCout);
#define sync_cout std::cout << IO_LOCK
#define sync_endl std::endl << IO_UNLOCK
void sync_cout_start();
void sync_cout_end();
// True if and only if the binary is compiled on a little-endian machine
static inline const union {
uint32_t i;
char c[4];
} Le = {0x01020304};
static inline const bool IsLittleEndian = (Le.c[0] == 4);
template<typename T, std::size_t MaxSize>
class ValueList {
public:
std::size_t size() const { return size_; }
void push_back(const T& value) { values_[size_++] = value; }
const T* begin() const { return values_; }
const T* end() const { return values_ + size_; }
const T& operator[](int index) const { return values_[index]; }
private:
T values_[MaxSize];
std::size_t size_ = 0;
};
// xorshift64star Pseudo-Random Number Generator
// This class is based on original code written and dedicated
// to the public domain by Sebastiano Vigna (2014).
// It has the following characteristics:
//
// - Outputs 64-bit numbers
// - Passes Dieharder and SmallCrush test batteries
// - Does not require warm-up, no zeroland to escape
// - Internal state is a single 64-bit integer
// - Period is 2^64 - 1
// - Speed: 1.60 ns/call (Core i7 @3.40GHz)
//
// For further analysis see
// <http://vigna.di.unimi.it/ftp/papers/xorshift.pdf>
class PRNG {
uint64_t s;
uint64_t rand64() {
s ^= s >> 12, s ^= s << 25, s ^= s >> 27;
return s * 2685821657736338717LL;
}
public:
PRNG(uint64_t seed) :
s(seed) {
assert(seed);
}
template<typename T>
T rand() {
return T(rand64());
}
// Special generator used to fast init magic numbers.
// Output values only have 1/8th of their bits set on average.
template<typename T>
T sparse_rand() {
return T(rand64() & rand64() & rand64());
}
};
inline uint64_t mul_hi64(uint64_t a, uint64_t b) {
#if defined(__GNUC__) && defined(IS_64BIT)
__extension__ using uint128 = unsigned __int128;
return (uint128(a) * uint128(b)) >> 64;
#else
uint64_t aL = uint32_t(a), aH = a >> 32;
uint64_t bL = uint32_t(b), bH = b >> 32;
uint64_t c1 = (aL * bL) >> 32;
uint64_t c2 = aH * bL + c1;
uint64_t c3 = aL * bH + uint32_t(c2);
return aH * bH + (c2 >> 32) + (c3 >> 32);
#endif
}
struct CommandLine {
public:
CommandLine(int _argc, char** _argv) :
argc(_argc),
argv(_argv) {}
static std::string get_binary_directory(std::string argv0);
static std::string get_working_directory();
int argc;
char** argv;
};
namespace Utility {
template<typename T, typename Predicate>
void move_to_front(std::vector<T>& vec, Predicate pred) {
auto it = std::find_if(vec.begin(), vec.end(), pred);
if (it != vec.end())
{
std::rotate(vec.begin(), it, it + 1);
}
}
}
} // namespace Stockfish
#endif // #ifndef MISC_H_INCLUDED
| 6,120
|
C++
|
.h
| 181
| 30.19337
| 92
| 0.664232
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,053
|
score.h
|
official-stockfish_Stockfish/src/score.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SCORE_H_INCLUDED
#define SCORE_H_INCLUDED
#include <variant>
#include <utility>
#include "types.h"
namespace Stockfish {
class Position;
class Score {
public:
struct Mate {
int plies;
};
struct Tablebase {
int plies;
bool win;
};
struct InternalUnits {
int value;
};
Score() = default;
Score(Value v, const Position& pos);
template<typename T>
bool is() const {
return std::holds_alternative<T>(score);
}
template<typename T>
T get() const {
return std::get<T>(score);
}
template<typename F>
decltype(auto) visit(F&& f) const {
return std::visit(std::forward<F>(f), score);
}
private:
std::variant<Mate, Tablebase, InternalUnits> score;
};
}
#endif // #ifndef SCORE_H_INCLUDED
| 1,605
|
C++
|
.h
| 52
| 26.480769
| 71
| 0.70228
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,055
|
movepick.h
|
official-stockfish_Stockfish/src/movepick.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MOVEPICK_H_INCLUDED
#define MOVEPICK_H_INCLUDED
#include "history.h"
#include "movegen.h"
#include "types.h"
namespace Stockfish {
class Position;
// The MovePicker class is used to pick one pseudo-legal move at a time from the
// current position. The most important method is next_move(), which emits one
// new pseudo-legal move on every call, until there are no moves left, when
// Move::none() is returned. In order to improve the efficiency of the alpha-beta
// algorithm, MovePicker attempts to return the moves which are most likely to get
// a cut-off first.
class MovePicker {
enum PickType {
Next,
Best
};
public:
MovePicker(const MovePicker&) = delete;
MovePicker& operator=(const MovePicker&) = delete;
MovePicker(const Position&,
Move,
Depth,
const ButterflyHistory*,
const LowPlyHistory*,
const CapturePieceToHistory*,
const PieceToHistory**,
const PawnHistory*,
int);
MovePicker(const Position&, Move, int, const CapturePieceToHistory*);
Move next_move();
void skip_quiet_moves();
private:
template<PickType T, typename Pred>
Move select(Pred);
template<GenType>
void score();
ExtMove* begin() { return cur; }
ExtMove* end() { return endMoves; }
const Position& pos;
const ButterflyHistory* mainHistory;
const LowPlyHistory* lowPlyHistory;
const CapturePieceToHistory* captureHistory;
const PieceToHistory** continuationHistory;
const PawnHistory* pawnHistory;
Move ttMove;
ExtMove * cur, *endMoves, *endBadCaptures, *beginBadQuiets, *endBadQuiets;
int stage;
int threshold;
Depth depth;
int ply;
bool skipQuiets = false;
ExtMove moves[MAX_MOVES];
};
} // namespace Stockfish
#endif // #ifndef MOVEPICK_H_INCLUDED
| 2,917
|
C++
|
.h
| 71
| 35.971831
| 97
| 0.653249
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,056
|
tt.h
|
official-stockfish_Stockfish/src/tt.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TT_H_INCLUDED
#define TT_H_INCLUDED
#include <cstddef>
#include <cstdint>
#include <tuple>
#include "memory.h"
#include "types.h"
namespace Stockfish {
class ThreadPool;
struct TTEntry;
struct Cluster;
// There is only one global hash table for the engine and all its threads. For chess in particular, we even allow racy
// updates between threads to and from the TT, as taking the time to synchronize access would cost thinking time and
// thus elo. As a hash table, collisions are possible and may cause chess playing issues (bizarre blunders, faulty mate
// reports, etc). Fixing these also loses elo; however such risk decreases quickly with larger TT size.
//
// `probe` is the primary method: given a board position, we lookup its entry in the table, and return a tuple of:
// 1) whether the entry already has this position
// 2) a copy of the prior data (if any) (may be inconsistent due to read races)
// 3) a writer object to this entry
// The copied data and the writer are separated to maintain clear boundaries between local vs global objects.
// A copy of the data already in the entry (possibly collided). `probe` may be racy, resulting in inconsistent data.
struct TTData {
Move move;
Value value, eval;
Depth depth;
Bound bound;
bool is_pv;
};
// This is used to make racy writes to the global TT.
struct TTWriter {
public:
void write(Key k, Value v, bool pv, Bound b, Depth d, Move m, Value ev, uint8_t generation8);
private:
friend class TranspositionTable;
TTEntry* entry;
TTWriter(TTEntry* tte);
};
class TranspositionTable {
public:
~TranspositionTable() { aligned_large_pages_free(table); }
void resize(size_t mbSize, ThreadPool& threads); // Set TT size
void clear(ThreadPool& threads); // Re-initialize memory, multithreaded
int hashfull(int maxAge = 0)
const; // Approximate what fraction of entries (permille) have been written to during this root search
void
new_search(); // This must be called at the beginning of each root search to track entry aging
uint8_t generation() const; // The current age, used when writing new data to the TT
std::tuple<bool, TTData, TTWriter>
probe(const Key key) const; // The main method, whose retvals separate local vs global objects
TTEntry* first_entry(const Key key)
const; // This is the hash function; its only external use is memory prefetching.
private:
friend struct TTEntry;
size_t clusterCount;
Cluster* table = nullptr;
uint8_t generation8 = 0; // Size must be not bigger than TTEntry::genBound8
};
} // namespace Stockfish
#endif // #ifndef TT_H_INCLUDED
| 3,480
|
C++
|
.h
| 74
| 43.810811
| 119
| 0.742164
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,057
|
timeman.h
|
official-stockfish_Stockfish/src/timeman.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TIMEMAN_H_INCLUDED
#define TIMEMAN_H_INCLUDED
#include <cstdint>
#include "misc.h"
#include "types.h"
namespace Stockfish {
class OptionsMap;
namespace Search {
struct LimitsType;
}
// The TimeManagement class computes the optimal time to think depending on
// the maximum available time, the game move number, and other parameters.
class TimeManagement {
public:
void init(Search::LimitsType& limits,
Color us,
int ply,
const OptionsMap& options,
double& originalTimeAdjust);
TimePoint optimum() const;
TimePoint maximum() const;
template<typename FUNC>
TimePoint elapsed(FUNC nodes) const {
return useNodesTime ? TimePoint(nodes()) : elapsed_time();
}
TimePoint elapsed_time() const { return now() - startTime; };
void clear();
void advance_nodes_time(std::int64_t nodes);
private:
TimePoint startTime;
TimePoint optimumTime;
TimePoint maximumTime;
std::int64_t availableNodes = -1; // When in 'nodes as time' mode
bool useNodesTime = false; // True if we are in 'nodes as time' mode
};
} // namespace Stockfish
#endif // #ifndef TIMEMAN_H_INCLUDED
| 2,028
|
C++
|
.h
| 51
| 35.509804
| 83
| 0.710862
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,058
|
search.h
|
official-stockfish_Stockfish/src/search.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SEARCH_H_INCLUDED
#define SEARCH_H_INCLUDED
#include <algorithm>
#include <array>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include "history.h"
#include "misc.h"
#include "nnue/network.h"
#include "nnue/nnue_accumulator.h"
#include "numa.h"
#include "position.h"
#include "score.h"
#include "syzygy/tbprobe.h"
#include "timeman.h"
#include "types.h"
namespace Stockfish {
// Different node types, used as a template parameter
enum NodeType {
NonPV,
PV,
Root
};
class TranspositionTable;
class ThreadPool;
class OptionsMap;
namespace Search {
// Stack struct keeps track of the information we need to remember from nodes
// shallower and deeper in the tree during the search. Each search thread has
// its own array of Stack objects, indexed by the current ply.
struct Stack {
Move* pv;
PieceToHistory* continuationHistory;
CorrectionHistory<PieceTo>* continuationCorrectionHistory;
int ply;
Move currentMove;
Move excludedMove;
Value staticEval;
int statScore;
int moveCount;
bool inCheck;
bool ttPv;
bool ttHit;
int cutoffCnt;
};
// RootMove struct is used for moves at the root of the tree. For each root move
// we store a score and a PV (really a refutation in the case of moves which
// fail low). Score is normally set at -VALUE_INFINITE for all non-pv moves.
struct RootMove {
explicit RootMove(Move m) :
pv(1, m) {}
bool extract_ponder_from_tt(const TranspositionTable& tt, Position& pos);
bool operator==(const Move& m) const { return pv[0] == m; }
// Sort in descending order
bool operator<(const RootMove& m) const {
return m.score != score ? m.score < score : m.previousScore < previousScore;
}
uint64_t effort = 0;
Value score = -VALUE_INFINITE;
Value previousScore = -VALUE_INFINITE;
Value averageScore = -VALUE_INFINITE;
Value meanSquaredScore = -VALUE_INFINITE * VALUE_INFINITE;
Value uciScore = -VALUE_INFINITE;
bool scoreLowerbound = false;
bool scoreUpperbound = false;
int selDepth = 0;
int tbRank = 0;
Value tbScore;
std::vector<Move> pv;
};
using RootMoves = std::vector<RootMove>;
// LimitsType struct stores information sent by the caller about the analysis required.
struct LimitsType {
// Init explicitly due to broken value-initialization of non POD in MSVC
LimitsType() {
time[WHITE] = time[BLACK] = inc[WHITE] = inc[BLACK] = npmsec = movetime = TimePoint(0);
movestogo = depth = mate = perft = infinite = 0;
nodes = 0;
ponderMode = false;
}
bool use_time_management() const { return time[WHITE] || time[BLACK]; }
std::vector<std::string> searchmoves;
TimePoint time[COLOR_NB], inc[COLOR_NB], npmsec, movetime, startTime;
int movestogo, depth, mate, perft, infinite;
uint64_t nodes;
bool ponderMode;
Square capSq;
};
// The UCI stores the uci options, thread pool, and transposition table.
// This struct is used to easily forward data to the Search::Worker class.
struct SharedState {
SharedState(const OptionsMap& optionsMap,
ThreadPool& threadPool,
TranspositionTable& transpositionTable,
const LazyNumaReplicated<Eval::NNUE::Networks>& nets) :
options(optionsMap),
threads(threadPool),
tt(transpositionTable),
networks(nets) {}
const OptionsMap& options;
ThreadPool& threads;
TranspositionTable& tt;
const LazyNumaReplicated<Eval::NNUE::Networks>& networks;
};
class Worker;
// Null Object Pattern, implement a common interface for the SearchManagers.
// A Null Object will be given to non-mainthread workers.
class ISearchManager {
public:
virtual ~ISearchManager() {}
virtual void check_time(Search::Worker&) = 0;
};
struct InfoShort {
int depth;
Score score;
};
struct InfoFull: InfoShort {
int selDepth;
size_t multiPV;
std::string_view wdl;
std::string_view bound;
size_t timeMs;
size_t nodes;
size_t nps;
size_t tbHits;
std::string_view pv;
int hashfull;
};
struct InfoIteration {
int depth;
std::string_view currmove;
size_t currmovenumber;
};
// Skill structure is used to implement strength limit. If we have a UCI_Elo,
// we convert it to an appropriate skill level, anchored to the Stash engine.
// This method is based on a fit of the Elo results for games played between
// Stockfish at various skill levels and various versions of the Stash engine.
// Skill 0 .. 19 now covers CCRL Blitz Elo from 1320 to 3190, approximately
// Reference: https://github.com/vondele/Stockfish/commit/a08b8d4e9711c2
struct Skill {
// Lowest and highest Elo ratings used in the skill level calculation
constexpr static int LowestElo = 1320;
constexpr static int HighestElo = 3190;
Skill(int skill_level, int uci_elo) {
if (uci_elo)
{
double e = double(uci_elo - LowestElo) / (HighestElo - LowestElo);
level = std::clamp((((37.2473 * e - 40.8525) * e + 22.2943) * e - 0.311438), 0.0, 19.0);
}
else
level = double(skill_level);
}
bool enabled() const { return level < 20.0; }
bool time_to_pick(Depth depth) const { return depth == 1 + int(level); }
Move pick_best(const RootMoves&, size_t multiPV);
double level;
Move best = Move::none();
};
// SearchManager manages the search from the main thread. It is responsible for
// keeping track of the time, and storing data strictly related to the main thread.
class SearchManager: public ISearchManager {
public:
using UpdateShort = std::function<void(const InfoShort&)>;
using UpdateFull = std::function<void(const InfoFull&)>;
using UpdateIter = std::function<void(const InfoIteration&)>;
using UpdateBestmove = std::function<void(std::string_view, std::string_view)>;
struct UpdateContext {
UpdateShort onUpdateNoMoves;
UpdateFull onUpdateFull;
UpdateIter onIter;
UpdateBestmove onBestmove;
};
SearchManager(const UpdateContext& updateContext) :
updates(updateContext) {}
void check_time(Search::Worker& worker) override;
void pv(Search::Worker& worker,
const ThreadPool& threads,
const TranspositionTable& tt,
Depth depth);
Stockfish::TimeManagement tm;
double originalTimeAdjust;
int callsCnt;
std::atomic_bool ponder;
std::array<Value, 4> iterValue;
double previousTimeReduction;
Value bestPreviousScore;
Value bestPreviousAverageScore;
bool stopOnPonderhit;
size_t id;
const UpdateContext& updates;
};
class NullSearchManager: public ISearchManager {
public:
void check_time(Search::Worker&) override {}
};
// Search::Worker is the class that does the actual search.
// It is instantiated once per thread, and it is responsible for keeping track
// of the search history, and storing data required for the search.
class Worker {
public:
Worker(SharedState&, std::unique_ptr<ISearchManager>, size_t, NumaReplicatedAccessToken);
// Called at instantiation to initialize reductions tables.
// Reset histories, usually before a new game.
void clear();
// Called when the program receives the UCI 'go' command.
// It searches from the root position and outputs the "bestmove".
void start_searching();
bool is_mainthread() const { return threadIdx == 0; }
void ensure_network_replicated();
// Public because they need to be updatable by the stats
ButterflyHistory mainHistory;
LowPlyHistory lowPlyHistory;
CapturePieceToHistory captureHistory;
ContinuationHistory continuationHistory[2][2];
PawnHistory pawnHistory;
CorrectionHistory<Pawn> pawnCorrectionHistory;
CorrectionHistory<Major> majorPieceCorrectionHistory;
CorrectionHistory<Minor> minorPieceCorrectionHistory;
CorrectionHistory<NonPawn> nonPawnCorrectionHistory[COLOR_NB];
CorrectionHistory<Continuation> continuationCorrectionHistory;
private:
void iterative_deepening();
// This is the main search function, for both PV and non-PV nodes
template<NodeType nodeType>
Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode);
// Quiescence search function, which is called by the main search
template<NodeType nodeType>
Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta);
Depth reduction(bool i, Depth d, int mn, int delta) const;
// Pointer to the search manager, only allowed to be called by the main thread
SearchManager* main_manager() const {
assert(threadIdx == 0);
return static_cast<SearchManager*>(manager.get());
}
TimePoint elapsed() const;
TimePoint elapsed_time() const;
LimitsType limits;
size_t pvIdx, pvLast;
std::atomic<uint64_t> nodes, tbHits, bestMoveChanges;
int selDepth, nmpMinPly;
Value optimism[COLOR_NB];
Position rootPos;
StateInfo rootState;
RootMoves rootMoves;
Depth rootDepth, completedDepth;
Value rootDelta;
size_t threadIdx;
NumaReplicatedAccessToken numaAccessToken;
// Reductions lookup table initialized at startup
std::array<int, MAX_MOVES> reductions; // [depth or moveNumber]
// The main thread has a SearchManager, the others have a NullSearchManager
std::unique_ptr<ISearchManager> manager;
Tablebases::Config tbConfig;
const OptionsMap& options;
ThreadPool& threads;
TranspositionTable& tt;
const LazyNumaReplicated<Eval::NNUE::Networks>& networks;
// Used by NNUE
Eval::NNUE::AccumulatorCaches refreshTable;
friend class Stockfish::ThreadPool;
friend class SearchManager;
};
} // namespace Search
} // namespace Stockfish
#endif // #ifndef SEARCH_H_INCLUDED
| 12,066
|
C++
|
.h
| 286
| 37.622378
| 100
| 0.643547
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,059
|
thread.h
|
official-stockfish_Stockfish/src/thread.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef THREAD_H_INCLUDED
#define THREAD_H_INCLUDED
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <vector>
#include "numa.h"
#include "position.h"
#include "search.h"
#include "thread_win32_osx.h"
namespace Stockfish {
class OptionsMap;
using Value = int;
// Sometimes we don't want to actually bind the threads, but the recipient still
// needs to think it runs on *some* NUMA node, such that it can access structures
// that rely on NUMA node knowledge. This class encapsulates this optional process
// such that the recipient does not need to know whether the binding happened or not.
class OptionalThreadToNumaNodeBinder {
public:
OptionalThreadToNumaNodeBinder(NumaIndex n) :
numaConfig(nullptr),
numaId(n) {}
OptionalThreadToNumaNodeBinder(const NumaConfig& cfg, NumaIndex n) :
numaConfig(&cfg),
numaId(n) {}
NumaReplicatedAccessToken operator()() const {
if (numaConfig != nullptr)
return numaConfig->bind_current_thread_to_numa_node(numaId);
else
return NumaReplicatedAccessToken(numaId);
}
private:
const NumaConfig* numaConfig;
NumaIndex numaId;
};
// Abstraction of a thread. It contains a pointer to the worker and a native thread.
// After construction, the native thread is started with idle_loop()
// waiting for a signal to start searching.
// When the signal is received, the thread starts searching and when
// the search is finished, it goes back to idle_loop() waiting for a new signal.
class Thread {
public:
Thread(Search::SharedState&,
std::unique_ptr<Search::ISearchManager>,
size_t,
OptionalThreadToNumaNodeBinder);
virtual ~Thread();
void idle_loop();
void start_searching();
void clear_worker();
void run_custom_job(std::function<void()> f);
void ensure_network_replicated();
// Thread has been slightly altered to allow running custom jobs, so
// this name is no longer correct. However, this class (and ThreadPool)
// require further work to make them properly generic while maintaining
// appropriate specificity regarding search, from the point of view of an
// outside user, so renaming of this function is left for whenever that happens.
void wait_for_search_finished();
size_t id() const { return idx; }
std::unique_ptr<Search::Worker> worker;
std::function<void()> jobFunc;
private:
std::mutex mutex;
std::condition_variable cv;
size_t idx, nthreads;
bool exit = false, searching = true; // Set before starting std::thread
NativeThread stdThread;
NumaReplicatedAccessToken numaAccessToken;
};
// ThreadPool struct handles all the threads-related stuff like init, starting,
// parking and, most importantly, launching a thread. All the access to threads
// is done through this class.
class ThreadPool {
public:
ThreadPool() {}
~ThreadPool() {
// destroy any existing thread(s)
if (threads.size() > 0)
{
main_thread()->wait_for_search_finished();
threads.clear();
}
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool(ThreadPool&&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
ThreadPool& operator=(ThreadPool&&) = delete;
void start_thinking(const OptionsMap&, Position&, StateListPtr&, Search::LimitsType);
void run_on_thread(size_t threadId, std::function<void()> f);
void wait_on_thread(size_t threadId);
size_t num_threads() const;
void clear();
void set(const NumaConfig& numaConfig,
Search::SharedState,
const Search::SearchManager::UpdateContext&);
Search::SearchManager* main_manager();
Thread* main_thread() const { return threads.front().get(); }
uint64_t nodes_searched() const;
uint64_t tb_hits() const;
Thread* get_best_thread() const;
void start_searching();
void wait_for_search_finished() const;
std::vector<size_t> get_bound_thread_count_by_numa_node() const;
void ensure_network_replicated();
std::atomic_bool stop, abortedSearch, increaseDepth;
auto cbegin() const noexcept { return threads.cbegin(); }
auto begin() noexcept { return threads.begin(); }
auto end() noexcept { return threads.end(); }
auto cend() const noexcept { return threads.cend(); }
auto size() const noexcept { return threads.size(); }
auto empty() const noexcept { return threads.empty(); }
private:
StateListPtr setupStates;
std::vector<std::unique_ptr<Thread>> threads;
std::vector<NumaIndex> boundThreadToNumaNode;
uint64_t accumulate(std::atomic<uint64_t> Search::Worker::*member) const {
uint64_t sum = 0;
for (auto&& th : threads)
sum += (th->worker.get()->*member).load(std::memory_order_relaxed);
return sum;
}
};
} // namespace Stockfish
#endif // #ifndef THREAD_H_INCLUDED
| 6,072
|
C++
|
.h
| 142
| 37.866197
| 97
| 0.680523
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,060
|
numa.h
|
official-stockfish_Stockfish/src/numa.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NUMA_H_INCLUDED
#define NUMA_H_INCLUDED
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <cstring>
#include "memory.h"
// We support linux very well, but we explicitly do NOT support Android,
// because there is no affected systems, not worth maintaining.
#if defined(__linux__) && !defined(__ANDROID__)
#if !defined(_GNU_SOURCE)
#define _GNU_SOURCE
#endif
#include <sched.h>
#elif defined(_WIN64)
#if _WIN32_WINNT < 0x0601
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
#endif
// On Windows each processor group can have up to 64 processors.
// https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups
static constexpr size_t WIN_PROCESSOR_GROUP_SIZE = 64;
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#include <windows.h>
#if defined small
#undef small
#endif
// https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadselectedcpusetmasks
using SetThreadSelectedCpuSetMasks_t = BOOL (*)(HANDLE, PGROUP_AFFINITY, USHORT);
// https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadselectedcpusetmasks
using GetThreadSelectedCpuSetMasks_t = BOOL (*)(HANDLE, PGROUP_AFFINITY, USHORT, PUSHORT);
#endif
#include "misc.h"
namespace Stockfish {
using CpuIndex = size_t;
using NumaIndex = size_t;
inline CpuIndex get_hardware_concurrency() {
CpuIndex concurrency = std::thread::hardware_concurrency();
// Get all processors across all processor groups on windows, since
// hardware_concurrency() only returns the number of processors in
// the first group, because only these are available to std::thread.
#ifdef _WIN64
concurrency = std::max<CpuIndex>(concurrency, GetActiveProcessorCount(ALL_PROCESSOR_GROUPS));
#endif
return concurrency;
}
inline const CpuIndex SYSTEM_THREADS_NB = std::max<CpuIndex>(1, get_hardware_concurrency());
#if defined(_WIN64)
struct WindowsAffinity {
std::optional<std::set<CpuIndex>> oldApi;
std::optional<std::set<CpuIndex>> newApi;
// We also provide diagnostic for when the affinity is set to nullopt
// whether it was due to being indeterminate. If affinity is indeterminate
// it is best to assume it is not set at all, so consistent with the meaning
// of the nullopt affinity.
bool isNewDeterminate = true;
bool isOldDeterminate = true;
std::optional<std::set<CpuIndex>> get_combined() const {
if (!oldApi.has_value())
return newApi;
if (!newApi.has_value())
return oldApi;
std::set<CpuIndex> intersect;
std::set_intersection(oldApi->begin(), oldApi->end(), newApi->begin(), newApi->end(),
std::inserter(intersect, intersect.begin()));
return intersect;
}
// Since Windows 11 and Windows Server 2022 thread affinities can span
// processor groups and can be set as such by a new WinAPI function. However,
// we may need to force using the old API if we detect that the process has
// affinity set by the old API already and we want to override that. Due to the
// limitations of the old API we cannot detect its use reliably. There will be
// cases where we detect not use but it has actually been used and vice versa.
bool likely_used_old_api() const { return oldApi.has_value() || !isOldDeterminate; }
};
inline std::pair<BOOL, std::vector<USHORT>> get_process_group_affinity() {
// GetProcessGroupAffinity requires the GroupArray argument to be
// aligned to 4 bytes instead of just 2.
static constexpr size_t GroupArrayMinimumAlignment = 4;
static_assert(GroupArrayMinimumAlignment >= alignof(USHORT));
// The function should succeed the second time, but it may fail if the group
// affinity has changed between GetProcessGroupAffinity calls. In such case
// we consider this a hard error, as we Cannot work with unstable affinities
// anyway.
static constexpr int MAX_TRIES = 2;
USHORT GroupCount = 1;
for (int i = 0; i < MAX_TRIES; ++i)
{
auto GroupArray = std::make_unique<USHORT[]>(
GroupCount + (GroupArrayMinimumAlignment / alignof(USHORT) - 1));
USHORT* GroupArrayAligned = align_ptr_up<GroupArrayMinimumAlignment>(GroupArray.get());
const BOOL status =
GetProcessGroupAffinity(GetCurrentProcess(), &GroupCount, GroupArrayAligned);
if (status == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
break;
}
if (status != 0)
{
return std::make_pair(status,
std::vector(GroupArrayAligned, GroupArrayAligned + GroupCount));
}
}
return std::make_pair(0, std::vector<USHORT>());
}
// On Windows there are two ways to set affinity, and therefore 2 ways to get it.
// These are not consistent, so we have to check both. In some cases it is actually
// not possible to determine affinity. For example when two different threads have
// affinity on different processor groups, set using SetThreadAffinityMask, we cannot
// retrieve the actual affinities.
// From documentation on GetProcessAffinityMask:
// > If the calling process contains threads in multiple groups,
// > the function returns zero for both affinity masks.
// In such cases we just give up and assume we have affinity for all processors.
// nullopt means no affinity is set, that is, all processors are allowed
inline WindowsAffinity get_process_affinity() {
HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
auto GetThreadSelectedCpuSetMasks_f = GetThreadSelectedCpuSetMasks_t(
(void (*)()) GetProcAddress(k32, "GetThreadSelectedCpuSetMasks"));
BOOL status = 0;
WindowsAffinity affinity;
if (GetThreadSelectedCpuSetMasks_f != nullptr)
{
USHORT RequiredMaskCount;
status = GetThreadSelectedCpuSetMasks_f(GetCurrentThread(), nullptr, 0, &RequiredMaskCount);
// We expect ERROR_INSUFFICIENT_BUFFER from GetThreadSelectedCpuSetMasks,
// but other failure is an actual error.
if (status == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
affinity.isNewDeterminate = false;
}
else if (RequiredMaskCount > 0)
{
// If RequiredMaskCount then these affinities were never set, but it's
// not consistent so GetProcessAffinityMask may still return some affinity.
auto groupAffinities = std::make_unique<GROUP_AFFINITY[]>(RequiredMaskCount);
status = GetThreadSelectedCpuSetMasks_f(GetCurrentThread(), groupAffinities.get(),
RequiredMaskCount, &RequiredMaskCount);
if (status == 0)
{
affinity.isNewDeterminate = false;
}
else
{
std::set<CpuIndex> cpus;
for (USHORT i = 0; i < RequiredMaskCount; ++i)
{
const size_t procGroupIndex = groupAffinities[i].Group;
for (size_t j = 0; j < WIN_PROCESSOR_GROUP_SIZE; ++j)
{
if (groupAffinities[i].Mask & (KAFFINITY(1) << j))
cpus.insert(procGroupIndex * WIN_PROCESSOR_GROUP_SIZE + j);
}
}
affinity.newApi = std::move(cpus);
}
}
}
// NOTE: There is no way to determine full affinity using the old API if
// individual threads set affinity on different processor groups.
DWORD_PTR proc, sys;
status = GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);
// If proc == 0 then we cannot determine affinity because it spans processor groups.
// On Windows 11 and Server 2022 it will instead
// > If, however, hHandle specifies a handle to the current process, the function
// > always uses the calling thread's primary group (which by default is the same
// > as the process' primary group) in order to set the
// > lpProcessAffinityMask and lpSystemAffinityMask.
// So it will never be indeterminate here. We can only make assumptions later.
if (status == 0 || proc == 0)
{
affinity.isOldDeterminate = false;
return affinity;
}
// If SetProcessAffinityMask was never called the affinity must span
// all processor groups, but if it was called it must only span one.
std::vector<USHORT> groupAffinity; // We need to capture this later and capturing
// from structured bindings requires c++20.
std::tie(status, groupAffinity) = get_process_group_affinity();
if (status == 0)
{
affinity.isOldDeterminate = false;
return affinity;
}
if (groupAffinity.size() == 1)
{
// We detect the case when affinity is set to all processors and correctly
// leave affinity.oldApi as nullopt.
if (GetActiveProcessorGroupCount() != 1 || proc != sys)
{
std::set<CpuIndex> cpus;
const size_t procGroupIndex = groupAffinity[0];
const uint64_t mask = static_cast<uint64_t>(proc);
for (size_t j = 0; j < WIN_PROCESSOR_GROUP_SIZE; ++j)
{
if (mask & (KAFFINITY(1) << j))
cpus.insert(procGroupIndex * WIN_PROCESSOR_GROUP_SIZE + j);
}
affinity.oldApi = std::move(cpus);
}
}
else
{
// If we got here it means that either SetProcessAffinityMask was never set
// or we're on Windows 11/Server 2022.
// Since Windows 11 and Windows Server 2022 the behaviour of
// GetProcessAffinityMask changed:
// > If, however, hHandle specifies a handle to the current process,
// > the function always uses the calling thread's primary group
// > (which by default is the same as the process' primary group)
// > in order to set the lpProcessAffinityMask and lpSystemAffinityMask.
// In which case we can actually retrieve the full affinity.
if (GetThreadSelectedCpuSetMasks_f != nullptr)
{
std::thread th([&]() {
std::set<CpuIndex> cpus;
bool isAffinityFull = true;
for (auto procGroupIndex : groupAffinity)
{
const int numActiveProcessors =
GetActiveProcessorCount(static_cast<WORD>(procGroupIndex));
// We have to schedule to two different processors
// and & the affinities we get. Otherwise our processor
// choice could influence the resulting affinity.
// We assume the processor IDs within the group are
// filled sequentially from 0.
uint64_t procCombined = std::numeric_limits<uint64_t>::max();
uint64_t sysCombined = std::numeric_limits<uint64_t>::max();
for (int i = 0; i < std::min(numActiveProcessors, 2); ++i)
{
GROUP_AFFINITY GroupAffinity;
std::memset(&GroupAffinity, 0, sizeof(GROUP_AFFINITY));
GroupAffinity.Group = static_cast<WORD>(procGroupIndex);
GroupAffinity.Mask = static_cast<KAFFINITY>(1) << i;
status =
SetThreadGroupAffinity(GetCurrentThread(), &GroupAffinity, nullptr);
if (status == 0)
{
affinity.isOldDeterminate = false;
return;
}
SwitchToThread();
DWORD_PTR proc2, sys2;
status = GetProcessAffinityMask(GetCurrentProcess(), &proc2, &sys2);
if (status == 0)
{
affinity.isOldDeterminate = false;
return;
}
procCombined &= static_cast<uint64_t>(proc2);
sysCombined &= static_cast<uint64_t>(sys2);
}
if (procCombined != sysCombined)
isAffinityFull = false;
for (size_t j = 0; j < WIN_PROCESSOR_GROUP_SIZE; ++j)
{
if (procCombined & (KAFFINITY(1) << j))
cpus.insert(procGroupIndex * WIN_PROCESSOR_GROUP_SIZE + j);
}
}
// We have to detect the case where the affinity was not set,
// or is set to all processors so that we correctly produce as
// std::nullopt result.
if (!isAffinityFull)
{
affinity.oldApi = std::move(cpus);
}
});
th.join();
}
}
return affinity;
}
#endif
#if defined(__linux__) && !defined(__ANDROID__)
inline std::set<CpuIndex> get_process_affinity() {
std::set<CpuIndex> cpus;
// For unsupported systems, or in case of a soft error, we may assume
// all processors are available for use.
[[maybe_unused]] auto set_to_all_cpus = [&]() {
for (CpuIndex c = 0; c < SYSTEM_THREADS_NB; ++c)
cpus.insert(c);
};
// cpu_set_t by default holds 1024 entries. This may not be enough soon,
// but there is no easy way to determine how many threads there actually
// is. In this case we just choose a reasonable upper bound.
static constexpr CpuIndex MaxNumCpus = 1024 * 64;
cpu_set_t* mask = CPU_ALLOC(MaxNumCpus);
if (mask == nullptr)
std::exit(EXIT_FAILURE);
const size_t masksize = CPU_ALLOC_SIZE(MaxNumCpus);
CPU_ZERO_S(masksize, mask);
const int status = sched_getaffinity(0, masksize, mask);
if (status != 0)
{
CPU_FREE(mask);
std::exit(EXIT_FAILURE);
}
for (CpuIndex c = 0; c < MaxNumCpus; ++c)
if (CPU_ISSET_S(c, masksize, mask))
cpus.insert(c);
CPU_FREE(mask);
return cpus;
}
#endif
#if defined(__linux__) && !defined(__ANDROID__)
inline static const auto STARTUP_PROCESSOR_AFFINITY = get_process_affinity();
#elif defined(_WIN64)
inline static const auto STARTUP_PROCESSOR_AFFINITY = get_process_affinity();
inline static const auto STARTUP_USE_OLD_AFFINITY_API =
STARTUP_PROCESSOR_AFFINITY.likely_used_old_api();
#endif
// We want to abstract the purpose of storing the numa node index somewhat.
// Whoever is using this does not need to know the specifics of the replication
// machinery to be able to access NUMA replicated memory.
class NumaReplicatedAccessToken {
public:
NumaReplicatedAccessToken() :
n(0) {}
explicit NumaReplicatedAccessToken(NumaIndex idx) :
n(idx) {}
NumaIndex get_numa_index() const { return n; }
private:
NumaIndex n;
};
// Designed as immutable, because there is no good reason to alter an already
// existing config in a way that doesn't require recreating it completely, and
// it would be complex and expensive to maintain class invariants.
// The CPU (processor) numbers always correspond to the actual numbering used
// by the system. The NUMA node numbers MAY NOT correspond to the system's
// numbering of the NUMA nodes. In particular, empty nodes may be removed, or
// the user may create custom nodes. It is guaranteed that NUMA nodes are NOT
// empty: every node exposed by NumaConfig has at least one processor assigned.
//
// We use startup affinities so as not to modify its own behaviour in time.
//
// Since Stockfish doesn't support exceptions all places where an exception
// should be thrown are replaced by std::exit.
class NumaConfig {
public:
NumaConfig() :
highestCpuIndex(0),
customAffinity(false) {
const auto numCpus = SYSTEM_THREADS_NB;
add_cpu_range_to_node(NumaIndex{0}, CpuIndex{0}, numCpus - 1);
}
// This function queries the system for the mapping of processors to NUMA nodes.
// On Linux we read from standardized kernel sysfs, with a fallback to single NUMA
// node. On Windows we utilize GetNumaProcessorNodeEx, which has its quirks, see
// comment for Windows implementation of get_process_affinity.
static NumaConfig from_system([[maybe_unused]] bool respectProcessAffinity = true) {
NumaConfig cfg = empty();
#if defined(__linux__) && !defined(__ANDROID__)
std::set<CpuIndex> allowedCpus;
if (respectProcessAffinity)
allowedCpus = STARTUP_PROCESSOR_AFFINITY;
auto is_cpu_allowed = [respectProcessAffinity, &allowedCpus](CpuIndex c) {
return !respectProcessAffinity || allowedCpus.count(c) == 1;
};
// On Linux things are straightforward, since there's no processor groups and
// any thread can be scheduled on all processors.
// We try to gather this information from the sysfs first
// https://www.kernel.org/doc/Documentation/ABI/stable/sysfs-devices-node
bool useFallback = false;
auto fallback = [&]() {
useFallback = true;
cfg = empty();
};
// /sys/devices/system/node/online contains information about active NUMA nodes
auto nodeIdsStr = read_file_to_string("/sys/devices/system/node/online");
if (!nodeIdsStr.has_value() || nodeIdsStr->empty())
{
fallback();
}
else
{
remove_whitespace(*nodeIdsStr);
for (size_t n : indices_from_shortened_string(*nodeIdsStr))
{
// /sys/devices/system/node/node.../cpulist
std::string path =
std::string("/sys/devices/system/node/node") + std::to_string(n) + "/cpulist";
auto cpuIdsStr = read_file_to_string(path);
// Now, we only bail if the file does not exist. Some nodes may be
// empty, that's fine. An empty node still has a file that appears
// to have some whitespace, so we need to handle that.
if (!cpuIdsStr.has_value())
{
fallback();
break;
}
else
{
remove_whitespace(*cpuIdsStr);
for (size_t c : indices_from_shortened_string(*cpuIdsStr))
{
if (is_cpu_allowed(c))
cfg.add_cpu_to_node(n, c);
}
}
}
}
if (useFallback)
{
for (CpuIndex c = 0; c < SYSTEM_THREADS_NB; ++c)
if (is_cpu_allowed(c))
cfg.add_cpu_to_node(NumaIndex{0}, c);
}
#elif defined(_WIN64)
std::optional<std::set<CpuIndex>> allowedCpus;
if (respectProcessAffinity)
allowedCpus = STARTUP_PROCESSOR_AFFINITY.get_combined();
// The affinity cannot be determined in all cases on Windows,
// but we at least guarantee that the number of allowed processors
// is >= number of processors in the affinity mask. In case the user
// is not satisfied they must set the processor numbers explicitly.
auto is_cpu_allowed = [&allowedCpus](CpuIndex c) {
return !allowedCpus.has_value() || allowedCpus->count(c) == 1;
};
WORD numProcGroups = GetActiveProcessorGroupCount();
for (WORD procGroup = 0; procGroup < numProcGroups; ++procGroup)
{
for (BYTE number = 0; number < WIN_PROCESSOR_GROUP_SIZE; ++number)
{
PROCESSOR_NUMBER procnum;
procnum.Group = procGroup;
procnum.Number = number;
procnum.Reserved = 0;
USHORT nodeNumber;
const BOOL status = GetNumaProcessorNodeEx(&procnum, &nodeNumber);
const CpuIndex c = static_cast<CpuIndex>(procGroup) * WIN_PROCESSOR_GROUP_SIZE
+ static_cast<CpuIndex>(number);
if (status != 0 && nodeNumber != std::numeric_limits<USHORT>::max()
&& is_cpu_allowed(c))
{
cfg.add_cpu_to_node(nodeNumber, c);
}
}
}
// Split the NUMA nodes to be contained within a group if necessary.
// This is needed between Windows 10 Build 20348 and Windows 11, because
// the new NUMA allocation behaviour was introduced while there was
// still no way to set thread affinity spanning multiple processor groups.
// See https://learn.microsoft.com/en-us/windows/win32/procthread/numa-support
// We also do this is if need to force old API for some reason.
//
// 2024-08-26: It appears that we need to actually always force this behaviour.
// While Windows allows this to work now, such assignments have bad interaction
// with the scheduler - in particular it still prefers scheduling on the thread's
// "primary" node, even if it means scheduling SMT processors first.
// See https://github.com/official-stockfish/Stockfish/issues/5551
// See https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups
//
// Each process is assigned a primary group at creation, and by default all
// of its threads' primary group is the same. Each thread's ideal processor
// is in the thread's primary group, so threads will preferentially be
// scheduled to processors on their primary group, but they are able to
// be scheduled to processors on any other group.
//
// used to be guarded by if (STARTUP_USE_OLD_AFFINITY_API)
{
NumaConfig splitCfg = empty();
NumaIndex splitNodeIndex = 0;
for (const auto& cpus : cfg.nodes)
{
if (cpus.empty())
continue;
size_t lastProcGroupIndex = *(cpus.begin()) / WIN_PROCESSOR_GROUP_SIZE;
for (CpuIndex c : cpus)
{
const size_t procGroupIndex = c / WIN_PROCESSOR_GROUP_SIZE;
if (procGroupIndex != lastProcGroupIndex)
{
splitNodeIndex += 1;
lastProcGroupIndex = procGroupIndex;
}
splitCfg.add_cpu_to_node(splitNodeIndex, c);
}
splitNodeIndex += 1;
}
cfg = std::move(splitCfg);
}
#else
// Fallback for unsupported systems.
for (CpuIndex c = 0; c < SYSTEM_THREADS_NB; ++c)
cfg.add_cpu_to_node(NumaIndex{0}, c);
#endif
// We have to ensure no empty NUMA nodes persist.
cfg.remove_empty_numa_nodes();
// If the user explicitly opts out from respecting the current process affinity
// then it may be inconsistent with the current affinity (obviously), so we
// consider it custom.
if (!respectProcessAffinity)
cfg.customAffinity = true;
return cfg;
}
// ':'-separated numa nodes
// ','-separated cpu indices
// supports "first-last" range syntax for cpu indices
// For example "0-15,128-143:16-31,144-159:32-47,160-175:48-63,176-191"
static NumaConfig from_string(const std::string& s) {
NumaConfig cfg = empty();
NumaIndex n = 0;
for (auto&& nodeStr : split(s, ":"))
{
auto indices = indices_from_shortened_string(std::string(nodeStr));
if (!indices.empty())
{
for (auto idx : indices)
{
if (!cfg.add_cpu_to_node(n, CpuIndex(idx)))
std::exit(EXIT_FAILURE);
}
n += 1;
}
}
cfg.customAffinity = true;
return cfg;
}
NumaConfig(const NumaConfig&) = delete;
NumaConfig(NumaConfig&&) = default;
NumaConfig& operator=(const NumaConfig&) = delete;
NumaConfig& operator=(NumaConfig&&) = default;
bool is_cpu_assigned(CpuIndex n) const { return nodeByCpu.count(n) == 1; }
NumaIndex num_numa_nodes() const { return nodes.size(); }
CpuIndex num_cpus_in_numa_node(NumaIndex n) const {
assert(n < nodes.size());
return nodes[n].size();
}
CpuIndex num_cpus() const { return nodeByCpu.size(); }
bool requires_memory_replication() const { return customAffinity || nodes.size() > 1; }
std::string to_string() const {
std::string str;
bool isFirstNode = true;
for (auto&& cpus : nodes)
{
if (!isFirstNode)
str += ":";
bool isFirstSet = true;
auto rangeStart = cpus.begin();
for (auto it = cpus.begin(); it != cpus.end(); ++it)
{
auto next = std::next(it);
if (next == cpus.end() || *next != *it + 1)
{
// cpus[i] is at the end of the range (may be of size 1)
if (!isFirstSet)
str += ",";
const CpuIndex last = *it;
if (it != rangeStart)
{
const CpuIndex first = *rangeStart;
str += std::to_string(first);
str += "-";
str += std::to_string(last);
}
else
str += std::to_string(last);
rangeStart = next;
isFirstSet = false;
}
}
isFirstNode = false;
}
return str;
}
bool suggests_binding_threads(CpuIndex numThreads) const {
// If we can reasonably determine that the threads cannot be contained
// by the OS within the first NUMA node then we advise distributing
// and binding threads. When the threads are not bound we can only use
// NUMA memory replicated objects from the first node, so when the OS
// has to schedule on other nodes we lose performance. We also suggest
// binding if there's enough threads to distribute among nodes with minimal
// disparity. We try to ignore small nodes, in particular the empty ones.
// If the affinity set by the user does not match the affinity given by
// the OS then binding is necessary to ensure the threads are running on
// correct processors.
if (customAffinity)
return true;
// We obviously cannot distribute a single thread, so a single thread
// should never be bound.
if (numThreads <= 1)
return false;
size_t largestNodeSize = 0;
for (auto&& cpus : nodes)
if (cpus.size() > largestNodeSize)
largestNodeSize = cpus.size();
auto is_node_small = [largestNodeSize](const std::set<CpuIndex>& node) {
static constexpr double SmallNodeThreshold = 0.6;
return static_cast<double>(node.size()) / static_cast<double>(largestNodeSize)
<= SmallNodeThreshold;
};
size_t numNotSmallNodes = 0;
for (auto&& cpus : nodes)
if (!is_node_small(cpus))
numNotSmallNodes += 1;
return (numThreads > largestNodeSize / 2 || numThreads >= numNotSmallNodes * 4)
&& nodes.size() > 1;
}
std::vector<NumaIndex> distribute_threads_among_numa_nodes(CpuIndex numThreads) const {
std::vector<NumaIndex> ns;
if (nodes.size() == 1)
{
// Special case for when there's no NUMA nodes. This doesn't buy us
// much, but let's keep the default path simple.
ns.resize(numThreads, NumaIndex{0});
}
else
{
std::vector<size_t> occupation(nodes.size(), 0);
for (CpuIndex c = 0; c < numThreads; ++c)
{
NumaIndex bestNode{0};
float bestNodeFill = std::numeric_limits<float>::max();
for (NumaIndex n = 0; n < nodes.size(); ++n)
{
float fill =
static_cast<float>(occupation[n] + 1) / static_cast<float>(nodes[n].size());
// NOTE: Do we want to perhaps fill the first available node
// up to 50% first before considering other nodes?
// Probably not, because it would interfere with running
// multiple instances. We basically shouldn't favor any
// particular node.
if (fill < bestNodeFill)
{
bestNode = n;
bestNodeFill = fill;
}
}
ns.emplace_back(bestNode);
occupation[bestNode] += 1;
}
}
return ns;
}
NumaReplicatedAccessToken bind_current_thread_to_numa_node(NumaIndex n) const {
if (n >= nodes.size() || nodes[n].size() == 0)
std::exit(EXIT_FAILURE);
#if defined(__linux__) && !defined(__ANDROID__)
cpu_set_t* mask = CPU_ALLOC(highestCpuIndex + 1);
if (mask == nullptr)
std::exit(EXIT_FAILURE);
const size_t masksize = CPU_ALLOC_SIZE(highestCpuIndex + 1);
CPU_ZERO_S(masksize, mask);
for (CpuIndex c : nodes[n])
CPU_SET_S(c, masksize, mask);
const int status = sched_setaffinity(0, masksize, mask);
CPU_FREE(mask);
if (status != 0)
std::exit(EXIT_FAILURE);
// We yield this thread just to be sure it gets rescheduled.
// This is defensive, allowed because this code is not performance critical.
sched_yield();
#elif defined(_WIN64)
// Requires Windows 11. No good way to set thread affinity spanning
// processor groups before that.
HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
auto SetThreadSelectedCpuSetMasks_f = SetThreadSelectedCpuSetMasks_t(
(void (*)()) GetProcAddress(k32, "SetThreadSelectedCpuSetMasks"));
// We ALWAYS set affinity with the new API if available, because
// there's no downsides, and we forcibly keep it consistent with
// the old API should we need to use it. I.e. we always keep this
// as a superset of what we set with SetThreadGroupAffinity.
if (SetThreadSelectedCpuSetMasks_f != nullptr)
{
// Only available on Windows 11 and Windows Server 2022 onwards
const USHORT numProcGroups = USHORT(
((highestCpuIndex + 1) + WIN_PROCESSOR_GROUP_SIZE - 1) / WIN_PROCESSOR_GROUP_SIZE);
auto groupAffinities = std::make_unique<GROUP_AFFINITY[]>(numProcGroups);
std::memset(groupAffinities.get(), 0, sizeof(GROUP_AFFINITY) * numProcGroups);
for (WORD i = 0; i < numProcGroups; ++i)
groupAffinities[i].Group = i;
for (CpuIndex c : nodes[n])
{
const size_t procGroupIndex = c / WIN_PROCESSOR_GROUP_SIZE;
const size_t idxWithinProcGroup = c % WIN_PROCESSOR_GROUP_SIZE;
groupAffinities[procGroupIndex].Mask |= KAFFINITY(1) << idxWithinProcGroup;
}
HANDLE hThread = GetCurrentThread();
const BOOL status =
SetThreadSelectedCpuSetMasks_f(hThread, groupAffinities.get(), numProcGroups);
if (status == 0)
std::exit(EXIT_FAILURE);
// We yield this thread just to be sure it gets rescheduled.
// This is defensive, allowed because this code is not performance critical.
SwitchToThread();
}
// Sometimes we need to force the old API, but do not use it unless necessary.
if (SetThreadSelectedCpuSetMasks_f == nullptr || STARTUP_USE_OLD_AFFINITY_API)
{
// On earlier windows version (since windows 7) we cannot run a single thread
// on multiple processor groups, so we need to restrict the group.
// We assume the group of the first processor listed for this node.
// Processors from outside this group will not be assigned for this thread.
// Normally this won't be an issue because windows used to assign NUMA nodes
// such that they cannot span processor groups. However, since Windows 10
// Build 20348 the behaviour changed, so there's a small window of versions
// between this and Windows 11 that might exhibit problems with not all
// processors being utilized.
//
// We handle this in NumaConfig::from_system by manually splitting the
// nodes when we detect that there is no function to set affinity spanning
// processor nodes. This is required because otherwise our thread distribution
// code may produce suboptimal results.
//
// See https://learn.microsoft.com/en-us/windows/win32/procthread/numa-support
GROUP_AFFINITY affinity;
std::memset(&affinity, 0, sizeof(GROUP_AFFINITY));
// We use an ordered set to be sure to get the smallest cpu number here.
const size_t forcedProcGroupIndex = *(nodes[n].begin()) / WIN_PROCESSOR_GROUP_SIZE;
affinity.Group = static_cast<WORD>(forcedProcGroupIndex);
for (CpuIndex c : nodes[n])
{
const size_t procGroupIndex = c / WIN_PROCESSOR_GROUP_SIZE;
const size_t idxWithinProcGroup = c % WIN_PROCESSOR_GROUP_SIZE;
// We skip processors that are not in the same processor group.
// If everything was set up correctly this will never be an issue,
// but we have to account for bad NUMA node specification.
if (procGroupIndex != forcedProcGroupIndex)
continue;
affinity.Mask |= KAFFINITY(1) << idxWithinProcGroup;
}
HANDLE hThread = GetCurrentThread();
const BOOL status = SetThreadGroupAffinity(hThread, &affinity, nullptr);
if (status == 0)
std::exit(EXIT_FAILURE);
// We yield this thread just to be sure it gets rescheduled. This is
// defensive, allowed because this code is not performance critical.
SwitchToThread();
}
#endif
return NumaReplicatedAccessToken(n);
}
template<typename FuncT>
void execute_on_numa_node(NumaIndex n, FuncT&& f) const {
std::thread th([this, &f, n]() {
bind_current_thread_to_numa_node(n);
std::forward<FuncT>(f)();
});
th.join();
}
private:
std::vector<std::set<CpuIndex>> nodes;
std::map<CpuIndex, NumaIndex> nodeByCpu;
CpuIndex highestCpuIndex;
bool customAffinity;
static NumaConfig empty() { return NumaConfig(EmptyNodeTag{}); }
struct EmptyNodeTag {};
NumaConfig(EmptyNodeTag) :
highestCpuIndex(0),
customAffinity(false) {}
void remove_empty_numa_nodes() {
std::vector<std::set<CpuIndex>> newNodes;
for (auto&& cpus : nodes)
if (!cpus.empty())
newNodes.emplace_back(std::move(cpus));
nodes = std::move(newNodes);
}
// Returns true if successful
// Returns false if failed, i.e. when the cpu is already present
// strong guarantee, the structure remains unmodified
bool add_cpu_to_node(NumaIndex n, CpuIndex c) {
if (is_cpu_assigned(c))
return false;
while (nodes.size() <= n)
nodes.emplace_back();
nodes[n].insert(c);
nodeByCpu[c] = n;
if (c > highestCpuIndex)
highestCpuIndex = c;
return true;
}
// Returns true if successful
// Returns false if failed, i.e. when any of the cpus is already present
// strong guarantee, the structure remains unmodified
bool add_cpu_range_to_node(NumaIndex n, CpuIndex cfirst, CpuIndex clast) {
for (CpuIndex c = cfirst; c <= clast; ++c)
if (is_cpu_assigned(c))
return false;
while (nodes.size() <= n)
nodes.emplace_back();
for (CpuIndex c = cfirst; c <= clast; ++c)
{
nodes[n].insert(c);
nodeByCpu[c] = n;
}
if (clast > highestCpuIndex)
highestCpuIndex = clast;
return true;
}
static std::vector<size_t> indices_from_shortened_string(const std::string& s) {
std::vector<size_t> indices;
if (s.empty())
return indices;
for (const auto& ss : split(s, ","))
{
if (ss.empty())
continue;
auto parts = split(ss, "-");
if (parts.size() == 1)
{
const CpuIndex c = CpuIndex{str_to_size_t(std::string(parts[0]))};
indices.emplace_back(c);
}
else if (parts.size() == 2)
{
const CpuIndex cfirst = CpuIndex{str_to_size_t(std::string(parts[0]))};
const CpuIndex clast = CpuIndex{str_to_size_t(std::string(parts[1]))};
for (size_t c = cfirst; c <= clast; ++c)
{
indices.emplace_back(c);
}
}
}
return indices;
}
};
class NumaReplicationContext;
// Instances of this class are tracked by the NumaReplicationContext instance.
// NumaReplicationContext informs all tracked instances when NUMA configuration changes.
class NumaReplicatedBase {
public:
NumaReplicatedBase(NumaReplicationContext& ctx);
NumaReplicatedBase(const NumaReplicatedBase&) = delete;
NumaReplicatedBase(NumaReplicatedBase&& other) noexcept;
NumaReplicatedBase& operator=(const NumaReplicatedBase&) = delete;
NumaReplicatedBase& operator=(NumaReplicatedBase&& other) noexcept;
virtual void on_numa_config_changed() = 0;
virtual ~NumaReplicatedBase();
const NumaConfig& get_numa_config() const;
private:
NumaReplicationContext* context;
};
// We force boxing with a unique_ptr. If this becomes an issue due to added
// indirection we may need to add an option for a custom boxing type. When the
// NUMA config changes the value stored at the index 0 is replicated to other nodes.
template<typename T>
class NumaReplicated: public NumaReplicatedBase {
public:
using ReplicatorFuncType = std::function<T(const T&)>;
NumaReplicated(NumaReplicationContext& ctx) :
NumaReplicatedBase(ctx) {
replicate_from(T{});
}
NumaReplicated(NumaReplicationContext& ctx, T&& source) :
NumaReplicatedBase(ctx) {
replicate_from(std::move(source));
}
NumaReplicated(const NumaReplicated&) = delete;
NumaReplicated(NumaReplicated&& other) noexcept :
NumaReplicatedBase(std::move(other)),
instances(std::exchange(other.instances, {})) {}
NumaReplicated& operator=(const NumaReplicated&) = delete;
NumaReplicated& operator=(NumaReplicated&& other) noexcept {
NumaReplicatedBase::operator=(*this, std::move(other));
instances = std::exchange(other.instances, {});
return *this;
}
NumaReplicated& operator=(T&& source) {
replicate_from(std::move(source));
return *this;
}
~NumaReplicated() override = default;
const T& operator[](NumaReplicatedAccessToken token) const {
assert(token.get_numa_index() < instances.size());
return *(instances[token.get_numa_index()]);
}
const T& operator*() const { return *(instances[0]); }
const T* operator->() const { return instances[0].get(); }
template<typename FuncT>
void modify_and_replicate(FuncT&& f) {
auto source = std::move(instances[0]);
std::forward<FuncT>(f)(*source);
replicate_from(std::move(*source));
}
void on_numa_config_changed() override {
// Use the first one as the source. It doesn't matter which one we use,
// because they all must be identical, but the first one is guaranteed to exist.
auto source = std::move(instances[0]);
replicate_from(std::move(*source));
}
private:
std::vector<std::unique_ptr<T>> instances;
void replicate_from(T&& source) {
instances.clear();
const NumaConfig& cfg = get_numa_config();
if (cfg.requires_memory_replication())
{
for (NumaIndex n = 0; n < cfg.num_numa_nodes(); ++n)
{
cfg.execute_on_numa_node(
n, [this, &source]() { instances.emplace_back(std::make_unique<T>(source)); });
}
}
else
{
assert(cfg.num_numa_nodes() == 1);
// We take advantage of the fact that replication is not required
// and reuse the source value, avoiding one copy operation.
instances.emplace_back(std::make_unique<T>(std::move(source)));
}
}
};
// We force boxing with a unique_ptr. If this becomes an issue due to added
// indirection we may need to add an option for a custom boxing type.
template<typename T>
class LazyNumaReplicated: public NumaReplicatedBase {
public:
using ReplicatorFuncType = std::function<T(const T&)>;
LazyNumaReplicated(NumaReplicationContext& ctx) :
NumaReplicatedBase(ctx) {
prepare_replicate_from(T{});
}
LazyNumaReplicated(NumaReplicationContext& ctx, T&& source) :
NumaReplicatedBase(ctx) {
prepare_replicate_from(std::move(source));
}
LazyNumaReplicated(const LazyNumaReplicated&) = delete;
LazyNumaReplicated(LazyNumaReplicated&& other) noexcept :
NumaReplicatedBase(std::move(other)),
instances(std::exchange(other.instances, {})) {}
LazyNumaReplicated& operator=(const LazyNumaReplicated&) = delete;
LazyNumaReplicated& operator=(LazyNumaReplicated&& other) noexcept {
NumaReplicatedBase::operator=(*this, std::move(other));
instances = std::exchange(other.instances, {});
return *this;
}
LazyNumaReplicated& operator=(T&& source) {
prepare_replicate_from(std::move(source));
return *this;
}
~LazyNumaReplicated() override = default;
const T& operator[](NumaReplicatedAccessToken token) const {
assert(token.get_numa_index() < instances.size());
ensure_present(token.get_numa_index());
return *(instances[token.get_numa_index()]);
}
const T& operator*() const { return *(instances[0]); }
const T* operator->() const { return instances[0].get(); }
template<typename FuncT>
void modify_and_replicate(FuncT&& f) {
auto source = std::move(instances[0]);
std::forward<FuncT>(f)(*source);
prepare_replicate_from(std::move(*source));
}
void on_numa_config_changed() override {
// Use the first one as the source. It doesn't matter which one we use,
// because they all must be identical, but the first one is guaranteed to exist.
auto source = std::move(instances[0]);
prepare_replicate_from(std::move(*source));
}
private:
mutable std::vector<std::unique_ptr<T>> instances;
mutable std::mutex mutex;
void ensure_present(NumaIndex idx) const {
assert(idx < instances.size());
if (instances[idx] != nullptr)
return;
assert(idx != 0);
std::unique_lock<std::mutex> lock(mutex);
// Check again for races.
if (instances[idx] != nullptr)
return;
const NumaConfig& cfg = get_numa_config();
cfg.execute_on_numa_node(
idx, [this, idx]() { instances[idx] = std::make_unique<T>(*instances[0]); });
}
void prepare_replicate_from(T&& source) {
instances.clear();
const NumaConfig& cfg = get_numa_config();
if (cfg.requires_memory_replication())
{
assert(cfg.num_numa_nodes() > 0);
// We just need to make sure the first instance is there.
// Note that we cannot move here as we need to reallocate the data
// on the correct NUMA node.
cfg.execute_on_numa_node(
0, [this, &source]() { instances.emplace_back(std::make_unique<T>(source)); });
// Prepare others for lazy init.
instances.resize(cfg.num_numa_nodes());
}
else
{
assert(cfg.num_numa_nodes() == 1);
// We take advantage of the fact that replication is not required
// and reuse the source value, avoiding one copy operation.
instances.emplace_back(std::make_unique<T>(std::move(source)));
}
}
};
class NumaReplicationContext {
public:
NumaReplicationContext(NumaConfig&& cfg) :
config(std::move(cfg)) {}
NumaReplicationContext(const NumaReplicationContext&) = delete;
NumaReplicationContext(NumaReplicationContext&&) = delete;
NumaReplicationContext& operator=(const NumaReplicationContext&) = delete;
NumaReplicationContext& operator=(NumaReplicationContext&&) = delete;
~NumaReplicationContext() {
// The context must outlive replicated objects
if (!trackedReplicatedObjects.empty())
std::exit(EXIT_FAILURE);
}
void attach(NumaReplicatedBase* obj) {
assert(trackedReplicatedObjects.count(obj) == 0);
trackedReplicatedObjects.insert(obj);
}
void detach(NumaReplicatedBase* obj) {
assert(trackedReplicatedObjects.count(obj) == 1);
trackedReplicatedObjects.erase(obj);
}
// oldObj may be invalid at this point
void move_attached([[maybe_unused]] NumaReplicatedBase* oldObj, NumaReplicatedBase* newObj) {
assert(trackedReplicatedObjects.count(oldObj) == 1);
assert(trackedReplicatedObjects.count(newObj) == 0);
trackedReplicatedObjects.erase(oldObj);
trackedReplicatedObjects.insert(newObj);
}
void set_numa_config(NumaConfig&& cfg) {
config = std::move(cfg);
for (auto&& obj : trackedReplicatedObjects)
obj->on_numa_config_changed();
}
const NumaConfig& get_numa_config() const { return config; }
private:
NumaConfig config;
// std::set uses std::less by default, which is required for pointer comparison
std::set<NumaReplicatedBase*> trackedReplicatedObjects;
};
inline NumaReplicatedBase::NumaReplicatedBase(NumaReplicationContext& ctx) :
context(&ctx) {
context->attach(this);
}
inline NumaReplicatedBase::NumaReplicatedBase(NumaReplicatedBase&& other) noexcept :
context(std::exchange(other.context, nullptr)) {
context->move_attached(&other, this);
}
inline NumaReplicatedBase& NumaReplicatedBase::operator=(NumaReplicatedBase&& other) noexcept {
context = std::exchange(other.context, nullptr);
context->move_attached(&other, this);
return *this;
}
inline NumaReplicatedBase::~NumaReplicatedBase() {
if (context != nullptr)
context->detach(this);
}
inline const NumaConfig& NumaReplicatedBase::get_numa_config() const {
return context->get_numa_config();
}
} // namespace Stockfish
#endif // #ifndef NUMA_H_INCLUDED
| 49,387
|
C++
|
.h
| 1,080
| 35.774074
| 122
| 0.609812
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,061
|
types.h
|
official-stockfish_Stockfish/src/types.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TYPES_H_INCLUDED
#define TYPES_H_INCLUDED
// When compiling with provided Makefile (e.g. for Linux and OSX), configuration
// is done automatically. To get started type 'make help'.
//
// When Makefile is not used (e.g. with Microsoft Visual Studio) some switches
// need to be set manually:
//
// -DNDEBUG | Disable debugging mode. Always use this for release.
//
// -DNO_PREFETCH | Disable use of prefetch asm-instruction. You may need this to
// | run on some very old machines.
//
// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction. Works
// | only in 64-bit mode and requires hardware with popcnt support.
//
// -DUSE_PEXT | Add runtime support for use of pext asm-instruction. Works
// | only in 64-bit mode and requires hardware with pext support.
#include <cassert>
#include <cstdint>
#if defined(_MSC_VER)
// Disable some silly and noisy warnings from MSVC compiler
#pragma warning(disable: 4127) // Conditional expression is constant
#pragma warning(disable: 4146) // Unary minus operator applied to unsigned type
#pragma warning(disable: 4800) // Forcing value to bool 'true' or 'false'
#endif
// Predefined macros hell:
//
// __GNUC__ Compiler is GCC, Clang or ICX
// __clang__ Compiler is Clang or ICX
// __INTEL_LLVM_COMPILER Compiler is ICX
// _MSC_VER Compiler is MSVC
// _WIN32 Building on Windows (any)
// _WIN64 Building on Windows 64 bit
#if defined(__GNUC__) && (__GNUC__ < 9 || (__GNUC__ == 9 && __GNUC_MINOR__ <= 2)) \
&& defined(_WIN32) && !defined(__clang__)
#define ALIGNAS_ON_STACK_VARIABLES_BROKEN
#endif
#define ASSERT_ALIGNED(ptr, alignment) assert(reinterpret_cast<uintptr_t>(ptr) % alignment == 0)
#if defined(_WIN64) && defined(_MSC_VER) // No Makefile used
#include <intrin.h> // Microsoft header for _BitScanForward64()
#define IS_64BIT
#endif
#if defined(USE_POPCNT) && defined(_MSC_VER)
#include <nmmintrin.h> // Microsoft header for _mm_popcnt_u64()
#endif
#if !defined(NO_PREFETCH) && defined(_MSC_VER)
#include <xmmintrin.h> // Microsoft header for _mm_prefetch()
#endif
#if defined(USE_PEXT)
#include <immintrin.h> // Header for _pext_u64() intrinsic
#define pext(b, m) _pext_u64(b, m)
#else
#define pext(b, m) 0
#endif
namespace Stockfish {
#ifdef USE_POPCNT
constexpr bool HasPopCnt = true;
#else
constexpr bool HasPopCnt = false;
#endif
#ifdef USE_PEXT
constexpr bool HasPext = true;
#else
constexpr bool HasPext = false;
#endif
#ifdef IS_64BIT
constexpr bool Is64Bit = true;
#else
constexpr bool Is64Bit = false;
#endif
using Key = uint64_t;
using Bitboard = uint64_t;
constexpr int MAX_MOVES = 256;
constexpr int MAX_PLY = 246;
enum Color {
WHITE,
BLACK,
COLOR_NB = 2
};
enum CastlingRights {
NO_CASTLING,
WHITE_OO,
WHITE_OOO = WHITE_OO << 1,
BLACK_OO = WHITE_OO << 2,
BLACK_OOO = WHITE_OO << 3,
KING_SIDE = WHITE_OO | BLACK_OO,
QUEEN_SIDE = WHITE_OOO | BLACK_OOO,
WHITE_CASTLING = WHITE_OO | WHITE_OOO,
BLACK_CASTLING = BLACK_OO | BLACK_OOO,
ANY_CASTLING = WHITE_CASTLING | BLACK_CASTLING,
CASTLING_RIGHT_NB = 16
};
enum Bound {
BOUND_NONE,
BOUND_UPPER,
BOUND_LOWER,
BOUND_EXACT = BOUND_UPPER | BOUND_LOWER
};
// Value is used as an alias for int, this is done to differentiate between a search
// value and any other integer value. The values used in search are always supposed
// to be in the range (-VALUE_NONE, VALUE_NONE] and should not exceed this range.
using Value = int;
constexpr Value VALUE_ZERO = 0;
constexpr Value VALUE_DRAW = 0;
constexpr Value VALUE_NONE = 32002;
constexpr Value VALUE_INFINITE = 32001;
constexpr Value VALUE_MATE = 32000;
constexpr Value VALUE_MATE_IN_MAX_PLY = VALUE_MATE - MAX_PLY;
constexpr Value VALUE_MATED_IN_MAX_PLY = -VALUE_MATE_IN_MAX_PLY;
constexpr Value VALUE_TB = VALUE_MATE_IN_MAX_PLY - 1;
constexpr Value VALUE_TB_WIN_IN_MAX_PLY = VALUE_TB - MAX_PLY;
constexpr Value VALUE_TB_LOSS_IN_MAX_PLY = -VALUE_TB_WIN_IN_MAX_PLY;
// In the code, we make the assumption that these values
// are such that non_pawn_material() can be used to uniquely
// identify the material on the board.
constexpr Value PawnValue = 208;
constexpr Value KnightValue = 781;
constexpr Value BishopValue = 825;
constexpr Value RookValue = 1276;
constexpr Value QueenValue = 2538;
// clang-format off
enum PieceType {
NO_PIECE_TYPE, PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING,
ALL_PIECES = 0,
PIECE_TYPE_NB = 8
};
enum Piece {
NO_PIECE,
W_PAWN = PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING,
B_PAWN = PAWN + 8, B_KNIGHT, B_BISHOP, B_ROOK, B_QUEEN, B_KING,
PIECE_NB = 16
};
// clang-format on
constexpr Value PieceValue[PIECE_NB] = {
VALUE_ZERO, PawnValue, KnightValue, BishopValue, RookValue, QueenValue, VALUE_ZERO, VALUE_ZERO,
VALUE_ZERO, PawnValue, KnightValue, BishopValue, RookValue, QueenValue, VALUE_ZERO, VALUE_ZERO};
using Depth = int;
enum : int {
// The following DEPTH_ constants are used for transposition table entries
// and quiescence search move generation stages. In regular search, the
// depth stored in the transposition table is literal: the search depth
// (effort) used to make the corresponding transposition table value. In
// quiescence search, however, the transposition table entries only store
// the current quiescence move generation stage (which should thus compare
// lower than any regular search depth).
DEPTH_QS = 0,
// For transposition table entries where no searching at all was done
// (whether regular or qsearch) we use DEPTH_UNSEARCHED, which should thus
// compare lower than any quiescence or regular depth. DEPTH_ENTRY_OFFSET
// is used only for the transposition table entry occupancy check (see tt.cpp),
// and should thus be lower than DEPTH_UNSEARCHED.
DEPTH_UNSEARCHED = -2,
DEPTH_ENTRY_OFFSET = -3
};
// clang-format off
enum Square : int {
SQ_A1, SQ_B1, SQ_C1, SQ_D1, SQ_E1, SQ_F1, SQ_G1, SQ_H1,
SQ_A2, SQ_B2, SQ_C2, SQ_D2, SQ_E2, SQ_F2, SQ_G2, SQ_H2,
SQ_A3, SQ_B3, SQ_C3, SQ_D3, SQ_E3, SQ_F3, SQ_G3, SQ_H3,
SQ_A4, SQ_B4, SQ_C4, SQ_D4, SQ_E4, SQ_F4, SQ_G4, SQ_H4,
SQ_A5, SQ_B5, SQ_C5, SQ_D5, SQ_E5, SQ_F5, SQ_G5, SQ_H5,
SQ_A6, SQ_B6, SQ_C6, SQ_D6, SQ_E6, SQ_F6, SQ_G6, SQ_H6,
SQ_A7, SQ_B7, SQ_C7, SQ_D7, SQ_E7, SQ_F7, SQ_G7, SQ_H7,
SQ_A8, SQ_B8, SQ_C8, SQ_D8, SQ_E8, SQ_F8, SQ_G8, SQ_H8,
SQ_NONE,
SQUARE_ZERO = 0,
SQUARE_NB = 64
};
// clang-format on
enum Direction : int {
NORTH = 8,
EAST = 1,
SOUTH = -NORTH,
WEST = -EAST,
NORTH_EAST = NORTH + EAST,
SOUTH_EAST = SOUTH + EAST,
SOUTH_WEST = SOUTH + WEST,
NORTH_WEST = NORTH + WEST
};
enum File : int {
FILE_A,
FILE_B,
FILE_C,
FILE_D,
FILE_E,
FILE_F,
FILE_G,
FILE_H,
FILE_NB
};
enum Rank : int {
RANK_1,
RANK_2,
RANK_3,
RANK_4,
RANK_5,
RANK_6,
RANK_7,
RANK_8,
RANK_NB
};
// Keep track of what a move changes on the board (used by NNUE)
struct DirtyPiece {
// Number of changed pieces
int dirty_num;
// Max 3 pieces can change in one move. A promotion with capture moves
// both the pawn and the captured piece to SQ_NONE and the piece promoted
// to from SQ_NONE to the capture square.
Piece piece[3];
// From and to squares, which may be SQ_NONE
Square from[3];
Square to[3];
};
#define ENABLE_INCR_OPERATORS_ON(T) \
inline T& operator++(T& d) { return d = T(int(d) + 1); } \
inline T& operator--(T& d) { return d = T(int(d) - 1); }
ENABLE_INCR_OPERATORS_ON(PieceType)
ENABLE_INCR_OPERATORS_ON(Square)
ENABLE_INCR_OPERATORS_ON(File)
ENABLE_INCR_OPERATORS_ON(Rank)
#undef ENABLE_INCR_OPERATORS_ON
constexpr Direction operator+(Direction d1, Direction d2) { return Direction(int(d1) + int(d2)); }
constexpr Direction operator*(int i, Direction d) { return Direction(i * int(d)); }
// Additional operators to add a Direction to a Square
constexpr Square operator+(Square s, Direction d) { return Square(int(s) + int(d)); }
constexpr Square operator-(Square s, Direction d) { return Square(int(s) - int(d)); }
inline Square& operator+=(Square& s, Direction d) { return s = s + d; }
inline Square& operator-=(Square& s, Direction d) { return s = s - d; }
// Toggle color
constexpr Color operator~(Color c) { return Color(c ^ BLACK); }
// Swap A1 <-> A8
constexpr Square flip_rank(Square s) { return Square(s ^ SQ_A8); }
// Swap A1 <-> H1
constexpr Square flip_file(Square s) { return Square(s ^ SQ_H1); }
// Swap color of piece B_KNIGHT <-> W_KNIGHT
constexpr Piece operator~(Piece pc) { return Piece(pc ^ 8); }
constexpr CastlingRights operator&(Color c, CastlingRights cr) {
return CastlingRights((c == WHITE ? WHITE_CASTLING : BLACK_CASTLING) & cr);
}
constexpr Value mate_in(int ply) { return VALUE_MATE - ply; }
constexpr Value mated_in(int ply) { return -VALUE_MATE + ply; }
constexpr Square make_square(File f, Rank r) { return Square((r << 3) + f); }
constexpr Piece make_piece(Color c, PieceType pt) { return Piece((c << 3) + pt); }
constexpr PieceType type_of(Piece pc) { return PieceType(pc & 7); }
inline Color color_of(Piece pc) {
assert(pc != NO_PIECE);
return Color(pc >> 3);
}
constexpr bool is_ok(Square s) { return s >= SQ_A1 && s <= SQ_H8; }
constexpr File file_of(Square s) { return File(s & 7); }
constexpr Rank rank_of(Square s) { return Rank(s >> 3); }
constexpr Square relative_square(Color c, Square s) { return Square(s ^ (c * 56)); }
constexpr Rank relative_rank(Color c, Rank r) { return Rank(r ^ (c * 7)); }
constexpr Rank relative_rank(Color c, Square s) { return relative_rank(c, rank_of(s)); }
constexpr Direction pawn_push(Color c) { return c == WHITE ? NORTH : SOUTH; }
// Based on a congruential pseudo-random number generator
constexpr Key make_key(uint64_t seed) {
return seed * 6364136223846793005ULL + 1442695040888963407ULL;
}
enum MoveType {
NORMAL,
PROMOTION = 1 << 14,
EN_PASSANT = 2 << 14,
CASTLING = 3 << 14
};
// A move needs 16 bits to be stored
//
// bit 0- 5: destination square (from 0 to 63)
// bit 6-11: origin square (from 0 to 63)
// bit 12-13: promotion piece type - 2 (from KNIGHT-2 to QUEEN-2)
// bit 14-15: special move flag: promotion (1), en passant (2), castling (3)
// NOTE: en passant bit is set only when a pawn can be captured
//
// Special cases are Move::none() and Move::null(). We can sneak these in because
// in any normal move the destination square and origin square are always different,
// but Move::none() and Move::null() have the same origin and destination square.
class Move {
public:
Move() = default;
constexpr explicit Move(std::uint16_t d) :
data(d) {}
constexpr Move(Square from, Square to) :
data((from << 6) + to) {}
template<MoveType T>
static constexpr Move make(Square from, Square to, PieceType pt = KNIGHT) {
return Move(T + ((pt - KNIGHT) << 12) + (from << 6) + to);
}
constexpr Square from_sq() const {
assert(is_ok());
return Square((data >> 6) & 0x3F);
}
constexpr Square to_sq() const {
assert(is_ok());
return Square(data & 0x3F);
}
constexpr int from_to() const { return data & 0xFFF; }
constexpr MoveType type_of() const { return MoveType(data & (3 << 14)); }
constexpr PieceType promotion_type() const { return PieceType(((data >> 12) & 3) + KNIGHT); }
constexpr bool is_ok() const { return none().data != data && null().data != data; }
static constexpr Move null() { return Move(65); }
static constexpr Move none() { return Move(0); }
constexpr bool operator==(const Move& m) const { return data == m.data; }
constexpr bool operator!=(const Move& m) const { return data != m.data; }
constexpr explicit operator bool() const { return data != 0; }
constexpr std::uint16_t raw() const { return data; }
struct MoveHash {
std::size_t operator()(const Move& m) const { return make_key(m.data); }
};
protected:
std::uint16_t data;
};
} // namespace Stockfish
#endif // #ifndef TYPES_H_INCLUDED
#include "tune.h" // Global visibility to tuning setup
| 13,412
|
C++
|
.h
| 329
| 37.066869
| 100
| 0.670541
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,062
|
ucioption.h
|
official-stockfish_Stockfish/src/ucioption.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UCIOPTION_H_INCLUDED
#define UCIOPTION_H_INCLUDED
#include <cstddef>
#include <functional>
#include <iosfwd>
#include <map>
#include <optional>
#include <string>
namespace Stockfish {
// Define a custom comparator, because the UCI options should be case-insensitive
struct CaseInsensitiveLess {
bool operator()(const std::string&, const std::string&) const;
};
class OptionsMap;
// The Option class implements each option as specified by the UCI protocol
class Option {
public:
using OnChange = std::function<std::optional<std::string>(const Option&)>;
Option(const OptionsMap*);
Option(OnChange = nullptr);
Option(bool v, OnChange = nullptr);
Option(const char* v, OnChange = nullptr);
Option(double v, int minv, int maxv, OnChange = nullptr);
Option(const char* v, const char* cur, OnChange = nullptr);
Option& operator=(const std::string&);
operator int() const;
operator std::string() const;
bool operator==(const char*) const;
bool operator!=(const char*) const;
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
private:
friend class OptionsMap;
friend class Engine;
friend class Tune;
void operator<<(const Option&);
std::string defaultValue, currentValue, type;
int min, max;
size_t idx;
OnChange on_change;
const OptionsMap* parent = nullptr;
};
class OptionsMap {
public:
using InfoListener = std::function<void(std::optional<std::string>)>;
OptionsMap() = default;
OptionsMap(const OptionsMap&) = delete;
OptionsMap(OptionsMap&&) = delete;
OptionsMap& operator=(const OptionsMap&) = delete;
OptionsMap& operator=(OptionsMap&&) = delete;
void add_info_listener(InfoListener&&);
void setoption(std::istringstream&);
Option operator[](const std::string&) const;
Option& operator[](const std::string&);
std::size_t count(const std::string&) const;
private:
friend class Engine;
friend class Option;
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
// The options container is defined as a std::map
using OptionsStore = std::map<std::string, Option, CaseInsensitiveLess>;
OptionsStore options_map;
InfoListener info;
};
}
#endif // #ifndef UCIOPTION_H_INCLUDED
| 3,179
|
C++
|
.h
| 79
| 36.392405
| 81
| 0.707642
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,063
|
thread_win32_osx.h
|
official-stockfish_Stockfish/src/thread_win32_osx.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef THREAD_WIN32_OSX_H_INCLUDED
#define THREAD_WIN32_OSX_H_INCLUDED
#include <thread>
// On OSX threads other than the main thread are created with a reduced stack
// size of 512KB by default, this is too low for deep searches, which require
// somewhat more than 1MB stack, so adjust it to TH_STACK_SIZE.
// The implementation calls pthread_create() with the stack size parameter
// equal to the Linux 8MB default, on platforms that support it.
#if defined(__APPLE__) || defined(__MINGW32__) || defined(__MINGW64__) || defined(USE_PTHREADS)
#include <pthread.h>
#include <functional>
namespace Stockfish {
class NativeThread {
pthread_t thread;
static constexpr size_t TH_STACK_SIZE = 8 * 1024 * 1024;
public:
template<class Function, class... Args>
explicit NativeThread(Function&& fun, Args&&... args) {
auto func = new std::function<void()>(
std::bind(std::forward<Function>(fun), std::forward<Args>(args)...));
pthread_attr_t attr_storage, *attr = &attr_storage;
pthread_attr_init(attr);
pthread_attr_setstacksize(attr, TH_STACK_SIZE);
auto start_routine = [](void* ptr) -> void* {
auto f = reinterpret_cast<std::function<void()>*>(ptr);
// Call the function
(*f)();
delete f;
return nullptr;
};
pthread_create(&thread, attr, start_routine, func);
}
void join() { pthread_join(thread, nullptr); }
};
} // namespace Stockfish
#else // Default case: use STL classes
namespace Stockfish {
using NativeThread = std::thread;
} // namespace Stockfish
#endif
#endif // #ifndef THREAD_WIN32_OSX_H_INCLUDED
| 2,461
|
C++
|
.h
| 55
| 39.963636
| 95
| 0.703735
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,064
|
evaluate.h
|
official-stockfish_Stockfish/src/evaluate.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef EVALUATE_H_INCLUDED
#define EVALUATE_H_INCLUDED
#include <string>
#include "types.h"
namespace Stockfish {
class Position;
namespace Eval {
// The default net name MUST follow the format nn-[SHA256 first 12 digits].nnue
// for the build process (profile-build and fishtest) to work. Do not change the
// name of the macro or the location where this macro is defined, as it is used
// in the Makefile/Fishtest.
#define EvalFileDefaultNameBig "nn-1c0000000000.nnue"
#define EvalFileDefaultNameSmall "nn-37f18f62d772.nnue"
namespace NNUE {
struct Networks;
struct AccumulatorCaches;
}
std::string trace(Position& pos, const Eval::NNUE::Networks& networks);
int simple_eval(const Position& pos, Color c);
bool use_smallnet(const Position& pos);
Value evaluate(const NNUE::Networks& networks,
const Position& pos,
Eval::NNUE::AccumulatorCaches& caches,
int optimism);
} // namespace Eval
} // namespace Stockfish
#endif // #ifndef EVALUATE_H_INCLUDED
| 1,837
|
C++
|
.h
| 41
| 41.756098
| 80
| 0.744526
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,066
|
tune.h
|
official-stockfish_Stockfish/src/tune.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TUNE_H_INCLUDED
#define TUNE_H_INCLUDED
#include <cstddef>
#include <memory>
#include <string>
#include <type_traits> // IWYU pragma: keep
#include <utility>
#include <vector>
namespace Stockfish {
class OptionsMap;
using Range = std::pair<int, int>; // Option's min-max values
using RangeFun = Range(int);
// Default Range function, to calculate Option's min-max values
inline Range default_range(int v) { return v > 0 ? Range(0, 2 * v) : Range(2 * v, 0); }
struct SetRange {
explicit SetRange(RangeFun f) :
fun(f) {}
SetRange(int min, int max) :
fun(nullptr),
range(min, max) {}
Range operator()(int v) const { return fun ? fun(v) : range; }
RangeFun* fun;
Range range;
};
#define SetDefaultRange SetRange(default_range)
// Tune class implements the 'magic' code that makes the setup of a fishtest tuning
// session as easy as it can be. Mainly you have just to remove const qualifiers
// from the variables you want to tune and flag them for tuning, so if you have:
//
// const Value myValue[][2] = { { V(100), V(20) }, { V(7), V(78) } };
//
// If you have a my_post_update() function to run after values have been updated,
// and a my_range() function to set custom Option's min-max values, then you just
// remove the 'const' qualifiers and write somewhere below in the file:
//
// TUNE(SetRange(my_range), myValue, my_post_update);
//
// You can also set the range directly, and restore the default at the end
//
// TUNE(SetRange(-100, 100), myValue, SetDefaultRange);
//
// In case update function is slow and you have many parameters, you can add:
//
// UPDATE_ON_LAST();
//
// And the values update, including post update function call, will be done only
// once, after the engine receives the last UCI option, that is the one defined
// and created as the last one, so the GUI should send the options in the same
// order in which have been defined.
class Tune {
using PostUpdate = void(); // Post-update function
Tune() { read_results(); }
Tune(const Tune&) = delete;
void operator=(const Tune&) = delete;
void read_results();
static Tune& instance() {
static Tune t;
return t;
} // Singleton
// Use polymorphism to accommodate Entry of different types in the same vector
struct EntryBase {
virtual ~EntryBase() = default;
virtual void init_option() = 0;
virtual void read_option() = 0;
};
template<typename T>
struct Entry: public EntryBase {
static_assert(!std::is_const_v<T>, "Parameter cannot be const!");
static_assert(std::is_same_v<T, int> || std::is_same_v<T, PostUpdate>,
"Parameter type not supported!");
Entry(const std::string& n, T& v, const SetRange& r) :
name(n),
value(v),
range(r) {}
void operator=(const Entry&) = delete; // Because 'value' is a reference
void init_option() override;
void read_option() override;
std::string name;
T& value;
SetRange range;
};
// Our facility to fill the container, each Entry corresponds to a parameter
// to tune. We use variadic templates to deal with an unspecified number of
// entries, each one of a possible different type.
static std::string next(std::string& names, bool pop = true);
int add(const SetRange&, std::string&&) { return 0; }
template<typename T, typename... Args>
int add(const SetRange& range, std::string&& names, T& value, Args&&... args) {
list.push_back(std::unique_ptr<EntryBase>(new Entry<T>(next(names), value, range)));
return add(range, std::move(names), args...);
}
// Template specialization for arrays: recursively handle multi-dimensional arrays
template<typename T, size_t N, typename... Args>
int add(const SetRange& range, std::string&& names, T (&value)[N], Args&&... args) {
for (size_t i = 0; i < N; i++)
add(range, next(names, i == N - 1) + "[" + std::to_string(i) + "]", value[i]);
return add(range, std::move(names), args...);
}
// Template specialization for SetRange
template<typename... Args>
int add(const SetRange&, std::string&& names, SetRange& value, Args&&... args) {
return add(value, (next(names), std::move(names)), args...);
}
static void make_option(OptionsMap* options, const std::string& n, int v, const SetRange& r);
std::vector<std::unique_ptr<EntryBase>> list;
public:
template<typename... Args>
static int add(const std::string& names, Args&&... args) {
return instance().add(SetDefaultRange, names.substr(1, names.size() - 2),
args...); // Remove trailing parenthesis
}
static void init(OptionsMap& o) {
options = &o;
for (auto& e : instance().list)
e->init_option();
read_options();
} // Deferred, due to UCIEngine::Options access
static void read_options() {
for (auto& e : instance().list)
e->read_option();
}
static bool update_on_last;
static OptionsMap* options;
};
// Some macro magic :-) we define a dummy int variable that the compiler initializes calling Tune::add()
#define STRINGIFY(x) #x
#define UNIQUE2(x, y) x##y
#define UNIQUE(x, y) UNIQUE2(x, y) // Two indirection levels to expand __LINE__
#define TUNE(...) int UNIQUE(p, __LINE__) = Tune::add(STRINGIFY((__VA_ARGS__)), __VA_ARGS__)
#define UPDATE_ON_LAST() bool UNIQUE(p, __LINE__) = Tune::update_on_last = true
} // namespace Stockfish
#endif // #ifndef TUNE_H_INCLUDED
| 6,463
|
C++
|
.h
| 146
| 39.267123
| 104
| 0.659076
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,067
|
tbprobe.h
|
official-stockfish_Stockfish/src/syzygy/tbprobe.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TBPROBE_H
#define TBPROBE_H
#include <string>
#include <vector>
namespace Stockfish {
class Position;
class OptionsMap;
using Depth = int;
namespace Search {
struct RootMove;
using RootMoves = std::vector<RootMove>;
}
}
namespace Stockfish::Tablebases {
struct Config {
int cardinality = 0;
bool rootInTB = false;
bool useRule50 = false;
Depth probeDepth = 0;
};
enum WDLScore {
WDLLoss = -2, // Loss
WDLBlessedLoss = -1, // Loss, but draw under 50-move rule
WDLDraw = 0, // Draw
WDLCursedWin = 1, // Win, but draw under 50-move rule
WDLWin = 2, // Win
};
// Possible states after a probing operation
enum ProbeState {
FAIL = 0, // Probe failed (missing file table)
OK = 1, // Probe successful
CHANGE_STM = -1, // DTZ should check the other side
ZEROING_BEST_MOVE = 2 // Best move zeroes DTZ (capture or pawn move)
};
extern int MaxCardinality;
void init(const std::string& paths);
WDLScore probe_wdl(Position& pos, ProbeState* result);
int probe_dtz(Position& pos, ProbeState* result);
bool root_probe(Position& pos, Search::RootMoves& rootMoves, bool rule50, bool rankDTZ);
bool root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, bool rule50);
Config rank_root_moves(const OptionsMap& options,
Position& pos,
Search::RootMoves& rootMoves,
bool rankDTZ = false);
} // namespace Stockfish::Tablebases
#endif
| 2,365
|
C++
|
.h
| 60
| 35.6
| 92
| 0.683865
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,068
|
incbin.h
|
official-stockfish_Stockfish/src/incbin/incbin.h
|
/**
* @file incbin.h
* @author Dale Weiler
* @brief Utility for including binary files
*
* Facilities for including binary files into the current translation unit
* and making use of them externally in other translation units.
*/
#ifndef INCBIN_HDR
#define INCBIN_HDR
#include <limits.h>
#if defined(__AVX512BW__) || \
defined(__AVX512CD__) || \
defined(__AVX512DQ__) || \
defined(__AVX512ER__) || \
defined(__AVX512PF__) || \
defined(__AVX512VL__) || \
defined(__AVX512F__)
# define INCBIN_ALIGNMENT_INDEX 6
#elif defined(__AVX__) || \
defined(__AVX2__)
# define INCBIN_ALIGNMENT_INDEX 5
#elif defined(__SSE__) || \
defined(__SSE2__) || \
defined(__SSE3__) || \
defined(__SSSE3__) || \
defined(__SSE4_1__) || \
defined(__SSE4_2__) || \
defined(__neon__)
# define INCBIN_ALIGNMENT_INDEX 4
#elif ULONG_MAX != 0xffffffffu
# define INCBIN_ALIGNMENT_INDEX 3
# else
# define INCBIN_ALIGNMENT_INDEX 2
#endif
/* Lookup table of (1 << n) where `n' is `INCBIN_ALIGNMENT_INDEX' */
#define INCBIN_ALIGN_SHIFT_0 1
#define INCBIN_ALIGN_SHIFT_1 2
#define INCBIN_ALIGN_SHIFT_2 4
#define INCBIN_ALIGN_SHIFT_3 8
#define INCBIN_ALIGN_SHIFT_4 16
#define INCBIN_ALIGN_SHIFT_5 32
#define INCBIN_ALIGN_SHIFT_6 64
/* Actual alignment value */
#define INCBIN_ALIGNMENT \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_ALIGN_SHIFT, _), \
INCBIN_ALIGNMENT_INDEX)
/* Stringize */
#define INCBIN_STR(X) \
#X
#define INCBIN_STRINGIZE(X) \
INCBIN_STR(X)
/* Concatenate */
#define INCBIN_CAT(X, Y) \
X ## Y
#define INCBIN_CONCATENATE(X, Y) \
INCBIN_CAT(X, Y)
/* Deferred macro expansion */
#define INCBIN_EVAL(X) \
X
#define INCBIN_INVOKE(N, ...) \
INCBIN_EVAL(N(__VA_ARGS__))
/* Green Hills uses a different directive for including binary data */
#if defined(__ghs__)
# if (__ghs_asm == 2)
# define INCBIN_MACRO ".file"
/* Or consider the ".myrawdata" entry in the ld file */
# else
# define INCBIN_MACRO "\tINCBIN"
# endif
#else
# define INCBIN_MACRO ".incbin"
#endif
#ifndef _MSC_VER
# define INCBIN_ALIGN \
__attribute__((aligned(INCBIN_ALIGNMENT)))
#else
# define INCBIN_ALIGN __declspec(align(INCBIN_ALIGNMENT))
#endif
#if defined(__arm__) || /* GNU C and RealView */ \
defined(__arm) || /* Diab */ \
defined(_ARM) /* ImageCraft */
# define INCBIN_ARM
#endif
#ifdef __GNUC__
/* Utilize .balign where supported */
# define INCBIN_ALIGN_HOST ".balign " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
# define INCBIN_ALIGN_BYTE ".balign 1\n"
#elif defined(INCBIN_ARM)
/*
* On arm assemblers, the alignment value is calculated as (1 << n) where `n' is
* the shift count. This is the value passed to `.align'
*/
# define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT_INDEX) "\n"
# define INCBIN_ALIGN_BYTE ".align 0\n"
#else
/* We assume other inline assembler's treat `.align' as `.balign' */
# define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
# define INCBIN_ALIGN_BYTE ".align 1\n"
#endif
/* INCBIN_CONST is used by incbin.c generated files */
#if defined(__cplusplus)
# define INCBIN_EXTERNAL extern "C"
# define INCBIN_CONST extern const
#else
# define INCBIN_EXTERNAL extern
# define INCBIN_CONST const
#endif
/**
* @brief Optionally override the linker section into which data is emitted.
*
* @warning If you use this facility, you'll have to deal with platform-specific linker output
* section naming on your own
*
* Overriding the default linker output section, e.g for esp8266/Arduino:
* @code
* #define INCBIN_OUTPUT_SECTION ".irom.text"
* #include "incbin.h"
* INCBIN(Foo, "foo.txt");
* // Data is emitted into program memory that never gets copied to RAM
* @endcode
*/
#if !defined(INCBIN_OUTPUT_SECTION)
# if defined(__APPLE__)
# define INCBIN_OUTPUT_SECTION ".const_data"
# else
# define INCBIN_OUTPUT_SECTION ".rodata"
# endif
#endif
#if defined(__APPLE__)
/* The directives are different for Apple-branded compilers */
# define INCBIN_SECTION INCBIN_OUTPUT_SECTION "\n"
# define INCBIN_GLOBAL(NAME) ".globl " INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
# define INCBIN_INT ".long "
# define INCBIN_MANGLE "_"
# define INCBIN_BYTE ".byte "
# define INCBIN_TYPE(...)
#else
# define INCBIN_SECTION ".section " INCBIN_OUTPUT_SECTION "\n"
# define INCBIN_GLOBAL(NAME) ".global " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
# if defined(__ghs__)
# define INCBIN_INT ".word "
# else
# define INCBIN_INT ".int "
# endif
# if defined(__USER_LABEL_PREFIX__)
# define INCBIN_MANGLE INCBIN_STRINGIZE(__USER_LABEL_PREFIX__)
# else
# define INCBIN_MANGLE ""
# endif
# if defined(INCBIN_ARM)
/* On arm assemblers, `@' is used as a line comment token */
# define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", %object\n"
# elif defined(__MINGW32__) || defined(__MINGW64__)
/* Mingw doesn't support this directive either */
# define INCBIN_TYPE(NAME)
# else
/* It's safe to use `@' on other architectures */
# define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", @object\n"
# endif
# define INCBIN_BYTE ".byte "
#endif
/* List of style types used for symbol names */
#define INCBIN_STYLE_CAMEL 0
#define INCBIN_STYLE_SNAKE 1
/**
* @brief Specify the prefix to use for symbol names.
*
* By default this is `g', producing symbols of the form:
* @code
* #include "incbin.h"
* INCBIN(Foo, "foo.txt");
*
* // Now you have the following symbols:
* // const unsigned char gFooData[];
* // const unsigned char *const gFooEnd;
* // const unsigned int gFooSize;
* @endcode
*
* If however you specify a prefix before including: e.g:
* @code
* #define INCBIN_PREFIX incbin
* #include "incbin.h"
* INCBIN(Foo, "foo.txt");
*
* // Now you have the following symbols instead:
* // const unsigned char incbinFooData[];
* // const unsigned char *const incbinFooEnd;
* // const unsigned int incbinFooSize;
* @endcode
*/
#if !defined(INCBIN_PREFIX)
# define INCBIN_PREFIX g
#endif
/**
* @brief Specify the style used for symbol names.
*
* Possible options are
* - INCBIN_STYLE_CAMEL "CamelCase"
* - INCBIN_STYLE_SNAKE "snake_case"
*
* Default option is *INCBIN_STYLE_CAMEL* producing symbols of the form:
* @code
* #include "incbin.h"
* INCBIN(Foo, "foo.txt");
*
* // Now you have the following symbols:
* // const unsigned char <prefix>FooData[];
* // const unsigned char *const <prefix>FooEnd;
* // const unsigned int <prefix>FooSize;
* @endcode
*
* If however you specify a style before including: e.g:
* @code
* #define INCBIN_STYLE INCBIN_STYLE_SNAKE
* #include "incbin.h"
* INCBIN(foo, "foo.txt");
*
* // Now you have the following symbols:
* // const unsigned char <prefix>foo_data[];
* // const unsigned char *const <prefix>foo_end;
* // const unsigned int <prefix>foo_size;
* @endcode
*/
#if !defined(INCBIN_STYLE)
# define INCBIN_STYLE INCBIN_STYLE_CAMEL
#endif
/* Style lookup tables */
#define INCBIN_STYLE_0_DATA Data
#define INCBIN_STYLE_0_END End
#define INCBIN_STYLE_0_SIZE Size
#define INCBIN_STYLE_1_DATA _data
#define INCBIN_STYLE_1_END _end
#define INCBIN_STYLE_1_SIZE _size
/* Style lookup: returning identifier */
#define INCBIN_STYLE_IDENT(TYPE) \
INCBIN_CONCATENATE( \
INCBIN_STYLE_, \
INCBIN_CONCATENATE( \
INCBIN_EVAL(INCBIN_STYLE), \
INCBIN_CONCATENATE(_, TYPE)))
/* Style lookup: returning string literal */
#define INCBIN_STYLE_STRING(TYPE) \
INCBIN_STRINGIZE( \
INCBIN_STYLE_IDENT(TYPE)) \
/* Generate the global labels by indirectly invoking the macro
* with our style type and concatenate the name against them. */
#define INCBIN_GLOBAL_LABELS(NAME, TYPE) \
INCBIN_INVOKE( \
INCBIN_GLOBAL, \
INCBIN_CONCATENATE( \
NAME, \
INCBIN_INVOKE( \
INCBIN_STYLE_IDENT, \
TYPE))) \
INCBIN_INVOKE( \
INCBIN_TYPE, \
INCBIN_CONCATENATE( \
NAME, \
INCBIN_INVOKE( \
INCBIN_STYLE_IDENT, \
TYPE)))
/**
* @brief Externally reference binary data included in another translation unit.
*
* Produces three external symbols that reference the binary data included in
* another translation unit.
*
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
* "Data", as well as "End" and "Size" after. An example is provided below.
*
* @param NAME The name given for the binary data
*
* @code
* INCBIN_EXTERN(Foo);
*
* // Now you have the following symbols:
* // extern const unsigned char <prefix>FooData[];
* // extern const unsigned char *const <prefix>FooEnd;
* // extern const unsigned int <prefix>FooSize;
* @endcode
*/
#define INCBIN_EXTERN(NAME) \
INCBIN_EXTERNAL const INCBIN_ALIGN unsigned char \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
INCBIN_STYLE_IDENT(DATA))[]; \
INCBIN_EXTERNAL const INCBIN_ALIGN unsigned char *const \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
INCBIN_STYLE_IDENT(END)); \
INCBIN_EXTERNAL const unsigned int \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
INCBIN_STYLE_IDENT(SIZE))
/**
* @brief Include a binary file into the current translation unit.
*
* Includes a binary file into the current translation unit, producing three symbols
* for objects that encode the data and size respectively.
*
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
* "Data", as well as "End" and "Size" after. An example is provided below.
*
* @param NAME The name to associate with this binary data (as an identifier.)
* @param FILENAME The file to include (as a string literal.)
*
* @code
* INCBIN(Icon, "icon.png");
*
* // Now you have the following symbols:
* // const unsigned char <prefix>IconData[];
* // const unsigned char *const <prefix>IconEnd;
* // const unsigned int <prefix>IconSize;
* @endcode
*
* @warning This must be used in global scope
* @warning The identifiers may be different if INCBIN_STYLE is not default
*
* To externally reference the data included by this in another translation unit
* please @see INCBIN_EXTERN.
*/
#ifdef _MSC_VER
#define INCBIN(NAME, FILENAME) \
INCBIN_EXTERN(NAME)
#else
#define INCBIN(NAME, FILENAME) \
__asm__(INCBIN_SECTION \
INCBIN_GLOBAL_LABELS(NAME, DATA) \
INCBIN_ALIGN_HOST \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) ":\n" \
INCBIN_MACRO " \"" FILENAME "\"\n" \
INCBIN_GLOBAL_LABELS(NAME, END) \
INCBIN_ALIGN_BYTE \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) ":\n" \
INCBIN_BYTE "1\n" \
INCBIN_GLOBAL_LABELS(NAME, SIZE) \
INCBIN_ALIGN_HOST \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(SIZE) ":\n" \
INCBIN_INT INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) " - " \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) "\n" \
INCBIN_ALIGN_HOST \
".text\n" \
); \
INCBIN_EXTERN(NAME)
#endif
#endif
| 11,614
|
C++
|
.h
| 348
| 30.074713
| 111
| 0.669305
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
12,069
|
nnue_common.h
|
official-stockfish_Stockfish/src/nnue/nnue_common.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Constants used in NNUE evaluation function
#ifndef NNUE_COMMON_H_INCLUDED
#define NNUE_COMMON_H_INCLUDED
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <type_traits>
#include "../misc.h"
#if defined(USE_AVX2)
#include <immintrin.h>
#elif defined(USE_SSE41)
#include <smmintrin.h>
#elif defined(USE_SSSE3)
#include <tmmintrin.h>
#elif defined(USE_SSE2)
#include <emmintrin.h>
#elif defined(USE_NEON)
#include <arm_neon.h>
#endif
namespace Stockfish::Eval::NNUE {
// Version of the evaluation file
constexpr std::uint32_t Version = 0x7AF32F20u;
// Constant used in evaluation value calculation
constexpr int OutputScale = 16;
constexpr int WeightScaleBits = 6;
// Size of cache line (in bytes)
constexpr std::size_t CacheLineSize = 64;
constexpr const char Leb128MagicString[] = "COMPRESSED_LEB128";
constexpr const std::size_t Leb128MagicStringSize = sizeof(Leb128MagicString) - 1;
// SIMD width (in bytes)
#if defined(USE_AVX2)
constexpr std::size_t SimdWidth = 32;
#elif defined(USE_SSE2)
constexpr std::size_t SimdWidth = 16;
#elif defined(USE_NEON)
constexpr std::size_t SimdWidth = 16;
#endif
constexpr std::size_t MaxSimdWidth = 32;
// Type of input feature after conversion
using TransformedFeatureType = std::uint8_t;
using IndexType = std::uint32_t;
// Round n up to be a multiple of base
template<typename IntType>
constexpr IntType ceil_to_multiple(IntType n, IntType base) {
return (n + base - 1) / base * base;
}
// Utility to read an integer (signed or unsigned, any size)
// from a stream in little-endian order. We swap the byte order after the read if
// necessary to return a result with the byte ordering of the compiling machine.
template<typename IntType>
inline IntType read_little_endian(std::istream& stream) {
IntType result;
if (IsLittleEndian)
stream.read(reinterpret_cast<char*>(&result), sizeof(IntType));
else
{
std::uint8_t u[sizeof(IntType)];
std::make_unsigned_t<IntType> v = 0;
stream.read(reinterpret_cast<char*>(u), sizeof(IntType));
for (std::size_t i = 0; i < sizeof(IntType); ++i)
v = (v << 8) | u[sizeof(IntType) - i - 1];
std::memcpy(&result, &v, sizeof(IntType));
}
return result;
}
// Utility to write an integer (signed or unsigned, any size)
// to a stream in little-endian order. We swap the byte order before the write if
// necessary to always write in little-endian order, independently of the byte
// ordering of the compiling machine.
template<typename IntType>
inline void write_little_endian(std::ostream& stream, IntType value) {
if (IsLittleEndian)
stream.write(reinterpret_cast<const char*>(&value), sizeof(IntType));
else
{
std::uint8_t u[sizeof(IntType)];
std::make_unsigned_t<IntType> v = value;
std::size_t i = 0;
// if constexpr to silence the warning about shift by 8
if constexpr (sizeof(IntType) > 1)
{
for (; i + 1 < sizeof(IntType); ++i)
{
u[i] = std::uint8_t(v);
v >>= 8;
}
}
u[i] = std::uint8_t(v);
stream.write(reinterpret_cast<char*>(u), sizeof(IntType));
}
}
// Read integers in bulk from a little-endian stream.
// This reads N integers from stream s and puts them in array out.
template<typename IntType>
inline void read_little_endian(std::istream& stream, IntType* out, std::size_t count) {
if (IsLittleEndian)
stream.read(reinterpret_cast<char*>(out), sizeof(IntType) * count);
else
for (std::size_t i = 0; i < count; ++i)
out[i] = read_little_endian<IntType>(stream);
}
// Write integers in bulk to a little-endian stream.
// This takes N integers from array values and writes them on stream s.
template<typename IntType>
inline void write_little_endian(std::ostream& stream, const IntType* values, std::size_t count) {
if (IsLittleEndian)
stream.write(reinterpret_cast<const char*>(values), sizeof(IntType) * count);
else
for (std::size_t i = 0; i < count; ++i)
write_little_endian<IntType>(stream, values[i]);
}
// Read N signed integers from the stream s, putting them in the array out.
// The stream is assumed to be compressed using the signed LEB128 format.
// See https://en.wikipedia.org/wiki/LEB128 for a description of the compression scheme.
template<typename IntType>
inline void read_leb_128(std::istream& stream, IntType* out, std::size_t count) {
// Check the presence of our LEB128 magic string
char leb128MagicString[Leb128MagicStringSize];
stream.read(leb128MagicString, Leb128MagicStringSize);
assert(strncmp(Leb128MagicString, leb128MagicString, Leb128MagicStringSize) == 0);
static_assert(std::is_signed_v<IntType>, "Not implemented for unsigned types");
const std::uint32_t BUF_SIZE = 4096;
std::uint8_t buf[BUF_SIZE];
auto bytes_left = read_little_endian<std::uint32_t>(stream);
std::uint32_t buf_pos = BUF_SIZE;
for (std::size_t i = 0; i < count; ++i)
{
IntType result = 0;
size_t shift = 0;
do
{
if (buf_pos == BUF_SIZE)
{
stream.read(reinterpret_cast<char*>(buf), std::min(bytes_left, BUF_SIZE));
buf_pos = 0;
}
std::uint8_t byte = buf[buf_pos++];
--bytes_left;
result |= (byte & 0x7f) << shift;
shift += 7;
if ((byte & 0x80) == 0)
{
out[i] = (sizeof(IntType) * 8 <= shift || (byte & 0x40) == 0)
? result
: result | ~((1 << shift) - 1);
break;
}
} while (shift < sizeof(IntType) * 8);
}
assert(bytes_left == 0);
}
// Write signed integers to a stream with LEB128 compression.
// This takes N integers from array values, compresses them with
// the LEB128 algorithm and writes the result on the stream s.
// See https://en.wikipedia.org/wiki/LEB128 for a description of the compression scheme.
template<typename IntType>
inline void write_leb_128(std::ostream& stream, const IntType* values, std::size_t count) {
// Write our LEB128 magic string
stream.write(Leb128MagicString, Leb128MagicStringSize);
static_assert(std::is_signed_v<IntType>, "Not implemented for unsigned types");
std::uint32_t byte_count = 0;
for (std::size_t i = 0; i < count; ++i)
{
IntType value = values[i];
std::uint8_t byte;
do
{
byte = value & 0x7f;
value >>= 7;
++byte_count;
} while ((byte & 0x40) == 0 ? value != 0 : value != -1);
}
write_little_endian(stream, byte_count);
const std::uint32_t BUF_SIZE = 4096;
std::uint8_t buf[BUF_SIZE];
std::uint32_t buf_pos = 0;
auto flush = [&]() {
if (buf_pos > 0)
{
stream.write(reinterpret_cast<char*>(buf), buf_pos);
buf_pos = 0;
}
};
auto write = [&](std::uint8_t byte) {
buf[buf_pos++] = byte;
if (buf_pos == BUF_SIZE)
flush();
};
for (std::size_t i = 0; i < count; ++i)
{
IntType value = values[i];
while (true)
{
std::uint8_t byte = value & 0x7f;
value >>= 7;
if ((byte & 0x40) == 0 ? value == 0 : value == -1)
{
write(byte);
break;
}
write(byte | 0x80);
}
}
flush();
}
} // namespace Stockfish::Eval::NNUE
#endif // #ifndef NNUE_COMMON_H_INCLUDED
| 8,587
|
C++
|
.h
| 223
| 32.488789
| 97
| 0.638564
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,070
|
nnue_accumulator.h
|
official-stockfish_Stockfish/src/nnue/nnue_accumulator.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Class for difference calculation of NNUE evaluation function
#ifndef NNUE_ACCUMULATOR_H_INCLUDED
#define NNUE_ACCUMULATOR_H_INCLUDED
#include <cstdint>
#include "nnue_architecture.h"
#include "nnue_common.h"
namespace Stockfish::Eval::NNUE {
using BiasType = std::int16_t;
using PSQTWeightType = std::int32_t;
using IndexType = std::uint32_t;
// Class that holds the result of affine transformation of input features
template<IndexType Size>
struct alignas(CacheLineSize) Accumulator {
std::int16_t accumulation[COLOR_NB][Size];
std::int32_t psqtAccumulation[COLOR_NB][PSQTBuckets];
bool computed[COLOR_NB];
};
// AccumulatorCaches struct provides per-thread accumulator caches, where each
// cache contains multiple entries for each of the possible king squares.
// When the accumulator needs to be refreshed, the cached entry is used to more
// efficiently update the accumulator, instead of rebuilding it from scratch.
// This idea, was first described by Luecx (author of Koivisto) and
// is commonly referred to as "Finny Tables".
struct AccumulatorCaches {
template<typename Networks>
AccumulatorCaches(const Networks& networks) {
clear(networks);
}
template<IndexType Size>
struct alignas(CacheLineSize) Cache {
struct alignas(CacheLineSize) Entry {
BiasType accumulation[Size];
PSQTWeightType psqtAccumulation[PSQTBuckets];
Bitboard byColorBB[COLOR_NB];
Bitboard byTypeBB[PIECE_TYPE_NB];
// To initialize a refresh entry, we set all its bitboards empty,
// so we put the biases in the accumulation, without any weights on top
void clear(const BiasType* biases) {
std::memcpy(accumulation, biases, sizeof(accumulation));
std::memset((uint8_t*) this + offsetof(Entry, psqtAccumulation), 0,
sizeof(Entry) - offsetof(Entry, psqtAccumulation));
}
};
template<typename Network>
void clear(const Network& network) {
for (auto& entries1D : entries)
for (auto& entry : entries1D)
entry.clear(network.featureTransformer->biases);
}
std::array<Entry, COLOR_NB>& operator[](Square sq) { return entries[sq]; }
std::array<std::array<Entry, COLOR_NB>, SQUARE_NB> entries;
};
template<typename Networks>
void clear(const Networks& networks) {
big.clear(networks.big);
small.clear(networks.small);
}
Cache<TransformedFeatureDimensionsBig> big;
Cache<TransformedFeatureDimensionsSmall> small;
};
} // namespace Stockfish::Eval::NNUE
#endif // NNUE_ACCUMULATOR_H_INCLUDED
| 3,535
|
C++
|
.h
| 76
| 40.407895
| 83
| 0.707424
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,071
|
nnue_feature_transformer.h
|
official-stockfish_Stockfish/src/nnue/nnue_feature_transformer.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// A class that converts the input features of the NNUE evaluation function
#ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
#define NNUE_FEATURE_TRANSFORMER_H_INCLUDED
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <iosfwd>
#include <utility>
#include "../position.h"
#include "../types.h"
#include "nnue_accumulator.h"
#include "nnue_architecture.h"
#include "nnue_common.h"
namespace Stockfish::Eval::NNUE {
using BiasType = std::int16_t;
using WeightType = std::int16_t;
using PSQTWeightType = std::int32_t;
// If vector instructions are enabled, we update and refresh the
// accumulator tile by tile such that each tile fits in the CPU's
// vector registers.
#define VECTOR
static_assert(PSQTBuckets % 8 == 0,
"Per feature PSQT values cannot be processed at granularity lower than 8 at a time.");
#ifdef USE_AVX512
using vec_t = __m512i;
using psqt_vec_t = __m256i;
#define vec_load(a) _mm512_load_si512(a)
#define vec_store(a, b) _mm512_store_si512(a, b)
#define vec_add_16(a, b) _mm512_add_epi16(a, b)
#define vec_sub_16(a, b) _mm512_sub_epi16(a, b)
#define vec_mulhi_16(a, b) _mm512_mulhi_epi16(a, b)
#define vec_zero() _mm512_setzero_epi32()
#define vec_set_16(a) _mm512_set1_epi16(a)
#define vec_max_16(a, b) _mm512_max_epi16(a, b)
#define vec_min_16(a, b) _mm512_min_epi16(a, b)
#define vec_slli_16(a, b) _mm512_slli_epi16(a, b)
// Inverse permuted at load time
#define vec_packus_16(a, b) _mm512_packus_epi16(a, b)
#define vec_load_psqt(a) _mm256_load_si256(a)
#define vec_store_psqt(a, b) _mm256_store_si256(a, b)
#define vec_add_psqt_32(a, b) _mm256_add_epi32(a, b)
#define vec_sub_psqt_32(a, b) _mm256_sub_epi32(a, b)
#define vec_zero_psqt() _mm256_setzero_si256()
#define NumRegistersSIMD 16
#define MaxChunkSize 64
#elif USE_AVX2
using vec_t = __m256i;
using psqt_vec_t = __m256i;
#define vec_load(a) _mm256_load_si256(a)
#define vec_store(a, b) _mm256_store_si256(a, b)
#define vec_add_16(a, b) _mm256_add_epi16(a, b)
#define vec_sub_16(a, b) _mm256_sub_epi16(a, b)
#define vec_mulhi_16(a, b) _mm256_mulhi_epi16(a, b)
#define vec_zero() _mm256_setzero_si256()
#define vec_set_16(a) _mm256_set1_epi16(a)
#define vec_max_16(a, b) _mm256_max_epi16(a, b)
#define vec_min_16(a, b) _mm256_min_epi16(a, b)
#define vec_slli_16(a, b) _mm256_slli_epi16(a, b)
// Inverse permuted at load time
#define vec_packus_16(a, b) _mm256_packus_epi16(a, b)
#define vec_load_psqt(a) _mm256_load_si256(a)
#define vec_store_psqt(a, b) _mm256_store_si256(a, b)
#define vec_add_psqt_32(a, b) _mm256_add_epi32(a, b)
#define vec_sub_psqt_32(a, b) _mm256_sub_epi32(a, b)
#define vec_zero_psqt() _mm256_setzero_si256()
#define NumRegistersSIMD 16
#define MaxChunkSize 32
#elif USE_SSE2
using vec_t = __m128i;
using psqt_vec_t = __m128i;
#define vec_load(a) (*(a))
#define vec_store(a, b) *(a) = (b)
#define vec_add_16(a, b) _mm_add_epi16(a, b)
#define vec_sub_16(a, b) _mm_sub_epi16(a, b)
#define vec_mulhi_16(a, b) _mm_mulhi_epi16(a, b)
#define vec_zero() _mm_setzero_si128()
#define vec_set_16(a) _mm_set1_epi16(a)
#define vec_max_16(a, b) _mm_max_epi16(a, b)
#define vec_min_16(a, b) _mm_min_epi16(a, b)
#define vec_slli_16(a, b) _mm_slli_epi16(a, b)
#define vec_packus_16(a, b) _mm_packus_epi16(a, b)
#define vec_load_psqt(a) (*(a))
#define vec_store_psqt(a, b) *(a) = (b)
#define vec_add_psqt_32(a, b) _mm_add_epi32(a, b)
#define vec_sub_psqt_32(a, b) _mm_sub_epi32(a, b)
#define vec_zero_psqt() _mm_setzero_si128()
#define NumRegistersSIMD (Is64Bit ? 16 : 8)
#define MaxChunkSize 16
#elif USE_NEON
using vec_t = int16x8_t;
using psqt_vec_t = int32x4_t;
#define vec_load(a) (*(a))
#define vec_store(a, b) *(a) = (b)
#define vec_add_16(a, b) vaddq_s16(a, b)
#define vec_sub_16(a, b) vsubq_s16(a, b)
#define vec_mulhi_16(a, b) vqdmulhq_s16(a, b)
#define vec_zero() \
vec_t { 0 }
#define vec_set_16(a) vdupq_n_s16(a)
#define vec_max_16(a, b) vmaxq_s16(a, b)
#define vec_min_16(a, b) vminq_s16(a, b)
#define vec_slli_16(a, b) vshlq_s16(a, vec_set_16(b))
#define vec_packus_16(a, b) reinterpret_cast<vec_t>(vcombine_u8(vqmovun_s16(a), vqmovun_s16(b)))
#define vec_load_psqt(a) (*(a))
#define vec_store_psqt(a, b) *(a) = (b)
#define vec_add_psqt_32(a, b) vaddq_s32(a, b)
#define vec_sub_psqt_32(a, b) vsubq_s32(a, b)
#define vec_zero_psqt() \
psqt_vec_t { 0 }
#define NumRegistersSIMD 16
#define MaxChunkSize 16
#else
#undef VECTOR
#endif
#ifdef VECTOR
// Compute optimal SIMD register count for feature transformer accumulation.
// We use __m* types as template arguments, which causes GCC to emit warnings
// about losing some attribute information. This is irrelevant to us as we
// only take their size, so the following pragma are harmless.
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wignored-attributes"
#endif
template<typename SIMDRegisterType, typename LaneType, int NumLanes, int MaxRegisters>
static constexpr int BestRegisterCount() {
#define RegisterSize sizeof(SIMDRegisterType)
#define LaneSize sizeof(LaneType)
static_assert(RegisterSize >= LaneSize);
static_assert(MaxRegisters <= NumRegistersSIMD);
static_assert(MaxRegisters > 0);
static_assert(NumRegistersSIMD > 0);
static_assert(RegisterSize % LaneSize == 0);
static_assert((NumLanes * LaneSize) % RegisterSize == 0);
const int ideal = (NumLanes * LaneSize) / RegisterSize;
if (ideal <= MaxRegisters)
return ideal;
// Look for the largest divisor of the ideal register count that is smaller than MaxRegisters
for (int divisor = MaxRegisters; divisor > 1; --divisor)
if (ideal % divisor == 0)
return divisor;
return 1;
}
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#endif
// Input feature converter
template<IndexType TransformedFeatureDimensions,
Accumulator<TransformedFeatureDimensions> StateInfo::*accPtr>
class FeatureTransformer {
// Number of output dimensions for one side
static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
private:
#ifdef VECTOR
static constexpr int NumRegs =
BestRegisterCount<vec_t, WeightType, TransformedFeatureDimensions, NumRegistersSIMD>();
static constexpr int NumPsqtRegs =
BestRegisterCount<psqt_vec_t, PSQTWeightType, PSQTBuckets, NumRegistersSIMD>();
static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
#endif
public:
// Output type
using OutputType = TransformedFeatureType;
// Number of input/output dimensions
static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
static constexpr IndexType OutputDimensions = HalfDimensions;
// Size of forward propagation buffer
static constexpr std::size_t BufferSize = OutputDimensions * sizeof(OutputType);
// Hash value embedded in the evaluation file
static constexpr std::uint32_t get_hash_value() {
return FeatureSet::HashValue ^ (OutputDimensions * 2);
}
static constexpr void order_packs([[maybe_unused]] uint64_t* v) {
#if defined(USE_AVX512) // _mm512_packs_epi16 ordering
uint64_t tmp0 = v[2], tmp1 = v[3];
v[2] = v[8], v[3] = v[9];
v[8] = v[4], v[9] = v[5];
v[4] = tmp0, v[5] = tmp1;
tmp0 = v[6], tmp1 = v[7];
v[6] = v[10], v[7] = v[11];
v[10] = v[12], v[11] = v[13];
v[12] = tmp0, v[13] = tmp1;
#elif defined(USE_AVX2) // _mm256_packs_epi16 ordering
std::swap(v[2], v[4]);
std::swap(v[3], v[5]);
#endif
}
static constexpr void inverse_order_packs([[maybe_unused]] uint64_t* v) {
#if defined(USE_AVX512) // Inverse _mm512_packs_epi16 ordering
uint64_t tmp0 = v[2], tmp1 = v[3];
v[2] = v[4], v[3] = v[5];
v[4] = v[8], v[5] = v[9];
v[8] = tmp0, v[9] = tmp1;
tmp0 = v[6], tmp1 = v[7];
v[6] = v[12], v[7] = v[13];
v[12] = v[10], v[13] = v[11];
v[10] = tmp0, v[11] = tmp1;
#elif defined(USE_AVX2) // Inverse _mm256_packs_epi16 ordering
std::swap(v[2], v[4]);
std::swap(v[3], v[5]);
#endif
}
void permute_weights([[maybe_unused]] void (*order_fn)(uint64_t*)) const {
#if defined(USE_AVX2)
#if defined(USE_AVX512)
constexpr IndexType di = 16;
#else
constexpr IndexType di = 8;
#endif
uint64_t* b = reinterpret_cast<uint64_t*>(const_cast<BiasType*>(&biases[0]));
for (IndexType i = 0; i < HalfDimensions * sizeof(BiasType) / sizeof(uint64_t); i += di)
order_fn(&b[i]);
for (IndexType j = 0; j < InputDimensions; ++j)
{
uint64_t* w =
reinterpret_cast<uint64_t*>(const_cast<WeightType*>(&weights[j * HalfDimensions]));
for (IndexType i = 0; i < HalfDimensions * sizeof(WeightType) / sizeof(uint64_t);
i += di)
order_fn(&w[i]);
}
#endif
}
inline void scale_weights(bool read) const {
for (IndexType j = 0; j < InputDimensions; ++j)
{
WeightType* w = const_cast<WeightType*>(&weights[j * HalfDimensions]);
for (IndexType i = 0; i < HalfDimensions; ++i)
w[i] = read ? w[i] * 2 : w[i] / 2;
}
BiasType* b = const_cast<BiasType*>(biases);
for (IndexType i = 0; i < HalfDimensions; ++i)
b[i] = read ? b[i] * 2 : b[i] / 2;
}
// Read network parameters
bool read_parameters(std::istream& stream) {
read_leb_128<BiasType>(stream, biases, HalfDimensions);
read_leb_128<WeightType>(stream, weights, HalfDimensions * InputDimensions);
read_leb_128<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
permute_weights(inverse_order_packs);
scale_weights(true);
return !stream.fail();
}
// Write network parameters
bool write_parameters(std::ostream& stream) const {
permute_weights(order_packs);
scale_weights(false);
write_leb_128<BiasType>(stream, biases, HalfDimensions);
write_leb_128<WeightType>(stream, weights, HalfDimensions * InputDimensions);
write_leb_128<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
permute_weights(inverse_order_packs);
scale_weights(true);
return !stream.fail();
}
// Convert input features
std::int32_t transform(const Position& pos,
AccumulatorCaches::Cache<HalfDimensions>* cache,
OutputType* output,
int bucket) const {
update_accumulator<WHITE>(pos, cache);
update_accumulator<BLACK>(pos, cache);
const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
const auto& psqtAccumulation = (pos.state()->*accPtr).psqtAccumulation;
const auto psqt =
(psqtAccumulation[perspectives[0]][bucket] - psqtAccumulation[perspectives[1]][bucket])
/ 2;
const auto& accumulation = (pos.state()->*accPtr).accumulation;
for (IndexType p = 0; p < 2; ++p)
{
const IndexType offset = (HalfDimensions / 2) * p;
#if defined(VECTOR)
constexpr IndexType OutputChunkSize = MaxChunkSize;
static_assert((HalfDimensions / 2) % OutputChunkSize == 0);
constexpr IndexType NumOutputChunks = HalfDimensions / 2 / OutputChunkSize;
const vec_t Zero = vec_zero();
const vec_t One = vec_set_16(127 * 2);
const vec_t* in0 = reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][0]));
const vec_t* in1 =
reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][HalfDimensions / 2]));
vec_t* out = reinterpret_cast<vec_t*>(output + offset);
// Per the NNUE architecture, here we want to multiply pairs of
// clipped elements and divide the product by 128. To do this,
// we can naively perform min/max operation to clip each of the
// four int16 vectors, mullo pairs together, then pack them into
// one int8 vector. However, there exists a faster way.
// The idea here is to use the implicit clipping from packus to
// save us two vec_max_16 instructions. This clipping works due
// to the fact that any int16 integer below zero will be zeroed
// on packus.
// Consider the case where the second element is negative.
// If we do standard clipping, that element will be zero, which
// means our pairwise product is zero. If we perform packus and
// remove the lower-side clip for the second element, then our
// product before packus will be negative, and is zeroed on pack.
// The two operation produce equivalent results, but the second
// one (using packus) saves one max operation per pair.
// But here we run into a problem: mullo does not preserve the
// sign of the multiplication. We can get around this by doing
// mulhi, which keeps the sign. But that requires an additional
// tweak.
// mulhi cuts off the last 16 bits of the resulting product,
// which is the same as performing a rightward shift of 16 bits.
// We can use this to our advantage. Recall that we want to
// divide the final product by 128, which is equivalent to a
// 7-bit right shift. Intuitively, if we shift the clipped
// value left by 9, and perform mulhi, which shifts the product
// right by 16 bits, then we will net a right shift of 7 bits.
// However, this won't work as intended. Since we clip the
// values to have a maximum value of 127, shifting it by 9 bits
// might occupy the signed bit, resulting in some positive
// values being interpreted as negative after the shift.
// There is a way, however, to get around this limitation. When
// loading the network, scale accumulator weights and biases by
// 2. To get the same pairwise multiplication result as before,
// we need to divide the product by 128 * 2 * 2 = 512, which
// amounts to a right shift of 9 bits. So now we only have to
// shift left by 7 bits, perform mulhi (shifts right by 16 bits)
// and net a 9 bit right shift. Since we scaled everything by
// two, the values are clipped at 127 * 2 = 254, which occupies
// 8 bits. Shifting it by 7 bits left will no longer occupy the
// signed bit, so we are safe.
// Note that on NEON processors, we shift left by 6 instead
// because the instruction "vqdmulhq_s16" also doubles the
// return value after the multiplication, adding an extra shift
// to the left by 1, so we compensate by shifting less before
// the multiplication.
constexpr int shift =
#if defined(USE_SSE2)
7;
#else
6;
#endif
for (IndexType j = 0; j < NumOutputChunks; ++j)
{
const vec_t sum0a =
vec_slli_16(vec_max_16(vec_min_16(in0[j * 2 + 0], One), Zero), shift);
const vec_t sum0b =
vec_slli_16(vec_max_16(vec_min_16(in0[j * 2 + 1], One), Zero), shift);
const vec_t sum1a = vec_min_16(in1[j * 2 + 0], One);
const vec_t sum1b = vec_min_16(in1[j * 2 + 1], One);
const vec_t pa = vec_mulhi_16(sum0a, sum1a);
const vec_t pb = vec_mulhi_16(sum0b, sum1b);
out[j] = vec_packus_16(pa, pb);
}
#else
for (IndexType j = 0; j < HalfDimensions / 2; ++j)
{
BiasType sum0 = accumulation[static_cast<int>(perspectives[p])][j + 0];
BiasType sum1 =
accumulation[static_cast<int>(perspectives[p])][j + HalfDimensions / 2];
sum0 = std::clamp<BiasType>(sum0, 0, 127 * 2);
sum1 = std::clamp<BiasType>(sum1, 0, 127 * 2);
output[offset + j] = static_cast<OutputType>(unsigned(sum0 * sum1) / 512);
}
#endif
}
return psqt;
} // end of function transform()
void hint_common_access(const Position& pos,
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
hint_common_access_for_perspective<WHITE>(pos, cache);
hint_common_access_for_perspective<BLACK>(pos, cache);
}
private:
template<Color Perspective>
StateInfo* try_find_computed_accumulator(const Position& pos) const {
// Look for a usable accumulator of an earlier position. We keep track
// of the estimated gain in terms of features to be added/subtracted.
StateInfo* st = pos.state();
int gain = FeatureSet::refresh_cost(pos);
while (st->previous && !(st->*accPtr).computed[Perspective])
{
// This governs when a full feature refresh is needed and how many
// updates are better than just one full refresh.
if (FeatureSet::requires_refresh(st, Perspective)
|| (gain -= FeatureSet::update_cost(st) + 1) < 0)
break;
st = st->previous;
}
return st;
}
// It computes the accumulator of the next position, or updates the
// current position's accumulator if CurrentOnly is true.
template<Color Perspective, bool CurrentOnly>
void update_accumulator_incremental(const Position& pos, StateInfo* computed) const {
assert((computed->*accPtr).computed[Perspective]);
assert(computed->next != nullptr);
#ifdef VECTOR
// Gcc-10.2 unnecessarily spills AVX2 registers if this array
// is defined in the VECTOR code below, once in each branch.
vec_t acc[NumRegs];
psqt_vec_t psqt[NumPsqtRegs];
#endif
const Square ksq = pos.square<KING>(Perspective);
// The size must be enough to contain the largest possible update.
// That might depend on the feature set and generally relies on the
// feature set's update cost calculation to be correct and never allow
// updates with more added/removed features than MaxActiveDimensions.
FeatureSet::IndexList removed, added;
if constexpr (CurrentOnly)
for (StateInfo* st = pos.state(); st != computed; st = st->previous)
FeatureSet::append_changed_indices<Perspective>(ksq, st->dirtyPiece, removed,
added);
else
FeatureSet::append_changed_indices<Perspective>(ksq, computed->next->dirtyPiece,
removed, added);
StateInfo* next = CurrentOnly ? pos.state() : computed->next;
assert(!(next->*accPtr).computed[Perspective]);
#ifdef VECTOR
if ((removed.size() == 1 || removed.size() == 2) && added.size() == 1)
{
auto accIn =
reinterpret_cast<const vec_t*>(&(computed->*accPtr).accumulation[Perspective][0]);
auto accOut = reinterpret_cast<vec_t*>(&(next->*accPtr).accumulation[Perspective][0]);
const IndexType offsetR0 = HalfDimensions * removed[0];
auto columnR0 = reinterpret_cast<const vec_t*>(&weights[offsetR0]);
const IndexType offsetA = HalfDimensions * added[0];
auto columnA = reinterpret_cast<const vec_t*>(&weights[offsetA]);
if (removed.size() == 1)
{
for (IndexType i = 0; i < HalfDimensions * sizeof(WeightType) / sizeof(vec_t); ++i)
accOut[i] = vec_add_16(vec_sub_16(accIn[i], columnR0[i]), columnA[i]);
}
else
{
const IndexType offsetR1 = HalfDimensions * removed[1];
auto columnR1 = reinterpret_cast<const vec_t*>(&weights[offsetR1]);
for (IndexType i = 0; i < HalfDimensions * sizeof(WeightType) / sizeof(vec_t); ++i)
accOut[i] = vec_sub_16(vec_add_16(accIn[i], columnA[i]),
vec_add_16(columnR0[i], columnR1[i]));
}
auto accPsqtIn = reinterpret_cast<const psqt_vec_t*>(
&(computed->*accPtr).psqtAccumulation[Perspective][0]);
auto accPsqtOut =
reinterpret_cast<psqt_vec_t*>(&(next->*accPtr).psqtAccumulation[Perspective][0]);
const IndexType offsetPsqtR0 = PSQTBuckets * removed[0];
auto columnPsqtR0 = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtR0]);
const IndexType offsetPsqtA = PSQTBuckets * added[0];
auto columnPsqtA = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtA]);
if (removed.size() == 1)
{
for (std::size_t i = 0;
i < PSQTBuckets * sizeof(PSQTWeightType) / sizeof(psqt_vec_t); ++i)
accPsqtOut[i] = vec_add_psqt_32(vec_sub_psqt_32(accPsqtIn[i], columnPsqtR0[i]),
columnPsqtA[i]);
}
else
{
const IndexType offsetPsqtR1 = PSQTBuckets * removed[1];
auto columnPsqtR1 = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtR1]);
for (std::size_t i = 0;
i < PSQTBuckets * sizeof(PSQTWeightType) / sizeof(psqt_vec_t); ++i)
accPsqtOut[i] =
vec_sub_psqt_32(vec_add_psqt_32(accPsqtIn[i], columnPsqtA[i]),
vec_add_psqt_32(columnPsqtR0[i], columnPsqtR1[i]));
}
}
else
{
for (IndexType i = 0; i < HalfDimensions / TileHeight; ++i)
{
// Load accumulator
auto accTileIn = reinterpret_cast<const vec_t*>(
&(computed->*accPtr).accumulation[Perspective][i * TileHeight]);
for (IndexType j = 0; j < NumRegs; ++j)
acc[j] = vec_load(&accTileIn[j]);
// Difference calculation for the deactivated features
for (const auto index : removed)
{
const IndexType offset = HalfDimensions * index + i * TileHeight;
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
for (IndexType j = 0; j < NumRegs; ++j)
acc[j] = vec_sub_16(acc[j], column[j]);
}
// Difference calculation for the activated features
for (const auto index : added)
{
const IndexType offset = HalfDimensions * index + i * TileHeight;
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
for (IndexType j = 0; j < NumRegs; ++j)
acc[j] = vec_add_16(acc[j], column[j]);
}
// Store accumulator
auto accTileOut = reinterpret_cast<vec_t*>(
&(next->*accPtr).accumulation[Perspective][i * TileHeight]);
for (IndexType j = 0; j < NumRegs; ++j)
vec_store(&accTileOut[j], acc[j]);
}
for (IndexType i = 0; i < PSQTBuckets / PsqtTileHeight; ++i)
{
// Load accumulator
auto accTilePsqtIn = reinterpret_cast<const psqt_vec_t*>(
&(computed->*accPtr).psqtAccumulation[Perspective][i * PsqtTileHeight]);
for (std::size_t j = 0; j < NumPsqtRegs; ++j)
psqt[j] = vec_load_psqt(&accTilePsqtIn[j]);
// Difference calculation for the deactivated features
for (const auto index : removed)
{
const IndexType offset = PSQTBuckets * index + i * PsqtTileHeight;
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
for (std::size_t j = 0; j < NumPsqtRegs; ++j)
psqt[j] = vec_sub_psqt_32(psqt[j], columnPsqt[j]);
}
// Difference calculation for the activated features
for (const auto index : added)
{
const IndexType offset = PSQTBuckets * index + i * PsqtTileHeight;
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
for (std::size_t j = 0; j < NumPsqtRegs; ++j)
psqt[j] = vec_add_psqt_32(psqt[j], columnPsqt[j]);
}
// Store accumulator
auto accTilePsqtOut = reinterpret_cast<psqt_vec_t*>(
&(next->*accPtr).psqtAccumulation[Perspective][i * PsqtTileHeight]);
for (std::size_t j = 0; j < NumPsqtRegs; ++j)
vec_store_psqt(&accTilePsqtOut[j], psqt[j]);
}
}
#else
std::memcpy((next->*accPtr).accumulation[Perspective],
(computed->*accPtr).accumulation[Perspective],
HalfDimensions * sizeof(BiasType));
std::memcpy((next->*accPtr).psqtAccumulation[Perspective],
(computed->*accPtr).psqtAccumulation[Perspective],
PSQTBuckets * sizeof(PSQTWeightType));
// Difference calculation for the deactivated features
for (const auto index : removed)
{
const IndexType offset = HalfDimensions * index;
for (IndexType i = 0; i < HalfDimensions; ++i)
(next->*accPtr).accumulation[Perspective][i] -= weights[offset + i];
for (std::size_t i = 0; i < PSQTBuckets; ++i)
(next->*accPtr).psqtAccumulation[Perspective][i] -=
psqtWeights[index * PSQTBuckets + i];
}
// Difference calculation for the activated features
for (const auto index : added)
{
const IndexType offset = HalfDimensions * index;
for (IndexType i = 0; i < HalfDimensions; ++i)
(next->*accPtr).accumulation[Perspective][i] += weights[offset + i];
for (std::size_t i = 0; i < PSQTBuckets; ++i)
(next->*accPtr).psqtAccumulation[Perspective][i] +=
psqtWeights[index * PSQTBuckets + i];
}
#endif
(next->*accPtr).computed[Perspective] = true;
if (!CurrentOnly && next != pos.state())
update_accumulator_incremental<Perspective, false>(pos, next);
}
template<Color Perspective>
void update_accumulator_refresh_cache(const Position& pos,
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
assert(cache != nullptr);
Square ksq = pos.square<KING>(Perspective);
auto& entry = (*cache)[ksq][Perspective];
FeatureSet::IndexList removed, added;
for (Color c : {WHITE, BLACK})
{
for (PieceType pt = PAWN; pt <= KING; ++pt)
{
const Piece piece = make_piece(c, pt);
const Bitboard oldBB = entry.byColorBB[c] & entry.byTypeBB[pt];
const Bitboard newBB = pos.pieces(c, pt);
Bitboard toRemove = oldBB & ~newBB;
Bitboard toAdd = newBB & ~oldBB;
while (toRemove)
{
Square sq = pop_lsb(toRemove);
removed.push_back(FeatureSet::make_index<Perspective>(sq, piece, ksq));
}
while (toAdd)
{
Square sq = pop_lsb(toAdd);
added.push_back(FeatureSet::make_index<Perspective>(sq, piece, ksq));
}
}
}
auto& accumulator = pos.state()->*accPtr;
accumulator.computed[Perspective] = true;
#ifdef VECTOR
vec_t acc[NumRegs];
psqt_vec_t psqt[NumPsqtRegs];
for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
{
auto accTile =
reinterpret_cast<vec_t*>(&accumulator.accumulation[Perspective][j * TileHeight]);
auto entryTile = reinterpret_cast<vec_t*>(&entry.accumulation[j * TileHeight]);
for (IndexType k = 0; k < NumRegs; ++k)
acc[k] = entryTile[k];
int i = 0;
for (; i < int(std::min(removed.size(), added.size())); ++i)
{
IndexType indexR = removed[i];
const IndexType offsetR = HalfDimensions * indexR + j * TileHeight;
auto columnR = reinterpret_cast<const vec_t*>(&weights[offsetR]);
IndexType indexA = added[i];
const IndexType offsetA = HalfDimensions * indexA + j * TileHeight;
auto columnA = reinterpret_cast<const vec_t*>(&weights[offsetA]);
for (unsigned k = 0; k < NumRegs; ++k)
acc[k] = vec_add_16(acc[k], vec_sub_16(columnA[k], columnR[k]));
}
for (; i < int(removed.size()); ++i)
{
IndexType index = removed[i];
const IndexType offset = HalfDimensions * index + j * TileHeight;
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
for (unsigned k = 0; k < NumRegs; ++k)
acc[k] = vec_sub_16(acc[k], column[k]);
}
for (; i < int(added.size()); ++i)
{
IndexType index = added[i];
const IndexType offset = HalfDimensions * index + j * TileHeight;
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
for (unsigned k = 0; k < NumRegs; ++k)
acc[k] = vec_add_16(acc[k], column[k]);
}
for (IndexType k = 0; k < NumRegs; k++)
vec_store(&entryTile[k], acc[k]);
for (IndexType k = 0; k < NumRegs; k++)
vec_store(&accTile[k], acc[k]);
}
for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
{
auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
&accumulator.psqtAccumulation[Perspective][j * PsqtTileHeight]);
auto entryTilePsqt =
reinterpret_cast<psqt_vec_t*>(&entry.psqtAccumulation[j * PsqtTileHeight]);
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
psqt[k] = entryTilePsqt[k];
for (int i = 0; i < int(removed.size()); ++i)
{
IndexType index = removed[i];
const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
}
for (int i = 0; i < int(added.size()); ++i)
{
IndexType index = added[i];
const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
}
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
vec_store_psqt(&entryTilePsqt[k], psqt[k]);
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
vec_store_psqt(&accTilePsqt[k], psqt[k]);
}
#else
for (const auto index : removed)
{
const IndexType offset = HalfDimensions * index;
for (IndexType j = 0; j < HalfDimensions; ++j)
entry.accumulation[j] -= weights[offset + j];
for (std::size_t k = 0; k < PSQTBuckets; ++k)
entry.psqtAccumulation[k] -= psqtWeights[index * PSQTBuckets + k];
}
for (const auto index : added)
{
const IndexType offset = HalfDimensions * index;
for (IndexType j = 0; j < HalfDimensions; ++j)
entry.accumulation[j] += weights[offset + j];
for (std::size_t k = 0; k < PSQTBuckets; ++k)
entry.psqtAccumulation[k] += psqtWeights[index * PSQTBuckets + k];
}
// The accumulator of the refresh entry has been updated.
// Now copy its content to the actual accumulator we were refreshing.
std::memcpy(accumulator.accumulation[Perspective], entry.accumulation,
sizeof(BiasType) * HalfDimensions);
std::memcpy(accumulator.psqtAccumulation[Perspective], entry.psqtAccumulation,
sizeof(int32_t) * PSQTBuckets);
#endif
for (Color c : {WHITE, BLACK})
entry.byColorBB[c] = pos.pieces(c);
for (PieceType pt = PAWN; pt <= KING; ++pt)
entry.byTypeBB[pt] = pos.pieces(pt);
}
template<Color Perspective>
void hint_common_access_for_perspective(const Position& pos,
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
// Works like update_accumulator, but performs less work.
// Updates ONLY the accumulator for pos.
// Look for a usable accumulator of an earlier position. We keep track
// of the estimated gain in terms of features to be added/subtracted.
// Fast early exit.
if ((pos.state()->*accPtr).computed[Perspective])
return;
StateInfo* oldest = try_find_computed_accumulator<Perspective>(pos);
if ((oldest->*accPtr).computed[Perspective] && oldest != pos.state())
update_accumulator_incremental<Perspective, true>(pos, oldest);
else
update_accumulator_refresh_cache<Perspective>(pos, cache);
}
template<Color Perspective>
void update_accumulator(const Position& pos,
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
StateInfo* oldest = try_find_computed_accumulator<Perspective>(pos);
if ((oldest->*accPtr).computed[Perspective] && oldest != pos.state())
// Start from the oldest computed accumulator, update all the
// accumulators up to the current position.
update_accumulator_incremental<Perspective, false>(pos, oldest);
else
update_accumulator_refresh_cache<Perspective>(pos, cache);
}
template<IndexType Size>
friend struct AccumulatorCaches::Cache;
alignas(CacheLineSize) BiasType biases[HalfDimensions];
alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
};
} // namespace Stockfish::Eval::NNUE
#endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
| 37,236
|
C++
|
.h
| 733
| 39.961801
| 100
| 0.58323
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,072
|
nnue_misc.h
|
official-stockfish_Stockfish/src/nnue/nnue_misc.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NNUE_MISC_H_INCLUDED
#define NNUE_MISC_H_INCLUDED
#include <cstddef>
#include <string>
#include "../types.h"
#include "nnue_architecture.h"
namespace Stockfish {
class Position;
namespace Eval::NNUE {
struct EvalFile {
// Default net name, will use one of the EvalFileDefaultName* macros defined
// in evaluate.h
std::string defaultName;
// Selected net name, either via uci option or default
std::string current;
// Net description extracted from the net file
std::string netDescription;
};
struct NnueEvalTrace {
static_assert(LayerStacks == PSQTBuckets);
Value psqt[LayerStacks];
Value positional[LayerStacks];
std::size_t correctBucket;
};
struct Networks;
struct AccumulatorCaches;
std::string trace(Position& pos, const Networks& networks, AccumulatorCaches& caches);
void hint_common_parent_position(const Position& pos,
const Networks& networks,
AccumulatorCaches& caches);
} // namespace Stockfish::Eval::NNUE
} // namespace Stockfish
#endif // #ifndef NNUE_MISC_H_INCLUDED
| 1,926
|
C++
|
.h
| 47
| 36.468085
| 86
| 0.728249
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,073
|
network.h
|
official-stockfish_Stockfish/src/nnue/network.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NETWORK_H_INCLUDED
#define NETWORK_H_INCLUDED
#include <cstdint>
#include <functional>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
#include "../memory.h"
#include "../position.h"
#include "../types.h"
#include "nnue_accumulator.h"
#include "nnue_architecture.h"
#include "nnue_feature_transformer.h"
#include "nnue_misc.h"
namespace Stockfish::Eval::NNUE {
enum class EmbeddedNNUEType {
BIG,
SMALL,
};
using NetworkOutput = std::tuple<Value, Value>;
template<typename Arch, typename Transformer>
class Network {
static constexpr IndexType FTDimensions = Arch::TransformedFeatureDimensions;
public:
Network(EvalFile file, EmbeddedNNUEType type) :
evalFile(file),
embeddedType(type) {}
Network(const Network& other);
Network(Network&& other) = default;
Network& operator=(const Network& other);
Network& operator=(Network&& other) = default;
void load(const std::string& rootDirectory, std::string evalfilePath);
bool save(const std::optional<std::string>& filename) const;
NetworkOutput evaluate(const Position& pos,
AccumulatorCaches::Cache<FTDimensions>* cache) const;
void hint_common_access(const Position& pos,
AccumulatorCaches::Cache<FTDimensions>* cache) const;
void verify(std::string evalfilePath, const std::function<void(std::string_view)>&) const;
NnueEvalTrace trace_evaluate(const Position& pos,
AccumulatorCaches::Cache<FTDimensions>* cache) const;
private:
void load_user_net(const std::string&, const std::string&);
void load_internal();
void initialize();
bool save(std::ostream&, const std::string&, const std::string&) const;
std::optional<std::string> load(std::istream&);
bool read_header(std::istream&, std::uint32_t*, std::string*) const;
bool write_header(std::ostream&, std::uint32_t, const std::string&) const;
bool read_parameters(std::istream&, std::string&) const;
bool write_parameters(std::ostream&, const std::string&) const;
// Input feature converter
LargePagePtr<Transformer> featureTransformer;
// Evaluation function
AlignedPtr<Arch[]> network;
EvalFile evalFile;
EmbeddedNNUEType embeddedType;
// Hash value of evaluation function structure
static constexpr std::uint32_t hash = Transformer::get_hash_value() ^ Arch::get_hash_value();
template<IndexType Size>
friend struct AccumulatorCaches::Cache;
};
// Definitions of the network types
using SmallFeatureTransformer =
FeatureTransformer<TransformedFeatureDimensionsSmall, &StateInfo::accumulatorSmall>;
using SmallNetworkArchitecture =
NetworkArchitecture<TransformedFeatureDimensionsSmall, L2Small, L3Small>;
using BigFeatureTransformer =
FeatureTransformer<TransformedFeatureDimensionsBig, &StateInfo::accumulatorBig>;
using BigNetworkArchitecture = NetworkArchitecture<TransformedFeatureDimensionsBig, L2Big, L3Big>;
using NetworkBig = Network<BigNetworkArchitecture, BigFeatureTransformer>;
using NetworkSmall = Network<SmallNetworkArchitecture, SmallFeatureTransformer>;
struct Networks {
Networks(NetworkBig&& nB, NetworkSmall&& nS) :
big(std::move(nB)),
small(std::move(nS)) {}
NetworkBig big;
NetworkSmall small;
};
} // namespace Stockfish
#endif
| 4,315
|
C++
|
.h
| 97
| 40.010309
| 98
| 0.728055
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,074
|
nnue_architecture.h
|
official-stockfish_Stockfish/src/nnue/nnue_architecture.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Input features and network structure used in NNUE evaluation function
#ifndef NNUE_ARCHITECTURE_H_INCLUDED
#define NNUE_ARCHITECTURE_H_INCLUDED
#include <cstdint>
#include <cstring>
#include <iosfwd>
#include "features/half_ka_v2_hm.h"
#include "layers/affine_transform.h"
#include "layers/affine_transform_sparse_input.h"
#include "layers/clipped_relu.h"
#include "layers/sqr_clipped_relu.h"
#include "nnue_common.h"
namespace Stockfish::Eval::NNUE {
// Input features used in evaluation function
using FeatureSet = Features::HalfKAv2_hm;
// Number of input feature dimensions after conversion
constexpr IndexType TransformedFeatureDimensionsBig = 3072;
constexpr int L2Big = 15;
constexpr int L3Big = 32;
constexpr IndexType TransformedFeatureDimensionsSmall = 128;
constexpr int L2Small = 15;
constexpr int L3Small = 32;
constexpr IndexType PSQTBuckets = 8;
constexpr IndexType LayerStacks = 8;
template<IndexType L1, int L2, int L3>
struct NetworkArchitecture {
static constexpr IndexType TransformedFeatureDimensions = L1;
static constexpr int FC_0_OUTPUTS = L2;
static constexpr int FC_1_OUTPUTS = L3;
Layers::AffineTransformSparseInput<TransformedFeatureDimensions, FC_0_OUTPUTS + 1> fc_0;
Layers::SqrClippedReLU<FC_0_OUTPUTS + 1> ac_sqr_0;
Layers::ClippedReLU<FC_0_OUTPUTS + 1> ac_0;
Layers::AffineTransform<FC_0_OUTPUTS * 2, FC_1_OUTPUTS> fc_1;
Layers::ClippedReLU<FC_1_OUTPUTS> ac_1;
Layers::AffineTransform<FC_1_OUTPUTS, 1> fc_2;
// Hash value embedded in the evaluation file
static constexpr std::uint32_t get_hash_value() {
// input slice hash
std::uint32_t hashValue = 0xEC42E90Du;
hashValue ^= TransformedFeatureDimensions * 2;
hashValue = decltype(fc_0)::get_hash_value(hashValue);
hashValue = decltype(ac_0)::get_hash_value(hashValue);
hashValue = decltype(fc_1)::get_hash_value(hashValue);
hashValue = decltype(ac_1)::get_hash_value(hashValue);
hashValue = decltype(fc_2)::get_hash_value(hashValue);
return hashValue;
}
// Read network parameters
bool read_parameters(std::istream& stream) {
return fc_0.read_parameters(stream) && ac_0.read_parameters(stream)
&& fc_1.read_parameters(stream) && ac_1.read_parameters(stream)
&& fc_2.read_parameters(stream);
}
// Write network parameters
bool write_parameters(std::ostream& stream) const {
return fc_0.write_parameters(stream) && ac_0.write_parameters(stream)
&& fc_1.write_parameters(stream) && ac_1.write_parameters(stream)
&& fc_2.write_parameters(stream);
}
std::int32_t propagate(const TransformedFeatureType* transformedFeatures) {
struct alignas(CacheLineSize) Buffer {
alignas(CacheLineSize) typename decltype(fc_0)::OutputBuffer fc_0_out;
alignas(CacheLineSize) typename decltype(ac_sqr_0)::OutputType
ac_sqr_0_out[ceil_to_multiple<IndexType>(FC_0_OUTPUTS * 2, 32)];
alignas(CacheLineSize) typename decltype(ac_0)::OutputBuffer ac_0_out;
alignas(CacheLineSize) typename decltype(fc_1)::OutputBuffer fc_1_out;
alignas(CacheLineSize) typename decltype(ac_1)::OutputBuffer ac_1_out;
alignas(CacheLineSize) typename decltype(fc_2)::OutputBuffer fc_2_out;
Buffer() { std::memset(this, 0, sizeof(*this)); }
};
#if defined(__clang__) && (__APPLE__)
// workaround for a bug reported with xcode 12
static thread_local auto tlsBuffer = std::make_unique<Buffer>();
// Access TLS only once, cache result.
Buffer& buffer = *tlsBuffer;
#else
alignas(CacheLineSize) static thread_local Buffer buffer;
#endif
fc_0.propagate(transformedFeatures, buffer.fc_0_out);
ac_sqr_0.propagate(buffer.fc_0_out, buffer.ac_sqr_0_out);
ac_0.propagate(buffer.fc_0_out, buffer.ac_0_out);
std::memcpy(buffer.ac_sqr_0_out + FC_0_OUTPUTS, buffer.ac_0_out,
FC_0_OUTPUTS * sizeof(typename decltype(ac_0)::OutputType));
fc_1.propagate(buffer.ac_sqr_0_out, buffer.fc_1_out);
ac_1.propagate(buffer.fc_1_out, buffer.ac_1_out);
fc_2.propagate(buffer.ac_1_out, buffer.fc_2_out);
// buffer.fc_0_out[FC_0_OUTPUTS] is such that 1.0 is equal to 127*(1<<WeightScaleBits) in
// quantized form, but we want 1.0 to be equal to 600*OutputScale
std::int32_t fwdOut =
(buffer.fc_0_out[FC_0_OUTPUTS]) * (600 * OutputScale) / (127 * (1 << WeightScaleBits));
std::int32_t outputValue = buffer.fc_2_out[0] + fwdOut;
return outputValue;
}
};
} // namespace Stockfish::Eval::NNUE
#endif // #ifndef NNUE_ARCHITECTURE_H_INCLUDED
| 5,913
|
C++
|
.h
| 110
| 47.781818
| 97
| 0.659107
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,075
|
clipped_relu.h
|
official-stockfish_Stockfish/src/nnue/layers/clipped_relu.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Definition of layer ClippedReLU of NNUE evaluation function
#ifndef NNUE_LAYERS_CLIPPED_RELU_H_INCLUDED
#define NNUE_LAYERS_CLIPPED_RELU_H_INCLUDED
#include <algorithm>
#include <cstdint>
#include <iosfwd>
#include "../nnue_common.h"
namespace Stockfish::Eval::NNUE::Layers {
// Clipped ReLU
template<IndexType InDims>
class ClippedReLU {
public:
// Input/output type
using InputType = std::int32_t;
using OutputType = std::uint8_t;
// Number of input/output dimensions
static constexpr IndexType InputDimensions = InDims;
static constexpr IndexType OutputDimensions = InputDimensions;
static constexpr IndexType PaddedOutputDimensions =
ceil_to_multiple<IndexType>(OutputDimensions, 32);
using OutputBuffer = OutputType[PaddedOutputDimensions];
// Hash value embedded in the evaluation file
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
std::uint32_t hashValue = 0x538D24C7u;
hashValue += prevHash;
return hashValue;
}
// Read network parameters
bool read_parameters(std::istream&) { return true; }
// Write network parameters
bool write_parameters(std::ostream&) const { return true; }
// Forward propagation
void propagate(const InputType* input, OutputType* output) const {
#if defined(USE_AVX2)
if constexpr (InputDimensions % SimdWidth == 0)
{
constexpr IndexType NumChunks = InputDimensions / SimdWidth;
const __m256i Offsets = _mm256_set_epi32(7, 3, 6, 2, 5, 1, 4, 0);
const auto in = reinterpret_cast<const __m256i*>(input);
const auto out = reinterpret_cast<__m256i*>(output);
for (IndexType i = 0; i < NumChunks; ++i)
{
const __m256i words0 =
_mm256_srli_epi16(_mm256_packus_epi32(_mm256_load_si256(&in[i * 4 + 0]),
_mm256_load_si256(&in[i * 4 + 1])),
WeightScaleBits);
const __m256i words1 =
_mm256_srli_epi16(_mm256_packus_epi32(_mm256_load_si256(&in[i * 4 + 2]),
_mm256_load_si256(&in[i * 4 + 3])),
WeightScaleBits);
_mm256_store_si256(&out[i], _mm256_permutevar8x32_epi32(
_mm256_packs_epi16(words0, words1), Offsets));
}
}
else
{
constexpr IndexType NumChunks = InputDimensions / (SimdWidth / 2);
const auto in = reinterpret_cast<const __m128i*>(input);
const auto out = reinterpret_cast<__m128i*>(output);
for (IndexType i = 0; i < NumChunks; ++i)
{
const __m128i words0 = _mm_srli_epi16(
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1])),
WeightScaleBits);
const __m128i words1 = _mm_srli_epi16(
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3])),
WeightScaleBits);
_mm_store_si128(&out[i], _mm_packs_epi16(words0, words1));
}
}
constexpr IndexType Start = InputDimensions % SimdWidth == 0
? InputDimensions / SimdWidth * SimdWidth
: InputDimensions / (SimdWidth / 2) * (SimdWidth / 2);
#elif defined(USE_SSE2)
constexpr IndexType NumChunks = InputDimensions / SimdWidth;
#ifndef USE_SSE41
const __m128i k0x80s = _mm_set1_epi8(-128);
#endif
const auto in = reinterpret_cast<const __m128i*>(input);
const auto out = reinterpret_cast<__m128i*>(output);
for (IndexType i = 0; i < NumChunks; ++i)
{
#if defined(USE_SSE41)
const __m128i words0 = _mm_srli_epi16(
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1])),
WeightScaleBits);
const __m128i words1 = _mm_srli_epi16(
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3])),
WeightScaleBits);
_mm_store_si128(&out[i], _mm_packs_epi16(words0, words1));
#else
const __m128i words0 = _mm_srai_epi16(
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1])),
WeightScaleBits);
const __m128i words1 = _mm_srai_epi16(
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3])),
WeightScaleBits);
const __m128i packedbytes = _mm_packs_epi16(words0, words1);
_mm_store_si128(&out[i], _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s));
#endif
}
constexpr IndexType Start = NumChunks * SimdWidth;
#elif defined(USE_NEON)
constexpr IndexType NumChunks = InputDimensions / (SimdWidth / 2);
const int8x8_t Zero = {0};
const auto in = reinterpret_cast<const int32x4_t*>(input);
const auto out = reinterpret_cast<int8x8_t*>(output);
for (IndexType i = 0; i < NumChunks; ++i)
{
int16x8_t shifted;
const auto pack = reinterpret_cast<int16x4_t*>(&shifted);
pack[0] = vqshrn_n_s32(in[i * 2 + 0], WeightScaleBits);
pack[1] = vqshrn_n_s32(in[i * 2 + 1], WeightScaleBits);
out[i] = vmax_s8(vqmovn_s16(shifted), Zero);
}
constexpr IndexType Start = NumChunks * (SimdWidth / 2);
#else
constexpr IndexType Start = 0;
#endif
for (IndexType i = Start; i < InputDimensions; ++i)
{
output[i] = static_cast<OutputType>(std::clamp(input[i] >> WeightScaleBits, 0, 127));
}
}
};
} // namespace Stockfish::Eval::NNUE::Layers
#endif // NNUE_LAYERS_CLIPPED_RELU_H_INCLUDED
| 6,903
|
C++
|
.h
| 141
| 38.609929
| 99
| 0.581095
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,076
|
affine_transform.h
|
official-stockfish_Stockfish/src/nnue/layers/affine_transform.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Definition of layer AffineTransform of NNUE evaluation function
#ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
#define NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
#include <cstdint>
#include <iostream>
#include "../nnue_common.h"
#include "simd.h"
/*
This file contains the definition for a fully connected layer (aka affine transform).
- expected use-case is for when PaddedInputDimensions == 32 and InputDimensions <= 32.
- that's why AVX512 is hard to implement
- expected use-case is small layers
- inputs are processed in chunks of 4, weights are respectively transposed
- accumulation happens directly to int32s
*/
namespace Stockfish::Eval::NNUE::Layers {
#if defined(USE_SSSE3) || defined(USE_NEON_DOTPROD)
#define ENABLE_SEQ_OPT
#endif
// Fallback implementation for older/other architectures.
// Requires the input to be padded to at least 16 values.
#ifndef ENABLE_SEQ_OPT
template<IndexType InputDimensions, IndexType PaddedInputDimensions, IndexType OutputDimensions>
static void affine_transform_non_ssse3(std::int32_t* output,
const std::int8_t* weights,
const std::int32_t* biases,
const std::uint8_t* input) {
#if defined(USE_SSE2) || defined(USE_NEON)
#if defined(USE_SSE2)
// At least a multiple of 16, with SSE2.
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
const __m128i Zeros = _mm_setzero_si128();
const auto inputVector = reinterpret_cast<const __m128i*>(input);
#elif defined(USE_NEON)
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
#endif
for (IndexType i = 0; i < OutputDimensions; ++i)
{
const IndexType offset = i * PaddedInputDimensions;
#if defined(USE_SSE2)
__m128i sumLo = _mm_cvtsi32_si128(biases[i]);
__m128i sumHi = Zeros;
const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
for (IndexType j = 0; j < NumChunks; ++j)
{
__m128i row_j = _mm_load_si128(&row[j]);
__m128i input_j = _mm_load_si128(&inputVector[j]);
__m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);
__m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);
__m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);
__m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);
__m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);
__m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);
sumLo = _mm_add_epi32(sumLo, productLo);
sumHi = _mm_add_epi32(sumHi, productHi);
}
__m128i sum = _mm_add_epi32(sumLo, sumHi);
__m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
sum = _mm_add_epi32(sum, sumHigh_64);
__m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
sum = _mm_add_epi32(sum, sum_second_32);
output[i] = _mm_cvtsi128_si32(sum);
#elif defined(USE_NEON)
int32x4_t sum = {biases[i]};
const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
for (IndexType j = 0; j < NumChunks; ++j)
{
int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
sum = vpadalq_s16(sum, product);
}
output[i] = sum[0] + sum[1] + sum[2] + sum[3];
#endif
}
#else
std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);
// Traverse weights in transpose order to take advantage of input sparsity
for (IndexType i = 0; i < InputDimensions; ++i)
if (input[i])
{
const std::int8_t* w = &weights[i];
const int in = input[i];
for (IndexType j = 0; j < OutputDimensions; ++j)
output[j] += w[j * PaddedInputDimensions] * in;
}
#endif
}
#endif // !ENABLE_SEQ_OPT
template<IndexType InDims, IndexType OutDims>
class AffineTransform {
public:
// Input/output type
using InputType = std::uint8_t;
using OutputType = std::int32_t;
// Number of input/output dimensions
static constexpr IndexType InputDimensions = InDims;
static constexpr IndexType OutputDimensions = OutDims;
static constexpr IndexType PaddedInputDimensions =
ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
static constexpr IndexType PaddedOutputDimensions =
ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
using OutputBuffer = OutputType[PaddedOutputDimensions];
// Hash value embedded in the evaluation file
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
std::uint32_t hashValue = 0xCC03DAE4u;
hashValue += OutputDimensions;
hashValue ^= prevHash >> 1;
hashValue ^= prevHash << 31;
return hashValue;
}
static constexpr IndexType get_weight_index_scrambled(IndexType i) {
return (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4
+ i / PaddedInputDimensions * 4 + i % 4;
}
static constexpr IndexType get_weight_index(IndexType i) {
#ifdef ENABLE_SEQ_OPT
return get_weight_index_scrambled(i);
#else
return i;
#endif
}
// Read network parameters
bool read_parameters(std::istream& stream) {
read_little_endian<BiasType>(stream, biases, OutputDimensions);
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
return !stream.fail();
}
// Write network parameters
bool write_parameters(std::ostream& stream) const {
write_little_endian<BiasType>(stream, biases, OutputDimensions);
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
return !stream.fail();
}
// Forward propagation
void propagate(const InputType* input, OutputType* output) const {
#ifdef ENABLE_SEQ_OPT
if constexpr (OutputDimensions > 1)
{
#if defined(USE_AVX512)
using vec_t = __m512i;
#define vec_set_32 _mm512_set1_epi32
#define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
#elif defined(USE_AVX2)
using vec_t = __m256i;
#define vec_set_32 _mm256_set1_epi32
#define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
#elif defined(USE_SSSE3)
using vec_t = __m128i;
#define vec_set_32 _mm_set1_epi32
#define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
#elif defined(USE_NEON_DOTPROD)
using vec_t = int32x4_t;
#define vec_set_32 vdupq_n_s32
#define vec_add_dpbusd_32(acc, a, b) \
Simd::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \
vreinterpretq_s8_s32(b))
#endif
static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
static_assert(OutputDimensions % OutputSimdWidth == 0);
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
const auto input32 = reinterpret_cast<const std::int32_t*>(input);
const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
vec_t acc[NumRegs];
for (IndexType k = 0; k < NumRegs; ++k)
acc[k] = biasvec[k];
for (IndexType i = 0; i < NumChunks; ++i)
{
const vec_t in0 = vec_set_32(input32[i]);
const auto col0 =
reinterpret_cast<const vec_t*>(&weights[i * OutputDimensions * 4]);
for (IndexType k = 0; k < NumRegs; ++k)
vec_add_dpbusd_32(acc[k], in0, col0[k]);
}
vec_t* outptr = reinterpret_cast<vec_t*>(output);
for (IndexType k = 0; k < NumRegs; ++k)
outptr[k] = acc[k];
#undef vec_set_32
#undef vec_add_dpbusd_32
}
else if constexpr (OutputDimensions == 1)
{
// We cannot use AVX512 for the last layer because there are only 32 inputs
// and the buffer is not padded to 64 elements.
#if defined(USE_AVX2)
using vec_t = __m256i;
#define vec_setzero() _mm256_setzero_si256()
#define vec_set_32 _mm256_set1_epi32
#define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
#define vec_hadd Simd::m256_hadd
#elif defined(USE_SSSE3)
using vec_t = __m128i;
#define vec_setzero() _mm_setzero_si128()
#define vec_set_32 _mm_set1_epi32
#define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
#define vec_hadd Simd::m128_hadd
#elif defined(USE_NEON_DOTPROD)
using vec_t = int32x4_t;
#define vec_setzero() vdupq_n_s32(0)
#define vec_set_32 vdupq_n_s32
#define vec_add_dpbusd_32(acc, a, b) \
Simd::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \
vreinterpretq_s8_s32(b))
#define vec_hadd Simd::neon_m128_hadd
#endif
const auto inputVector = reinterpret_cast<const vec_t*>(input);
static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);
static_assert(PaddedInputDimensions % InputSimdWidth == 0);
constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;
vec_t sum0 = vec_setzero();
const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
for (int j = 0; j < int(NumChunks); ++j)
{
const vec_t in = inputVector[j];
vec_add_dpbusd_32(sum0, in, row0[j]);
}
output[0] = vec_hadd(sum0, biases[0]);
#undef vec_setzero
#undef vec_set_32
#undef vec_add_dpbusd_32
#undef vec_hadd
}
#else
// Use old implementation for the other architectures.
affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
output, weights, biases, input);
#endif
}
private:
using BiasType = OutputType;
using WeightType = std::int8_t;
alignas(CacheLineSize) BiasType biases[OutputDimensions];
alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
};
} // namespace Stockfish::Eval::NNUE::Layers
#endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
| 12,047
|
C++
|
.h
| 253
| 38.992095
| 96
| 0.622775
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,077
|
sqr_clipped_relu.h
|
official-stockfish_Stockfish/src/nnue/layers/sqr_clipped_relu.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Definition of layer ClippedReLU of NNUE evaluation function
#ifndef NNUE_LAYERS_SQR_CLIPPED_RELU_H_INCLUDED
#define NNUE_LAYERS_SQR_CLIPPED_RELU_H_INCLUDED
#include <algorithm>
#include <cstdint>
#include <iosfwd>
#include "../nnue_common.h"
namespace Stockfish::Eval::NNUE::Layers {
// Clipped ReLU
template<IndexType InDims>
class SqrClippedReLU {
public:
// Input/output type
using InputType = std::int32_t;
using OutputType = std::uint8_t;
// Number of input/output dimensions
static constexpr IndexType InputDimensions = InDims;
static constexpr IndexType OutputDimensions = InputDimensions;
static constexpr IndexType PaddedOutputDimensions =
ceil_to_multiple<IndexType>(OutputDimensions, 32);
using OutputBuffer = OutputType[PaddedOutputDimensions];
// Hash value embedded in the evaluation file
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
std::uint32_t hashValue = 0x538D24C7u;
hashValue += prevHash;
return hashValue;
}
// Read network parameters
bool read_parameters(std::istream&) { return true; }
// Write network parameters
bool write_parameters(std::ostream&) const { return true; }
// Forward propagation
void propagate(const InputType* input, OutputType* output) const {
#if defined(USE_SSE2)
constexpr IndexType NumChunks = InputDimensions / 16;
static_assert(WeightScaleBits == 6);
const auto in = reinterpret_cast<const __m128i*>(input);
const auto out = reinterpret_cast<__m128i*>(output);
for (IndexType i = 0; i < NumChunks; ++i)
{
__m128i words0 =
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1]));
__m128i words1 =
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3]));
// We shift by WeightScaleBits * 2 = 12 and divide by 128
// which is an additional shift-right of 7, meaning 19 in total.
// MulHi strips the lower 16 bits so we need to shift out 3 more to match.
words0 = _mm_srli_epi16(_mm_mulhi_epi16(words0, words0), 3);
words1 = _mm_srli_epi16(_mm_mulhi_epi16(words1, words1), 3);
_mm_store_si128(&out[i], _mm_packs_epi16(words0, words1));
}
constexpr IndexType Start = NumChunks * 16;
#else
constexpr IndexType Start = 0;
#endif
for (IndexType i = Start; i < InputDimensions; ++i)
{
output[i] = static_cast<OutputType>(
// Really should be /127 but we need to make it fast so we right-shift
// by an extra 7 bits instead. Needs to be accounted for in the trainer.
std::min(127ll, ((long long) (input[i]) * input[i]) >> (2 * WeightScaleBits + 7)));
}
}
};
} // namespace Stockfish::Eval::NNUE::Layers
#endif // NNUE_LAYERS_SQR_CLIPPED_RELU_H_INCLUDED
| 3,744
|
C++
|
.h
| 80
| 40.475
| 97
| 0.67811
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,078
|
affine_transform_sparse_input.h
|
official-stockfish_Stockfish/src/nnue/layers/affine_transform_sparse_input.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Definition of layer AffineTransformSparseInput of NNUE evaluation function
#ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
#define NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include "../../bitboard.h"
#include "../nnue_common.h"
#include "affine_transform.h"
#include "simd.h"
/*
This file contains the definition for a fully connected layer (aka affine transform) with block sparse input.
*/
namespace Stockfish::Eval::NNUE::Layers {
#if (USE_SSSE3 | (USE_NEON >= 8))
alignas(CacheLineSize) static inline const
std::array<std::array<std::uint16_t, 8>, 256> lookup_indices = []() {
std::array<std::array<std::uint16_t, 8>, 256> v{};
for (unsigned i = 0; i < 256; ++i)
{
std::uint64_t j = i, k = 0;
while (j)
v[i][k++] = pop_lsb(j);
}
return v;
}();
// Find indices of nonzero numbers in an int32_t array
template<const IndexType InputDimensions>
void find_nnz(const std::int32_t* input, std::uint16_t* out, IndexType& count_out) {
#if defined(USE_SSSE3)
#if defined(USE_AVX512)
using vec_t = __m512i;
#define vec_nnz(a) _mm512_cmpgt_epi32_mask(a, _mm512_setzero_si512())
#elif defined(USE_AVX2)
using vec_t = __m256i;
#if defined(USE_VNNI) && !defined(USE_AVXVNNI)
#define vec_nnz(a) _mm256_cmpgt_epi32_mask(a, _mm256_setzero_si256())
#else
#define vec_nnz(a) \
_mm256_movemask_ps( \
_mm256_castsi256_ps(_mm256_cmpgt_epi32(a, _mm256_setzero_si256())))
#endif
#elif defined(USE_SSSE3)
using vec_t = __m128i;
#define vec_nnz(a) \
_mm_movemask_ps(_mm_castsi128_ps(_mm_cmpgt_epi32(a, _mm_setzero_si128())))
#endif
using vec128_t = __m128i;
#define vec128_zero _mm_setzero_si128()
#define vec128_set_16(a) _mm_set1_epi16(a)
#define vec128_load(a) _mm_load_si128(a)
#define vec128_storeu(a, b) _mm_storeu_si128(a, b)
#define vec128_add(a, b) _mm_add_epi16(a, b)
#elif defined(USE_NEON)
using vec_t = uint32x4_t;
static const std::uint32_t Mask[4] = {1, 2, 4, 8};
#define vec_nnz(a) vaddvq_u32(vandq_u32(vtstq_u32(a, a), vld1q_u32(Mask)))
using vec128_t = uint16x8_t;
#define vec128_zero vdupq_n_u16(0)
#define vec128_set_16(a) vdupq_n_u16(a)
#define vec128_load(a) vld1q_u16(reinterpret_cast<const std::uint16_t*>(a))
#define vec128_storeu(a, b) vst1q_u16(reinterpret_cast<std::uint16_t*>(a), b)
#define vec128_add(a, b) vaddq_u16(a, b)
#endif
constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(std::int32_t);
// Inputs are processed InputSimdWidth at a time and outputs are processed 8 at a time so we process in chunks of max(InputSimdWidth, 8)
constexpr IndexType ChunkSize = std::max<IndexType>(InputSimdWidth, 8);
constexpr IndexType NumChunks = InputDimensions / ChunkSize;
constexpr IndexType InputsPerChunk = ChunkSize / InputSimdWidth;
constexpr IndexType OutputsPerChunk = ChunkSize / 8;
const auto inputVector = reinterpret_cast<const vec_t*>(input);
IndexType count = 0;
vec128_t base = vec128_zero;
const vec128_t increment = vec128_set_16(8);
for (IndexType i = 0; i < NumChunks; ++i)
{
// bitmask of nonzero values in this chunk
unsigned nnz = 0;
for (IndexType j = 0; j < InputsPerChunk; ++j)
{
const vec_t inputChunk = inputVector[i * InputsPerChunk + j];
nnz |= unsigned(vec_nnz(inputChunk)) << (j * InputSimdWidth);
}
for (IndexType j = 0; j < OutputsPerChunk; ++j)
{
const auto lookup = (nnz >> (j * 8)) & 0xFF;
const auto offsets =
vec128_load(reinterpret_cast<const vec128_t*>(&lookup_indices[lookup]));
vec128_storeu(reinterpret_cast<vec128_t*>(out + count), vec128_add(base, offsets));
count += popcount(lookup);
base = vec128_add(base, increment);
}
}
count_out = count;
}
#undef vec_nnz
#undef vec128_zero
#undef vec128_set_16
#undef vec128_load
#undef vec128_storeu
#undef vec128_add
#endif
// Sparse input implementation
template<IndexType InDims, IndexType OutDims>
class AffineTransformSparseInput {
public:
// Input/output type
using InputType = std::uint8_t;
using OutputType = std::int32_t;
// Number of input/output dimensions
static constexpr IndexType InputDimensions = InDims;
static constexpr IndexType OutputDimensions = OutDims;
static_assert(OutputDimensions % 16 == 0,
"Only implemented for OutputDimensions divisible by 16.");
static constexpr IndexType PaddedInputDimensions =
ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
static constexpr IndexType PaddedOutputDimensions =
ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
#if (USE_SSSE3 | (USE_NEON >= 8))
static constexpr IndexType ChunkSize = 4;
#else
static constexpr IndexType ChunkSize = 1;
#endif
using OutputBuffer = OutputType[PaddedOutputDimensions];
// Hash value embedded in the evaluation file
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
std::uint32_t hashValue = 0xCC03DAE4u;
hashValue += OutputDimensions;
hashValue ^= prevHash >> 1;
hashValue ^= prevHash << 31;
return hashValue;
}
static constexpr IndexType get_weight_index_scrambled(IndexType i) {
return (i / ChunkSize) % (PaddedInputDimensions / ChunkSize) * OutputDimensions * ChunkSize
+ i / PaddedInputDimensions * ChunkSize + i % ChunkSize;
}
static constexpr IndexType get_weight_index(IndexType i) {
#if (USE_SSSE3 | (USE_NEON >= 8))
return get_weight_index_scrambled(i);
#else
return i;
#endif
}
// Read network parameters
bool read_parameters(std::istream& stream) {
read_little_endian<BiasType>(stream, biases, OutputDimensions);
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
return !stream.fail();
}
// Write network parameters
bool write_parameters(std::ostream& stream) const {
write_little_endian<BiasType>(stream, biases, OutputDimensions);
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
return !stream.fail();
}
// Forward propagation
void propagate(const InputType* input, OutputType* output) const {
#if (USE_SSSE3 | (USE_NEON >= 8))
#if defined(USE_AVX512)
using invec_t = __m512i;
using outvec_t = __m512i;
#define vec_set_32 _mm512_set1_epi32
#define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
#elif defined(USE_AVX2)
using invec_t = __m256i;
using outvec_t = __m256i;
#define vec_set_32 _mm256_set1_epi32
#define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
#elif defined(USE_SSSE3)
using invec_t = __m128i;
using outvec_t = __m128i;
#define vec_set_32 _mm_set1_epi32
#define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
#elif defined(USE_NEON_DOTPROD)
using invec_t = int8x16_t;
using outvec_t = int32x4_t;
#define vec_set_32(a) vreinterpretq_s8_u32(vdupq_n_u32(a))
#define vec_add_dpbusd_32 Simd::dotprod_m128_add_dpbusd_epi32
#elif defined(USE_NEON)
using invec_t = int8x16_t;
using outvec_t = int32x4_t;
#define vec_set_32(a) vreinterpretq_s8_u32(vdupq_n_u32(a))
#define vec_add_dpbusd_32 Simd::neon_m128_add_dpbusd_epi32
#endif
static constexpr IndexType OutputSimdWidth = sizeof(outvec_t) / sizeof(OutputType);
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / ChunkSize;
constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
std::uint16_t nnz[NumChunks];
IndexType count;
const auto input32 = reinterpret_cast<const std::int32_t*>(input);
// Find indices of nonzero 32-bit blocks
find_nnz<NumChunks>(input32, nnz, count);
const outvec_t* biasvec = reinterpret_cast<const outvec_t*>(biases);
outvec_t acc[NumRegs];
for (IndexType k = 0; k < NumRegs; ++k)
acc[k] = biasvec[k];
for (IndexType j = 0; j < count; ++j)
{
const auto i = nnz[j];
const invec_t in = vec_set_32(input32[i]);
const auto col =
reinterpret_cast<const invec_t*>(&weights[i * OutputDimensions * ChunkSize]);
for (IndexType k = 0; k < NumRegs; ++k)
vec_add_dpbusd_32(acc[k], in, col[k]);
}
outvec_t* outptr = reinterpret_cast<outvec_t*>(output);
for (IndexType k = 0; k < NumRegs; ++k)
outptr[k] = acc[k];
#undef vec_set_32
#undef vec_add_dpbusd_32
#else
// Use dense implementation for the other architectures.
affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
output, weights, biases, input);
#endif
}
private:
using BiasType = OutputType;
using WeightType = std::int8_t;
alignas(CacheLineSize) BiasType biases[OutputDimensions];
alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
};
} // namespace Stockfish::Eval::NNUE::Layers
#endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
| 10,753
|
C++
|
.h
| 241
| 37.626556
| 140
| 0.650692
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,079
|
simd.h
|
official-stockfish_Stockfish/src/nnue/layers/simd.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef STOCKFISH_SIMD_H_INCLUDED
#define STOCKFISH_SIMD_H_INCLUDED
#if defined(USE_AVX2)
#include <immintrin.h>
#elif defined(USE_SSE41)
#include <smmintrin.h>
#elif defined(USE_SSSE3)
#include <tmmintrin.h>
#elif defined(USE_SSE2)
#include <emmintrin.h>
#elif defined(USE_NEON)
#include <arm_neon.h>
#endif
namespace Stockfish::Simd {
#if defined(USE_AVX512)
[[maybe_unused]] static int m512_hadd(__m512i sum, int bias) {
return _mm512_reduce_add_epi32(sum) + bias;
}
[[maybe_unused]] static void m512_add_dpbusd_epi32(__m512i& acc, __m512i a, __m512i b) {
#if defined(USE_VNNI)
acc = _mm512_dpbusd_epi32(acc, a, b);
#else
__m512i product0 = _mm512_maddubs_epi16(a, b);
product0 = _mm512_madd_epi16(product0, _mm512_set1_epi16(1));
acc = _mm512_add_epi32(acc, product0);
#endif
}
#endif
#if defined(USE_AVX2)
[[maybe_unused]] static int m256_hadd(__m256i sum, int bias) {
__m128i sum128 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256(sum, 1));
sum128 = _mm_add_epi32(sum128, _mm_shuffle_epi32(sum128, _MM_PERM_BADC));
sum128 = _mm_add_epi32(sum128, _mm_shuffle_epi32(sum128, _MM_PERM_CDAB));
return _mm_cvtsi128_si32(sum128) + bias;
}
[[maybe_unused]] static void m256_add_dpbusd_epi32(__m256i& acc, __m256i a, __m256i b) {
#if defined(USE_VNNI)
acc = _mm256_dpbusd_epi32(acc, a, b);
#else
__m256i product0 = _mm256_maddubs_epi16(a, b);
product0 = _mm256_madd_epi16(product0, _mm256_set1_epi16(1));
acc = _mm256_add_epi32(acc, product0);
#endif
}
#endif
#if defined(USE_SSSE3)
[[maybe_unused]] static int m128_hadd(__m128i sum, int bias) {
sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0x4E)); //_MM_PERM_BADC
sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0xB1)); //_MM_PERM_CDAB
return _mm_cvtsi128_si32(sum) + bias;
}
[[maybe_unused]] static void m128_add_dpbusd_epi32(__m128i& acc, __m128i a, __m128i b) {
__m128i product0 = _mm_maddubs_epi16(a, b);
product0 = _mm_madd_epi16(product0, _mm_set1_epi16(1));
acc = _mm_add_epi32(acc, product0);
}
#endif
#if defined(USE_NEON_DOTPROD)
[[maybe_unused]] static void
dotprod_m128_add_dpbusd_epi32(int32x4_t& acc, int8x16_t a, int8x16_t b) {
acc = vdotq_s32(acc, a, b);
}
#endif
#if defined(USE_NEON)
[[maybe_unused]] static int neon_m128_reduce_add_epi32(int32x4_t s) {
#if USE_NEON >= 8
return vaddvq_s32(s);
#else
return s[0] + s[1] + s[2] + s[3];
#endif
}
[[maybe_unused]] static int neon_m128_hadd(int32x4_t sum, int bias) {
return neon_m128_reduce_add_epi32(sum) + bias;
}
#endif
#if USE_NEON >= 8
[[maybe_unused]] static void neon_m128_add_dpbusd_epi32(int32x4_t& acc, int8x16_t a, int8x16_t b) {
int16x8_t product0 = vmull_s8(vget_low_s8(a), vget_low_s8(b));
int16x8_t product1 = vmull_high_s8(a, b);
int16x8_t sum = vpaddq_s16(product0, product1);
acc = vpadalq_s16(acc, sum);
}
#endif
}
#endif // STOCKFISH_SIMD_H_INCLUDED
| 3,874
|
C++
|
.h
| 99
| 35.878788
| 99
| 0.677807
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,080
|
half_ka_v2_hm.h
|
official-stockfish_Stockfish/src/nnue/features/half_ka_v2_hm.h
|
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//Definition of input features HalfKP of NNUE evaluation function
#ifndef NNUE_FEATURES_HALF_KA_V2_HM_H_INCLUDED
#define NNUE_FEATURES_HALF_KA_V2_HM_H_INCLUDED
#include <cstdint>
#include "../../misc.h"
#include "../../types.h"
#include "../nnue_common.h"
namespace Stockfish {
struct StateInfo;
class Position;
}
namespace Stockfish::Eval::NNUE::Features {
// Feature HalfKAv2_hm: Combination of the position of own king and the
// position of pieces. Position mirrored such that king is always on e..h files.
class HalfKAv2_hm {
// Unique number for each piece type on each square
enum {
PS_NONE = 0,
PS_W_PAWN = 0,
PS_B_PAWN = 1 * SQUARE_NB,
PS_W_KNIGHT = 2 * SQUARE_NB,
PS_B_KNIGHT = 3 * SQUARE_NB,
PS_W_BISHOP = 4 * SQUARE_NB,
PS_B_BISHOP = 5 * SQUARE_NB,
PS_W_ROOK = 6 * SQUARE_NB,
PS_B_ROOK = 7 * SQUARE_NB,
PS_W_QUEEN = 8 * SQUARE_NB,
PS_B_QUEEN = 9 * SQUARE_NB,
PS_KING = 10 * SQUARE_NB,
PS_NB = 11 * SQUARE_NB
};
static constexpr IndexType PieceSquareIndex[COLOR_NB][PIECE_NB] = {
// Convention: W - us, B - them
// Viewed from other side, W and B are reversed
{PS_NONE, PS_W_PAWN, PS_W_KNIGHT, PS_W_BISHOP, PS_W_ROOK, PS_W_QUEEN, PS_KING, PS_NONE,
PS_NONE, PS_B_PAWN, PS_B_KNIGHT, PS_B_BISHOP, PS_B_ROOK, PS_B_QUEEN, PS_KING, PS_NONE},
{PS_NONE, PS_B_PAWN, PS_B_KNIGHT, PS_B_BISHOP, PS_B_ROOK, PS_B_QUEEN, PS_KING, PS_NONE,
PS_NONE, PS_W_PAWN, PS_W_KNIGHT, PS_W_BISHOP, PS_W_ROOK, PS_W_QUEEN, PS_KING, PS_NONE}};
public:
// Feature name
static constexpr const char* Name = "HalfKAv2_hm(Friend)";
// Hash value embedded in the evaluation file
static constexpr std::uint32_t HashValue = 0x7f234cb8u;
// Number of feature dimensions
static constexpr IndexType Dimensions =
static_cast<IndexType>(SQUARE_NB) * static_cast<IndexType>(PS_NB) / 2;
#define B(v) (v * PS_NB)
// clang-format off
static constexpr int KingBuckets[COLOR_NB][SQUARE_NB] = {
{ B(28), B(29), B(30), B(31), B(31), B(30), B(29), B(28),
B(24), B(25), B(26), B(27), B(27), B(26), B(25), B(24),
B(20), B(21), B(22), B(23), B(23), B(22), B(21), B(20),
B(16), B(17), B(18), B(19), B(19), B(18), B(17), B(16),
B(12), B(13), B(14), B(15), B(15), B(14), B(13), B(12),
B( 8), B( 9), B(10), B(11), B(11), B(10), B( 9), B( 8),
B( 4), B( 5), B( 6), B( 7), B( 7), B( 6), B( 5), B( 4),
B( 0), B( 1), B( 2), B( 3), B( 3), B( 2), B( 1), B( 0) },
{ B( 0), B( 1), B( 2), B( 3), B( 3), B( 2), B( 1), B( 0),
B( 4), B( 5), B( 6), B( 7), B( 7), B( 6), B( 5), B( 4),
B( 8), B( 9), B(10), B(11), B(11), B(10), B( 9), B( 8),
B(12), B(13), B(14), B(15), B(15), B(14), B(13), B(12),
B(16), B(17), B(18), B(19), B(19), B(18), B(17), B(16),
B(20), B(21), B(22), B(23), B(23), B(22), B(21), B(20),
B(24), B(25), B(26), B(27), B(27), B(26), B(25), B(24),
B(28), B(29), B(30), B(31), B(31), B(30), B(29), B(28) }
};
// clang-format on
#undef B
// clang-format off
// Orient a square according to perspective (rotates by 180 for black)
static constexpr int OrientTBL[COLOR_NB][SQUARE_NB] = {
{ SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1 },
{ SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8 }
};
// clang-format on
// Maximum number of simultaneously active features.
static constexpr IndexType MaxActiveDimensions = 32;
using IndexList = ValueList<IndexType, MaxActiveDimensions>;
// Index of a feature for a given king position and another piece on some square
template<Color Perspective>
static IndexType make_index(Square s, Piece pc, Square ksq);
// Get a list of indices for active features
template<Color Perspective>
static void append_active_indices(const Position& pos, IndexList& active);
// Get a list of indices for recently changed features
template<Color Perspective>
static void
append_changed_indices(Square ksq, const DirtyPiece& dp, IndexList& removed, IndexList& added);
// Returns the cost of updating one perspective, the most costly one.
// Assumes no refresh needed.
static int update_cost(const StateInfo* st);
static int refresh_cost(const Position& pos);
// Returns whether the change stored in this StateInfo means
// that a full accumulator refresh is required.
static bool requires_refresh(const StateInfo* st, Color perspective);
};
} // namespace Stockfish::Eval::NNUE::Features
#endif // #ifndef NNUE_FEATURES_HALF_KA_V2_HM_H_INCLUDED
| 6,416
|
C++
|
.h
| 126
| 45.134921
| 99
| 0.606447
|
official-stockfish/Stockfish
| 11,319
| 2,251
| 41
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,097
|
alpr_c.cpp
|
openalpr_openalpr/src/openalpr/alpr_c.cpp
|
/*
* Copyright (c) 2016 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "alpr_c.h"
#include <alpr.h>
#include <string.h>
#include <vector>
#include <stdlib.h>
OPENALPRC_DLL_EXPORT OPENALPR* openalpr_init(const char* country, const char* configFile, const char* runtimeDir)
{
alpr::Alpr* alpr_inst = new alpr::Alpr(country, configFile, runtimeDir);
return (OPENALPR*) alpr_inst;
}
OPENALPRC_DLL_EXPORT int openalpr_is_loaded(OPENALPR* instance)
{
return (int) ((alpr::Alpr*) instance)->isLoaded();
}
// Set the country used for plate recognition
OPENALPRC_DLL_EXPORT void openalpr_set_country(OPENALPR* instance, const char* country)
{
((alpr::Alpr*) instance)->setCountry(country);
}
// Update the prewarp setting without reloading the library
OPENALPRC_DLL_EXPORT void openalpr_set_prewarp(OPENALPR* instance, const char* prewarp_config)
{
((alpr::Alpr*) instance)->setPrewarp(prewarp_config);
}
// Update the detection mask without reloading the library
OPENALPRC_DLL_EXPORT void openalpr_set_mask(OPENALPR* instance, unsigned char* pixelData, int bytesPerPixel, int imgWidth, int imgHeight)
{
((alpr::Alpr*) instance)->setMask(pixelData, bytesPerPixel, imgWidth, imgHeight);
}
// Enable/disable region detection. Pass a 0 or 1
OPENALPRC_DLL_EXPORT void openalpr_set_detect_region(OPENALPR* instance, int detectRegion)
{
((alpr::Alpr*) instance)->setDetectRegion(detectRegion);
}
OPENALPRC_DLL_EXPORT void openalpr_set_topn(OPENALPR* instance, int topN)
{
((alpr::Alpr*) instance)->setTopN(topN);
}
OPENALPRC_DLL_EXPORT void openalpr_set_default_region(OPENALPR* instance, const char* region)
{
((alpr::Alpr*) instance)->setDefaultRegion(region);
}
// Recognizes the provided image and responds with JSON.
// Caller must call free() on the returned object
OPENALPRC_DLL_EXPORT char* openalpr_recognize_rawimage(OPENALPR* instance, unsigned char* pixelData, int bytesPerPixel, int imgWidth, int imgHeight, AlprCRegionOfInterest roi)
{
std::vector<alpr::AlprRegionOfInterest> rois;
alpr::AlprRegionOfInterest cpproi(roi.x, roi.y, roi.width, roi.height);
rois.push_back(cpproi);
alpr::AlprResults results = ((alpr::Alpr*) instance)->recognize(pixelData,bytesPerPixel, imgWidth, imgHeight, rois);
std::string json_string = alpr::Alpr::toJson(results);
char* result_obj = strdup(json_string.c_str());
return result_obj;
}
OPENALPRC_DLL_EXPORT char* openalpr_recognize_encodedimage(OPENALPR* instance, unsigned char* bytes, long long length, AlprCRegionOfInterest roi)
{
std::vector<alpr::AlprRegionOfInterest> rois;
alpr::AlprRegionOfInterest cpproi(roi.x, roi.y, roi.width, roi.height);
rois.push_back(cpproi);
std::vector<char> byte_vector(length);
memcpy(&byte_vector[0], bytes, length*sizeof(char));
alpr::AlprResults results = ((alpr::Alpr*) instance)->recognize(byte_vector, rois);
std::string json_string = alpr::Alpr::toJson(results);
char* result_obj = strdup(json_string.c_str());
return result_obj;
}
OPENALPRC_DLL_EXPORT void openalpr_free_response_string(char* response)
{
free(response);
}
OPENALPRC_DLL_EXPORT void openalpr_cleanup(OPENALPR* instance)
{
delete ((alpr::Alpr*) instance);
}
| 3,910
|
C++
|
.cpp
| 92
| 40.195652
| 175
| 0.767374
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
12,109
|
detectorcuda.cpp
|
openalpr_openalpr/src/openalpr/detection/detectorcuda.cpp
|
/*
* Copyright (c) 2013 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "detectorcuda.h"
#ifdef COMPILE_GPU
using namespace cv;
using namespace std;
namespace alpr
{
DetectorCUDA::DetectorCUDA(Config* config, PreWarp* prewarp) : Detector(config, prewarp) {
#if OPENCV_MAJOR_VERSION == 2
if( this->cuda_cascade.load( get_detector_file() ) )
#else
cuda_cascade = cuda::CascadeClassifier::create(get_detector_file());
if( !this->cuda_cascade.get()->empty() )
#endif
{
this->loaded = true;
printf("--(!)Loaded CUDA classifier\n");
}
else
{
this->loaded = false;
printf("--(!)Error loading CPU classifier %s\n", get_detector_file().c_str());
}
}
DetectorCUDA::~DetectorCUDA() {
}
vector<Rect> DetectorCUDA::find_plates(Mat frame, cv::Size min_plate_size, cv::Size max_plate_size)
{
//-- Detect plates
vector<Rect> plates;
timespec startTime;
getTimeMonotonic(&startTime);
#if OPENCV_MAJOR_VERSION == 2
gpu::GpuMat cudaFrame, plateregions_buffer;
#else
cuda::GpuMat cudaFrame, plateregions_buffer;
#endif
Mat plateregions_downloaded;
cudaFrame.upload(frame);
#if OPENCV_MAJOR_VERSION == 2
int numdetected = cuda_cascade.detectMultiScale(cudaFrame, plateregions_buffer,
(double) config->detection_iteration_increase, config->detectionStrictness,
min_plate_size);
#else
cuda_cascade->setScaleFactor((double) config->detection_iteration_increase);
cuda_cascade->setMinNeighbors(config->detectionStrictness);
cuda_cascade->setMinObjectSize(min_plate_size);
cuda_cascade->detectMultiScale(cudaFrame,
plateregions_buffer);
std::vector<Rect> detected;
cuda_cascade->convert(plateregions_buffer, detected);
int numdetected = detected.size();
#endif
plateregions_buffer.colRange(0, numdetected).download(plateregions_downloaded);
for (int i = 0; i < numdetected; ++i)
{
plates.push_back(plateregions_downloaded.ptr<cv::Rect>()[i]);
}
if (config->debugTiming)
{
timespec endTime;
getTimeMonotonic(&endTime);
cout << "LBP Time: " << diffclock(startTime, endTime) << "ms." << endl;
}
return plates;
}
}
#endif
| 2,935
|
C++
|
.cpp
| 85
| 30.529412
| 101
| 0.717175
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
12,124
|
ocr.cpp
|
openalpr_openalpr/src/openalpr/ocr/ocr.cpp
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ocr.h"
namespace alpr
{
OCR::OCR(Config* config) : postProcessor(config) {
this->config = config;
}
OCR::~OCR() {
}
void OCR::performOCR(PipelineData* pipeline_data)
{
timespec startTime;
getTimeMonotonic(&startTime);
segment(pipeline_data);
postProcessor.clear();
int absolute_charpos = 0;
for (unsigned int line_idx = 0; line_idx < pipeline_data->textLines.size(); line_idx++)
{
std::vector<OcrChar> chars = recognize_line(line_idx, pipeline_data);
for (uint32_t i = 0; i < chars.size(); i++)
{
// For multi-line plates, set the character indexes to sequential values based on the line number
int line_ordered_index = (line_idx * config->postProcessMaxCharacters) + chars[i].char_index;
postProcessor.addLetter(chars[i].letter, line_idx, line_ordered_index, chars[i].confidence);
absolute_charpos++;
}
}
if (config->debugTiming)
{
timespec endTime;
getTimeMonotonic(&endTime);
std::cout << "OCR Time: " << diffclock(startTime, endTime) << "ms." << std::endl;
}
}
}
| 1,916
|
C++
|
.cpp
| 52
| 32.230769
| 105
| 0.696937
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
12,140
|
textlinecollection.cpp
|
openalpr_openalpr/src/openalpr/edges/textlinecollection.cpp
|
/*
* File: textlinecollection.cpp
* Author: mhill
*
* Created on October 25, 2014, 4:06 PM
*/
#include "textlinecollection.h"
using namespace cv;
using namespace std;
namespace alpr
{
TextLineCollection::TextLineCollection(std::vector<TextLine> textLines) {
charHeight = 0;
charAngle = 0;
for (unsigned int i = 0; i < textLines.size(); i++)
{
charHeight += textLines[i].lineHeight;
charAngle += textLines[i].angle;
}
charHeight = charHeight / textLines.size();
charAngle = charAngle / textLines.size();
this->topCharArea = textLines[0].charBoxTop;
this->bottomCharArea = textLines[0].charBoxBottom;
for (unsigned int i = 1; i < textLines.size(); i++)
{
if (this->topCharArea.isPointBelowLine(textLines[i].charBoxTop.midpoint()) == false)
this->topCharArea = textLines[i].charBoxTop;
if (this->bottomCharArea.isPointBelowLine(textLines[i].charBoxBottom.midpoint()))
this->bottomCharArea = textLines[i].charBoxBottom;
}
longerSegment = this->bottomCharArea;
shorterSegment = this->topCharArea;
if (this->topCharArea.length > this->bottomCharArea.length)
{
longerSegment = this->topCharArea;
shorterSegment = this->bottomCharArea;
}
findCenterHorizontal();
findCenterVertical();
// Center Vertical Line
}
cv::Mat TextLineCollection::getDebugImage(cv::Size imageSize) {
Mat debugImage = Mat::zeros(imageSize, CV_8U);
line(debugImage, this->centerHorizontalLine.p1, this->centerHorizontalLine.p2, Scalar(255,255,255), 2);
line(debugImage, this->centerVerticalLine.p1, this->centerVerticalLine.p2, Scalar(255,255,255), 2);
return debugImage;
}
// Returns 1 for above, 0 for within, and -1 for below
int TextLineCollection::isAboveText(LineSegment line) {
// Test four points (left and right corner of top and bottom line)
Point topLeft = line.closestPointOnSegmentTo(topCharArea.p1);
Point topRight = line.closestPointOnSegmentTo(topCharArea.p2);
bool lineIsBelowTop = topCharArea.isPointBelowLine(topLeft) || topCharArea.isPointBelowLine(topRight);
if (!lineIsBelowTop)
return 1;
Point bottomLeft = line.closestPointOnSegmentTo(bottomCharArea.p1);
Point bottomRight = line.closestPointOnSegmentTo(bottomCharArea.p2);
bool lineIsBelowBottom = bottomCharArea.isPointBelowLine(bottomLeft) &&
bottomCharArea.isPointBelowLine(bottomRight);
if (lineIsBelowBottom)
return -1;
return 0;
}
// Returns 1 for left, 0 for within, and -1 for to the right
int TextLineCollection::isLeftOfText(LineSegment line) {
LineSegment leftSide = LineSegment(bottomCharArea.p1, topCharArea.p1);
Point topLeft = line.closestPointOnSegmentTo(leftSide.p2);
Point bottomLeft = line.closestPointOnSegmentTo(leftSide.p1);
bool lineIsAboveLeft = (!leftSide.isPointBelowLine(topLeft)) && (!leftSide.isPointBelowLine(bottomLeft));
if (lineIsAboveLeft)
return 1;
LineSegment rightSide = LineSegment(bottomCharArea.p2, topCharArea.p2);
Point topRight = line.closestPointOnSegmentTo(rightSide.p2);
Point bottomRight = line.closestPointOnSegmentTo(rightSide.p1);
bool lineIsBelowRight = rightSide.isPointBelowLine(topRight) && rightSide.isPointBelowLine(bottomRight);
if (lineIsBelowRight)
return -1;
return 0;
}
void TextLineCollection::findCenterHorizontal() {
// To find the center horizontal line:
// Find the longer of the lines (if multiline)
// Get the nearest point on the bottom-most line for the
// left and right
Point leftP1 = shorterSegment.closestPointOnSegmentTo(longerSegment.p1);
Point leftP2 = longerSegment.p1;
LineSegment left = LineSegment(leftP1, leftP2);
Point leftMidpoint = left.midpoint();
Point rightP1 = shorterSegment.closestPointOnSegmentTo(longerSegment.p2);
Point rightP2 = longerSegment.p2;
LineSegment right = LineSegment(rightP1, rightP2);
Point rightMidpoint = right.midpoint();
this->centerHorizontalLine = LineSegment(leftMidpoint, rightMidpoint);
}
void TextLineCollection::findCenterVertical() {
// To find the center vertical line:
// Choose the longest line (if multiline)
// Get the midpoint
// Draw a line up/down using the closest point on the bottom line
Point p1 = longerSegment.midpoint();
Point p2 = shorterSegment.closestPointOnSegmentTo(p1);
// Draw bottom to top
if (p1.y < p2.y)
this->centerVerticalLine = LineSegment(p1, p2);
else
this->centerVerticalLine = LineSegment(p2, p1);
}
}
| 4,675
|
C++
|
.cpp
| 108
| 37.87037
| 109
| 0.729107
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| true
| true
| true
| false
|
12,211
|
safequeue.h
|
openalpr_openalpr/src/inc/safequeue.h
|
#ifndef SAFE_QUEUE_H_
#define SAFE_QUEUE_H_
#include <queue>
#include "support/tinythread.h"
template <typename T>
class SafeQueue
{
public:
T pop()
{
tthread::lock_guard<tthread::mutex> mlock(_mutex);
while (_queue.empty()) {
_cond.wait(_mutex);
}
T val = _queue.front();
_queue.pop();
return val;
}
void push(const T& item)
{
tthread::lock_guard<tthread::mutex> mlock(_mutex);
_queue.push(item);
_cond.notify_one();
}
bool empty()
{
return _queue.empty();
}
private:
std::queue<T> _queue;
tthread::mutex _mutex;
tthread::condition_variable _cond;
};
#endif
| 806
|
C++
|
.h
| 34
| 15.441176
| 62
| 0.502611
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,220
|
constants.h
|
openalpr_openalpr/src/openalpr/constants.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_CONSTANTS_H
#define OPENALPR_CONSTANTS_H
#define RUNTIME_DIR "/runtime_data"
#define CONFIG_FILE "/openalpr.conf"
#define KEYPOINTS_DIR "/keypoints"
#define CASCADE_DIR "/region/"
#define POSTPROCESS_DIR "/postprocess"
#define DEFAULT_SHARE_DIR INSTALL_PREFIX "/share/openalpr"
#define DEFAULT_RUNTIME_DATA_DIR DEFAULT_SHARE_DIR "/runtime_data"
#define CONFIG_FILE_TEMPLATE_LOCATION DEFAULT_SHARE_DIR "/config/openalpr.defaults.conf"
#ifndef DEFAULT_CONFIG_FILE
#define DEFAULT_CONFIG_FILE "/etc/openalpr/openalpr.conf"
#endif
#define ENV_VARIABLE_CONFIG_FILE "OPENALPR_CONFIG_FILE"
#endif // OPENALPR_CONSTANTS_H
| 1,423
|
C++
|
.h
| 33
| 41.363636
| 89
| 0.774403
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
12,223
|
alpr_c.h
|
openalpr_openalpr/src/openalpr/alpr_c.h
|
/*
* Copyright (c) 2016 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ALPR_C_H
#define ALPR_C_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef WIN32
#define OPENALPRC_DLL_EXPORT __declspec( dllexport )
#else
#define OPENALPRC_DLL_EXPORT
#endif
typedef void OPENALPR;
struct AlprCRegionOfInterest
{
int x;
int y;
int width;
int height;
};
// Initializes the openALPR library and returns a pointer to the OpenALPR instance
OPENALPR* openalpr_init(const char* country, const char* configFile, const char* runtimeDir);
// Returns 1 if the library was loaded successfully, 0 otherwise
int openalpr_is_loaded(OPENALPR* instance);
// Set the country used for plate recognition
void openalpr_set_country(OPENALPR* instance, const char* country);
// Update the prewarp setting without reloading the library
void openalpr_set_prewarp(OPENALPR* instance, const char* prewarp_config);
// Update the detection mask without reloading the library
void openalpr_set_mask(OPENALPR* instance, unsigned char* pixelData, int bytesPerPixel, int imgWidth, int imgHeight);
// Enable/disable region detection. Pass a 0 or 1
void openalpr_set_detect_region(OPENALPR* instance, int detectRegion);
void openalpr_set_topn(OPENALPR* instance, int topN);
void openalpr_set_default_region(OPENALPR* instance, const char* region);
// Recognizes the provided image and responds with JSON.
// Image is expected to be raw pixel data (BGR, 3 channels)
// Caller must call free() on the returned object
char* openalpr_recognize_rawimage(OPENALPR* instance, unsigned char* pixelData, int bytesPerPixel, int imgWidth, int imgHeight, struct AlprCRegionOfInterest roi);
// Recognizes the encoded (e.g., JPEG, PNG) image. bytes are the raw bytes for the image data.
char* openalpr_recognize_encodedimage(OPENALPR* instance, unsigned char* bytes, long long length, struct AlprCRegionOfInterest roi);
// Frees a char* response that was provided from a recognition request.
// This is required for interoperating with managed languages (e.g., C#) that can't free the memory themselves
void openalpr_free_response_string(char* response);
// Free the memory for the OpenALPR instance created with openalpr_init
void openalpr_cleanup(OPENALPR* instance);
#ifdef __cplusplus
}
#endif
#endif /* ALPR_C_H */
| 3,002
|
C++
|
.h
| 65
| 44.338462
| 162
| 0.785714
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,234
|
detectorcpu.h
|
openalpr_openalpr/src/openalpr/detection/detectorcpu.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTORCPU_H
#define OPENALPR_DETECTORCPU_H
#include <vector>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#include "detector.h"
namespace alpr
{
class DetectorCPU : public Detector {
public:
DetectorCPU(Config* config, PreWarp* prewarp);
virtual ~DetectorCPU();
std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);
private:
cv::CascadeClassifier plate_cascade;
};
}
#endif /* OPENALPR_DETECTORCPU_H */
| 1,385
|
C++
|
.h
| 38
| 33.684211
| 105
| 0.756024
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,235
|
detectorocl.h
|
openalpr_openalpr/src/openalpr/detection/detectorocl.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_DETECTOROPENCL_H
#define OPENALPR_DETECTOROPENCL_H
#include <vector>
#if OPENCV_MAJOR_VERSION == 3
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv2/core/ocl.hpp"
#include "detector.h"
namespace alpr
{
class DetectorOCL : public Detector {
public:
DetectorOCL(Config* config, PreWarp* prewarp);
virtual ~DetectorOCL();
std::vector<cv::Rect> find_plates(cv::Mat frame, cv::Size min_plate_size, cv::Size max_plate_size);
private:
cv::CascadeClassifier plate_cascade;
};
}
#endif
#endif /* OPENALPR_DETECTOROPENCL_H */
| 1,451
|
C++
|
.h
| 41
| 33.04878
| 103
| 0.762007
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,239
|
version.h
|
openalpr_openalpr/src/openalpr/support/version.h
|
#ifndef OPENALPR_VERSION_H
#define OPENALPR_VERSION_H
/*
* return 1 if v1 > v2
* return 0 if v1 = v2
* return -1 if v1 < v2
*/
int cmpVersion(const char *v1, const char *v2);
#endif /* OPENALPR_VERSION_H */
| 216
|
C++
|
.h
| 9
| 22
| 47
| 0.688119
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,243
|
tinydir.h
|
openalpr_openalpr/src/openalpr/support/tinydir.h
|
/*
Copyright (c) 2013, Cong Xu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TINYDIR_H
#define TINYDIR_H
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#pragma warning (disable : 4996)
#else
#include <dirent.h>
#include <sys/stat.h>
#endif
/* types */
#define _TINYDIR_PATH_MAX 4096
#ifdef _MSC_VER
/* extra chars for the "\\*" mask */
#define _TINYDIR_PATH_EXTRA 2
#else
#define _TINYDIR_PATH_EXTRA 0
#endif
#define _TINYDIR_FILENAME_MAX 256
#ifdef _MSC_VER
#define strncasecmp _strnicmp
#endif
#ifdef _MSC_VER
#define _TINYDIR_FUNC static __inline
#else
#define _TINYDIR_FUNC static __inline__
#endif
typedef struct
{
char path[_TINYDIR_PATH_MAX];
char name[_TINYDIR_FILENAME_MAX];
int is_dir;
int is_reg;
#ifdef _MSC_VER
#else
struct stat _s;
#endif
} tinydir_file;
typedef struct
{
char path[_TINYDIR_PATH_MAX];
int has_next;
int n_files;
tinydir_file *_files;
#ifdef _MSC_VER
HANDLE _h;
WIN32_FIND_DATA _f;
#else
DIR *_d;
struct dirent *_e;
#endif
} tinydir_dir;
/* declarations */
_TINYDIR_FUNC
int tinydir_open(tinydir_dir *dir, const char *path);
_TINYDIR_FUNC
int tinydir_open_sorted(tinydir_dir *dir, const char *path);
_TINYDIR_FUNC
void tinydir_close(tinydir_dir *dir);
_TINYDIR_FUNC
int tinydir_next(tinydir_dir *dir);
_TINYDIR_FUNC
int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file);
_TINYDIR_FUNC
int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, int i);
_TINYDIR_FUNC
int tinydir_open_subdir_n(tinydir_dir *dir, int i);
_TINYDIR_FUNC
int _tinydir_file_cmp(const void *a, const void *b);
/* definitions*/
_TINYDIR_FUNC
int tinydir_open(tinydir_dir *dir, const char *path)
{
if (dir == NULL || path == NULL || strlen(path) == 0)
{
errno = EINVAL;
return -1;
}
if (strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX)
{
errno = ENAMETOOLONG;
return -1;
}
/* initialise dir */
dir->_files = NULL;
#ifdef _MSC_VER
dir->_h = INVALID_HANDLE_VALUE;
#else
dir->_d = NULL;
#endif
tinydir_close(dir);
strcpy(dir->path, path);
#ifdef _MSC_VER
strcat(dir->path, "\\*");
dir->_h = FindFirstFile(dir->path, &dir->_f);
dir->path[strlen(dir->path) - 2] = '\0';
if (dir->_h == INVALID_HANDLE_VALUE)
#else
dir->_d = opendir(path);
if (dir->_d == NULL)
#endif
{
errno = ENOENT;
goto bail;
}
/* read first file */
dir->has_next = 1;
#ifndef _MSC_VER
dir->_e = readdir(dir->_d);
if (dir->_e == NULL)
{
dir->has_next = 0;
}
#endif
return 0;
bail:
tinydir_close(dir);
return -1;
}
_TINYDIR_FUNC
int tinydir_open_sorted(tinydir_dir *dir, const char *path)
{
if (tinydir_open(dir, path) == -1)
{
return -1;
}
dir->n_files = 0;
while (dir->has_next)
{
tinydir_file *p_file;
dir->n_files++;
dir->_files = (tinydir_file *)realloc(dir->_files, sizeof(tinydir_file)*dir->n_files);
if (dir->_files == NULL)
{
errno = ENOMEM;
goto bail;
}
p_file = &dir->_files[dir->n_files - 1];
if (tinydir_readfile(dir, p_file) == -1)
{
goto bail;
}
if (tinydir_next(dir) == -1)
{
goto bail;
}
}
qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp);
return 0;
bail:
tinydir_close(dir);
return -1;
}
_TINYDIR_FUNC
void tinydir_close(tinydir_dir *dir)
{
if (dir == NULL)
{
return;
}
memset(dir->path, 0, sizeof(dir->path));
dir->has_next = 0;
dir->n_files = -1;
if (dir->_files != NULL)
{
free(dir->_files);
}
dir->_files = NULL;
#ifdef _MSC_VER
if (dir->_h != INVALID_HANDLE_VALUE)
{
FindClose(dir->_h);
}
dir->_h = INVALID_HANDLE_VALUE;
#else
if (dir->_d)
{
closedir(dir->_d);
}
dir->_d = NULL;
dir->_e = NULL;
#endif
}
_TINYDIR_FUNC
int tinydir_next(tinydir_dir *dir)
{
if (dir == NULL)
{
errno = EINVAL;
return -1;
}
if (!dir->has_next)
{
errno = ENOENT;
return -1;
}
#ifdef _MSC_VER
if (FindNextFile(dir->_h, &dir->_f) == 0)
#else
dir->_e = readdir(dir->_d);
if (dir->_e == NULL)
#endif
{
dir->has_next = 0;
#ifdef _MSC_VER
if (GetLastError() != ERROR_SUCCESS &&
GetLastError() != ERROR_NO_MORE_FILES)
{
tinydir_close(dir);
errno = EIO;
return -1;
}
#endif
}
return 0;
}
_TINYDIR_FUNC
int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file)
{
if (dir == NULL || file == NULL)
{
errno = EINVAL;
return -1;
}
#ifdef _MSC_VER
if (dir->_h == INVALID_HANDLE_VALUE)
#else
if (dir->_e == NULL)
#endif
{
errno = ENOENT;
return -1;
}
if (strlen(dir->path) +
strlen(
#ifdef _MSC_VER
dir->_f.cFileName
#else
dir->_e->d_name
#endif
) + 1 + _TINYDIR_PATH_EXTRA >=
_TINYDIR_PATH_MAX)
{
/* the path for the file will be too long */
errno = ENAMETOOLONG;
return -1;
}
if (strlen(
#ifdef _MSC_VER
dir->_f.cFileName
#else
dir->_e->d_name
#endif
) >= _TINYDIR_FILENAME_MAX)
{
errno = ENAMETOOLONG;
return -1;
}
strcpy(file->path, dir->path);
strcat(file->path, "/");
strcpy(file->name,
#ifdef _MSC_VER
dir->_f.cFileName
#else
dir->_e->d_name
#endif
);
strcat(file->path, file->name);
#ifndef _MSC_VER
if (stat(file->path, &file->_s) == -1)
{
return -1;
}
#endif
file->is_dir =
#ifdef _MSC_VER
!!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
#else
S_ISDIR(file->_s.st_mode);
#endif
file->is_reg =
#ifdef _MSC_VER
!!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) ||
(
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) &&
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) &&
#ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) &&
#endif
#ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) &&
#endif
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) &&
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY));
#else
S_ISREG(file->_s.st_mode);
#endif
return 0;
}
_TINYDIR_FUNC
int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, int i)
{
if (dir == NULL || file == NULL || i < 0)
{
errno = EINVAL;
return -1;
}
if (i >= dir->n_files)
{
errno = ENOENT;
return -1;
}
memcpy(file, &dir->_files[i], sizeof(tinydir_file));
return 0;
}
_TINYDIR_FUNC
int tinydir_open_subdir_n(tinydir_dir *dir, int i)
{
char path[_TINYDIR_PATH_MAX];
if (dir == NULL || i < 0)
{
errno = EINVAL;
return -1;
}
if (i >= dir->n_files || !dir->_files[i].is_dir)
{
errno = ENOENT;
return -1;
}
strcpy(path, dir->_files[i].path);
tinydir_close(dir);
if (tinydir_open_sorted(dir, path) == -1)
{
return -1;
}
return 0;
}
_TINYDIR_FUNC
int _tinydir_file_cmp(const void *a, const void *b)
{
const tinydir_file *fa = (const tinydir_file *)a;
const tinydir_file *fb = (const tinydir_file *)b;
if (fa->is_dir != fb->is_dir)
{
return -(fa->is_dir - fb->is_dir);
}
return strncasecmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX);
}
#endif
| 8,501
|
C++
|
.h
| 374
| 19.836898
| 90
| 0.661935
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,262
|
atomicops.h
|
openalpr_openalpr/src/openalpr/support/re2/util/atomicops.h
|
// Copyright 2006-2008 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef RE2_UTIL_ATOMICOPS_H__
#define RE2_UTIL_ATOMICOPS_H__
// The memory ordering constraints resemble the ones in C11.
// RELAXED - no memory ordering, just an atomic operation.
// CONSUME - data-dependent ordering.
// ACQUIRE - prevents memory accesses from hoisting above the operation.
// RELEASE - prevents memory accesses from sinking below the operation.
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#if !defined(OS_NACL) && (__has_builtin(__atomic_load_n) || (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__ >= 40801))
#define ATOMIC_LOAD_RELAXED(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_RELAXED); } while (0)
#define ATOMIC_LOAD_CONSUME(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_CONSUME); } while (0)
#define ATOMIC_LOAD_ACQUIRE(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_ACQUIRE); } while (0)
#define ATOMIC_STORE_RELAXED(p, v) __atomic_store_n((p), (v), __ATOMIC_RELAXED)
#define ATOMIC_STORE_RELEASE(p, v) __atomic_store_n((p), (v), __ATOMIC_RELEASE)
#else // old compiler
#define ATOMIC_LOAD_RELAXED(x, p) do { (x) = *(p); } while (0)
#define ATOMIC_LOAD_CONSUME(x, p) do { (x) = *(p); MaybeReadMemoryBarrier(); } while (0)
#define ATOMIC_LOAD_ACQUIRE(x, p) do { (x) = *(p); ReadMemoryBarrier(); } while (0)
#define ATOMIC_STORE_RELAXED(p, v) do { *(p) = (v); } while (0)
#define ATOMIC_STORE_RELEASE(p, v) do { WriteMemoryBarrier(); *(p) = (v); } while (0)
// WriteMemoryBarrier(), ReadMemoryBarrier() and MaybeReadMemoryBarrier()
// are an implementation detail and must not be used in the rest of the code.
#if defined(__i386__)
static inline void WriteMemoryBarrier() {
int x;
__asm__ __volatile__("xchgl (%0),%0" // The lock prefix is implicit for xchg.
:: "r" (&x));
}
#elif defined(__x86_64__)
// 64-bit implementations of memory barrier can be simpler, because
// "sfence" is guaranteed to exist.
static inline void WriteMemoryBarrier() {
__asm__ __volatile__("sfence" : : : "memory");
}
#elif defined(__ppc__) || defined(__powerpc64__)
static inline void WriteMemoryBarrier() {
__asm__ __volatile__("eieio" : : : "memory");
}
#elif defined(__alpha__)
static inline void WriteMemoryBarrier() {
__asm__ __volatile__("wmb" : : : "memory");
}
#elif defined(__aarch64__)
static inline void WriteMemoryBarrier() {
__asm__ __volatile__("dmb st" : : : "memory");
}
#elif defined(__arm__) && defined(__linux__)
// Linux on ARM puts a suitable memory barrier at a magic address for us to call.
static inline void WriteMemoryBarrier() {
((void(*)(void))0xffff0fa0)();
}
#elif defined(__windows__)
// Windows
inline void WriteMemoryBarrier() {
LONG x;
::InterlockedExchange(&x, 0);
}
#elif defined(OS_NACL)
// Native Client
inline void WriteMemoryBarrier() {
__sync_synchronize();
}
#elif defined(__mips__)
inline void WriteMemoryBarrier() {
__asm__ __volatile__("sync" : : : "memory");
}
#else
#include "util/mutex.h"
static inline void WriteMemoryBarrier() {
// Slight overkill, but good enough:
// any mutex implementation must have
// a read barrier after the lock operation and
// a write barrier before the unlock operation.
//
// It may be worthwhile to write architecture-specific
// barriers for the common platforms, as above, but
// this is a correct fallback.
re2::Mutex mu;
re2::MutexLock l(&mu);
}
#endif
// Alpha has very weak memory ordering. If relying on WriteBarriers, one must
// use read barriers for the readers too.
#if defined(__alpha__)
static inline void MaybeReadMemoryBarrier() {
__asm__ __volatile__("mb" : : : "memory");
}
#else
static inline void MaybeReadMemoryBarrier() {}
#endif // __alpha__
// Read barrier for various targets.
#if defined(__aarch64__)
static inline void ReadMemoryBarrier() {
__asm__ __volatile__("dmb ld" : : : "memory");
}
#elif defined(__alpha__)
static inline void ReadMemoryBarrier() {
__asm__ __volatile__("mb" : : : "memory");
}
#elif defined(__mips__)
inline void ReadMemoryBarrier() {
__asm__ __volatile__("sync" : : : "memory");
}
#else
static inline void ReadMemoryBarrier() {}
#endif
#endif // old compiler
#ifndef NO_THREAD_SAFETY_ANALYSIS
#define NO_THREAD_SAFETY_ANALYSIS
#endif
#endif // RE2_UTIL_ATOMICOPS_H__
| 4,421
|
C++
|
.h
| 116
| 36.068966
| 129
| 0.684755
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
12,269
|
valgrind.h
|
openalpr_openalpr/src/openalpr/support/re2/util/valgrind.h
|
/* -*- c -*-
----------------------------------------------------------------
Notice that the following BSD-style license applies to this one
file (valgrind.h) only. The rest of Valgrind is licensed under the
terms of the GNU General Public License, version 2, unless
otherwise indicated. See the COPYING file in the source
distribution for details.
----------------------------------------------------------------
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2000-2009 Julian Seward. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------
Notice that the above BSD-style license applies to this one file
(valgrind.h) only. The entire rest of Valgrind is licensed under
the terms of the GNU General Public License, version 2. See the
COPYING file in the source distribution for details.
----------------------------------------------------------------
*/
/* This file is for inclusion into client (your!) code.
You can use these macros to manipulate and query Valgrind's
execution inside your own programs.
The resulting executables will still run without Valgrind, just a
little bit more slowly than they otherwise would, but otherwise
unchanged. When not running on valgrind, each client request
consumes very few (eg. 7) instructions, so the resulting performance
loss is negligible unless you plan to execute client requests
millions of times per second. Nevertheless, if that is still a
problem, you can compile with the NVALGRIND symbol defined (gcc
-DNVALGRIND) so that client requests are not even compiled in. */
#ifndef __VALGRIND_H
#define __VALGRIND_H
#include <stdarg.h>
/* Nb: this file might be included in a file compiled with -ansi. So
we can't use C++ style "//" comments nor the "asm" keyword (instead
use "__asm__"). */
/* Derive some tags indicating what the target platform is. Note
that in this file we're using the compiler's CPP symbols for
identifying architectures, which are different to the ones we use
within the rest of Valgrind. Note, __powerpc__ is active for both
32 and 64-bit PPC, whereas __powerpc64__ is only active for the
latter (on Linux, that is).
Misc note: how to find out what's predefined in gcc by default:
gcc -Wp,-dM somefile.c
*/
#undef PLAT_ppc64_aix5
#undef PLAT_ppc32_aix5
#undef PLAT_x86_darwin
#undef PLAT_amd64_darwin
#undef PLAT_x86_linux
#undef PLAT_amd64_linux
#undef PLAT_ppc32_linux
#undef PLAT_ppc64_linux
#undef PLAT_arm_linux
#if defined(_AIX) && defined(__64BIT__)
# define PLAT_ppc64_aix5 1
#elif defined(_AIX) && !defined(__64BIT__)
# define PLAT_ppc32_aix5 1
#elif defined(__APPLE__) && defined(__i386__)
# define PLAT_x86_darwin 1
#elif defined(__APPLE__) && defined(__x86_64__)
# define PLAT_amd64_darwin 1
#elif defined(__linux__) && defined(__i386__)
# define PLAT_x86_linux 1
#elif defined(__linux__) && defined(__x86_64__)
# define PLAT_amd64_linux 1
#elif defined(__linux__) && defined(__powerpc__) && !defined(__powerpc64__)
# define PLAT_ppc32_linux 1
#elif defined(__linux__) && defined(__powerpc__) && defined(__powerpc64__)
# define PLAT_ppc64_linux 1
#elif defined(__linux__) && defined(__arm__)
# define PLAT_arm_linux 1
#else
/* If we're not compiling for our target platform, don't generate
any inline asms. */
# if !defined(NVALGRIND)
# define NVALGRIND 1
# endif
#endif
/* ------------------------------------------------------------------ */
/* ARCHITECTURE SPECIFICS for SPECIAL INSTRUCTIONS. There is nothing */
/* in here of use to end-users -- skip to the next section. */
/* ------------------------------------------------------------------ */
#if defined(NVALGRIND)
/* Define NVALGRIND to completely remove the Valgrind magic sequence
from the compiled code (analogous to NDEBUG's effects on
assert()) */
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
{ \
(_zzq_rlval) = (_zzq_default); \
}
#else /* ! NVALGRIND */
/* The following defines the magic code sequences which the JITter
spots and handles magically. Don't look too closely at them as
they will rot your brain.
The assembly code sequences for all architectures is in this one
file. This is because this file must be stand-alone, and we don't
want to have multiple files.
For VALGRIND_DO_CLIENT_REQUEST, we must ensure that the default
value gets put in the return slot, so that everything works when
this is executed not under Valgrind. Args are passed in a memory
block, and so there's no intrinsic limit to the number that could
be passed, but it's currently five.
The macro args are:
_zzq_rlval result lvalue
_zzq_default default value (result returned when running on real CPU)
_zzq_request request code
_zzq_arg1..5 request params
The other two macros are used to support function wrapping, and are
a lot simpler. VALGRIND_GET_NR_CONTEXT returns the value of the
guest's NRADDR pseudo-register and whatever other information is
needed to safely run the call original from the wrapper: on
ppc64-linux, the R2 value at the divert point is also needed. This
information is abstracted into a user-visible type, OrigFn.
VALGRIND_CALL_NOREDIR_* behaves the same as the following on the
guest, but guarantees that the branch instruction will not be
redirected: x86: call *%eax, amd64: call *%rax, ppc32/ppc64:
branch-and-link-to-r11. VALGRIND_CALL_NOREDIR is just text, not a
complete inline asm, since it needs to be combined with more magic
inline asm stuff to be useful.
*/
/* ------------------------- x86-{linux,darwin} ---------------- */
#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin)
typedef
struct {
unsigned int nraddr; /* where's the code? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"roll $3, %%edi ; roll $13, %%edi\n\t" \
"roll $29, %%edi ; roll $19, %%edi\n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
{ volatile unsigned int _zzq_args[6]; \
volatile unsigned int _zzq_result; \
_zzq_args[0] = (unsigned int)(_zzq_request); \
_zzq_args[1] = (unsigned int)(_zzq_arg1); \
_zzq_args[2] = (unsigned int)(_zzq_arg2); \
_zzq_args[3] = (unsigned int)(_zzq_arg3); \
_zzq_args[4] = (unsigned int)(_zzq_arg4); \
_zzq_args[5] = (unsigned int)(_zzq_arg5); \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %EDX = client_request ( %EAX ) */ \
"xchgl %%ebx,%%ebx" \
: "=d" (_zzq_result) \
: "a" (&_zzq_args[0]), "0" (_zzq_default) \
: "cc", "memory" \
); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
volatile unsigned int __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %EAX = guest_NRADDR */ \
"xchgl %%ecx,%%ecx" \
: "=a" (__addr) \
: \
: "cc", "memory" \
); \
_zzq_orig->nraddr = __addr; \
}
#define VALGRIND_CALL_NOREDIR_EAX \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* call-noredir *%EAX */ \
"xchgl %%edx,%%edx\n\t"
#endif /* PLAT_x86_linux || PLAT_x86_darwin */
/* ------------------------ amd64-{linux,darwin} --------------- */
#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin)
typedef
struct {
unsigned long long int nraddr; /* where's the code? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"rolq $3, %%rdi ; rolq $13, %%rdi\n\t" \
"rolq $61, %%rdi ; rolq $51, %%rdi\n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
{ volatile unsigned long long int _zzq_args[6]; \
volatile unsigned long long int _zzq_result; \
_zzq_args[0] = (unsigned long long int)(_zzq_request); \
_zzq_args[1] = (unsigned long long int)(_zzq_arg1); \
_zzq_args[2] = (unsigned long long int)(_zzq_arg2); \
_zzq_args[3] = (unsigned long long int)(_zzq_arg3); \
_zzq_args[4] = (unsigned long long int)(_zzq_arg4); \
_zzq_args[5] = (unsigned long long int)(_zzq_arg5); \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %RDX = client_request ( %RAX ) */ \
"xchgq %%rbx,%%rbx" \
: "=d" (_zzq_result) \
: "a" (&_zzq_args[0]), "0" (_zzq_default) \
: "cc", "memory" \
); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
volatile unsigned long long int __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %RAX = guest_NRADDR */ \
"xchgq %%rcx,%%rcx" \
: "=a" (__addr) \
: \
: "cc", "memory" \
); \
_zzq_orig->nraddr = __addr; \
}
#define VALGRIND_CALL_NOREDIR_RAX \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* call-noredir *%RAX */ \
"xchgq %%rdx,%%rdx\n\t"
#endif /* PLAT_amd64_linux || PLAT_amd64_darwin */
/* ------------------------ ppc32-linux ------------------------ */
#if defined(PLAT_ppc32_linux)
typedef
struct {
unsigned int nraddr; /* where's the code? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \
"rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
\
{ unsigned int _zzq_args[6]; \
unsigned int _zzq_result; \
unsigned int* _zzq_ptr; \
_zzq_args[0] = (unsigned int)(_zzq_request); \
_zzq_args[1] = (unsigned int)(_zzq_arg1); \
_zzq_args[2] = (unsigned int)(_zzq_arg2); \
_zzq_args[3] = (unsigned int)(_zzq_arg3); \
_zzq_args[4] = (unsigned int)(_zzq_arg4); \
_zzq_args[5] = (unsigned int)(_zzq_arg5); \
_zzq_ptr = _zzq_args; \
__asm__ volatile("mr 3,%1\n\t" /*default*/ \
"mr 4,%2\n\t" /*ptr*/ \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = client_request ( %R4 ) */ \
"or 1,1,1\n\t" \
"mr %0,3" /*result*/ \
: "=b" (_zzq_result) \
: "b" (_zzq_default), "b" (_zzq_ptr) \
: "cc", "memory", "r3", "r4"); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
unsigned int __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR */ \
"or 2,2,2\n\t" \
"mr %0,3" \
: "=b" (__addr) \
: \
: "cc", "memory", "r3" \
); \
_zzq_orig->nraddr = __addr; \
}
#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* branch-and-link-to-noredir *%R11 */ \
"or 3,3,3\n\t"
#endif /* PLAT_ppc32_linux */
/* ------------------------ ppc64-linux ------------------------ */
#if defined(PLAT_ppc64_linux)
typedef
struct {
unsigned long long int nraddr; /* where's the code? */
unsigned long long int r2; /* what tocptr do we need? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"rotldi 0,0,3 ; rotldi 0,0,13\n\t" \
"rotldi 0,0,61 ; rotldi 0,0,51\n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
\
{ unsigned long long int _zzq_args[6]; \
register unsigned long long int _zzq_result __asm__("r3"); \
register unsigned long long int* _zzq_ptr __asm__("r4"); \
_zzq_args[0] = (unsigned long long int)(_zzq_request); \
_zzq_args[1] = (unsigned long long int)(_zzq_arg1); \
_zzq_args[2] = (unsigned long long int)(_zzq_arg2); \
_zzq_args[3] = (unsigned long long int)(_zzq_arg3); \
_zzq_args[4] = (unsigned long long int)(_zzq_arg4); \
_zzq_args[5] = (unsigned long long int)(_zzq_arg5); \
_zzq_ptr = _zzq_args; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = client_request ( %R4 ) */ \
"or 1,1,1" \
: "=r" (_zzq_result) \
: "0" (_zzq_default), "r" (_zzq_ptr) \
: "cc", "memory"); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
register unsigned long long int __addr __asm__("r3"); \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR */ \
"or 2,2,2" \
: "=r" (__addr) \
: \
: "cc", "memory" \
); \
_zzq_orig->nraddr = __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR_GPR2 */ \
"or 4,4,4" \
: "=r" (__addr) \
: \
: "cc", "memory" \
); \
_zzq_orig->r2 = __addr; \
}
#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* branch-and-link-to-noredir *%R11 */ \
"or 3,3,3\n\t"
#endif /* PLAT_ppc64_linux */
/* ------------------------- arm-linux ------------------------- */
#if defined(PLAT_arm_linux)
typedef
struct {
unsigned int nraddr; /* where's the code? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"mov r12, r12, ror #3 ; mov r12, r12, ror #13 \n\t" \
"mov r12, r12, ror #29 ; mov r12, r12, ror #19 \n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
\
{ volatile unsigned int _zzq_args[6]; \
volatile unsigned int _zzq_result; \
_zzq_args[0] = (unsigned int)(_zzq_request); \
_zzq_args[1] = (unsigned int)(_zzq_arg1); \
_zzq_args[2] = (unsigned int)(_zzq_arg2); \
_zzq_args[3] = (unsigned int)(_zzq_arg3); \
_zzq_args[4] = (unsigned int)(_zzq_arg4); \
_zzq_args[5] = (unsigned int)(_zzq_arg5); \
__asm__ volatile("mov r3, %1\n\t" /*default*/ \
"mov r4, %2\n\t" /*ptr*/ \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* R3 = client_request ( R4 ) */ \
"orr r10, r10, r10\n\t" \
"mov %0, r3" /*result*/ \
: "=r" (_zzq_result) \
: "r" (_zzq_default), "r" (&_zzq_args[0]) \
: "cc","memory", "r3", "r4"); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
unsigned int __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* R3 = guest_NRADDR */ \
"orr r11, r11, r11\n\t" \
"mov %0, r3" \
: "=r" (__addr) \
: \
: "cc", "memory", "r3" \
); \
_zzq_orig->nraddr = __addr; \
}
#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* branch-and-link-to-noredir *%R4 */ \
"orr r12, r12, r12\n\t"
#endif /* PLAT_arm_linux */
/* ------------------------ ppc32-aix5 ------------------------- */
#if defined(PLAT_ppc32_aix5)
typedef
struct {
unsigned int nraddr; /* where's the code? */
unsigned int r2; /* what tocptr do we need? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \
"rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
\
{ unsigned int _zzq_args[7]; \
register unsigned int _zzq_result; \
register unsigned int* _zzq_ptr; \
_zzq_args[0] = (unsigned int)(_zzq_request); \
_zzq_args[1] = (unsigned int)(_zzq_arg1); \
_zzq_args[2] = (unsigned int)(_zzq_arg2); \
_zzq_args[3] = (unsigned int)(_zzq_arg3); \
_zzq_args[4] = (unsigned int)(_zzq_arg4); \
_zzq_args[5] = (unsigned int)(_zzq_arg5); \
_zzq_args[6] = (unsigned int)(_zzq_default); \
_zzq_ptr = _zzq_args; \
__asm__ volatile("mr 4,%1\n\t" \
"lwz 3, 24(4)\n\t" \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = client_request ( %R4 ) */ \
"or 1,1,1\n\t" \
"mr %0,3" \
: "=b" (_zzq_result) \
: "b" (_zzq_ptr) \
: "r3", "r4", "cc", "memory"); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
register unsigned int __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR */ \
"or 2,2,2\n\t" \
"mr %0,3" \
: "=b" (__addr) \
: \
: "r3", "cc", "memory" \
); \
_zzq_orig->nraddr = __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR_GPR2 */ \
"or 4,4,4\n\t" \
"mr %0,3" \
: "=b" (__addr) \
: \
: "r3", "cc", "memory" \
); \
_zzq_orig->r2 = __addr; \
}
#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* branch-and-link-to-noredir *%R11 */ \
"or 3,3,3\n\t"
#endif /* PLAT_ppc32_aix5 */
/* ------------------------ ppc64-aix5 ------------------------- */
#if defined(PLAT_ppc64_aix5)
typedef
struct {
unsigned long long int nraddr; /* where's the code? */
unsigned long long int r2; /* what tocptr do we need? */
}
OrigFn;
#define __SPECIAL_INSTRUCTION_PREAMBLE \
"rotldi 0,0,3 ; rotldi 0,0,13\n\t" \
"rotldi 0,0,61 ; rotldi 0,0,51\n\t"
#define VALGRIND_DO_CLIENT_REQUEST( \
_zzq_rlval, _zzq_default, _zzq_request, \
_zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
\
{ unsigned long long int _zzq_args[7]; \
register unsigned long long int _zzq_result; \
register unsigned long long int* _zzq_ptr; \
_zzq_args[0] = (unsigned int long long)(_zzq_request); \
_zzq_args[1] = (unsigned int long long)(_zzq_arg1); \
_zzq_args[2] = (unsigned int long long)(_zzq_arg2); \
_zzq_args[3] = (unsigned int long long)(_zzq_arg3); \
_zzq_args[4] = (unsigned int long long)(_zzq_arg4); \
_zzq_args[5] = (unsigned int long long)(_zzq_arg5); \
_zzq_args[6] = (unsigned int long long)(_zzq_default); \
_zzq_ptr = _zzq_args; \
__asm__ volatile("mr 4,%1\n\t" \
"ld 3, 48(4)\n\t" \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = client_request ( %R4 ) */ \
"or 1,1,1\n\t" \
"mr %0,3" \
: "=b" (_zzq_result) \
: "b" (_zzq_ptr) \
: "r3", "r4", "cc", "memory"); \
_zzq_rlval = _zzq_result; \
}
#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
{ volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
register unsigned long long int __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR */ \
"or 2,2,2\n\t" \
"mr %0,3" \
: "=b" (__addr) \
: \
: "r3", "cc", "memory" \
); \
_zzq_orig->nraddr = __addr; \
__asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
/* %R3 = guest_NRADDR_GPR2 */ \
"or 4,4,4\n\t" \
"mr %0,3" \
: "=b" (__addr) \
: \
: "r3", "cc", "memory" \
); \
_zzq_orig->r2 = __addr; \
}
#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
__SPECIAL_INSTRUCTION_PREAMBLE \
/* branch-and-link-to-noredir *%R11 */ \
"or 3,3,3\n\t"
#endif /* PLAT_ppc64_aix5 */
/* Insert assembly code for other platforms here... */
#endif /* NVALGRIND */
/* ------------------------------------------------------------------ */
/* PLATFORM SPECIFICS for FUNCTION WRAPPING. This is all very */
/* ugly. It's the least-worst tradeoff I can think of. */
/* ------------------------------------------------------------------ */
/* This section defines magic (a.k.a appalling-hack) macros for doing
guaranteed-no-redirection macros, so as to get from function
wrappers to the functions they are wrapping. The whole point is to
construct standard call sequences, but to do the call itself with a
special no-redirect call pseudo-instruction that the JIT
understands and handles specially. This section is long and
repetitious, and I can't see a way to make it shorter.
The naming scheme is as follows:
CALL_FN_{W,v}_{v,W,WW,WWW,WWWW,5W,6W,7W,etc}
'W' stands for "word" and 'v' for "void". Hence there are
different macros for calling arity 0, 1, 2, 3, 4, etc, functions,
and for each, the possibility of returning a word-typed result, or
no result.
*/
/* Use these to write the name of your wrapper. NOTE: duplicates
VG_WRAP_FUNCTION_Z{U,Z} in pub_tool_redir.h. */
/* Use an extra level of macroisation so as to ensure the soname/fnname
args are fully macro-expanded before pasting them together. */
#define VG_CONCAT4(_aa,_bb,_cc,_dd) _aa##_bb##_cc##_dd
#define I_WRAP_SONAME_FNNAME_ZU(soname,fnname) \
VG_CONCAT4(_vgwZU_,soname,_,fnname)
#define I_WRAP_SONAME_FNNAME_ZZ(soname,fnname) \
VG_CONCAT4(_vgwZZ_,soname,_,fnname)
/* Use this macro from within a wrapper function to collect the
context (address and possibly other info) of the original function.
Once you have that you can then use it in one of the CALL_FN_
macros. The type of the argument _lval is OrigFn. */
#define VALGRIND_GET_ORIG_FN(_lval) VALGRIND_GET_NR_CONTEXT(_lval)
/* Derivatives of the main macros below, for calling functions
returning void. */
#define CALL_FN_v_v(fnptr) \
do { volatile unsigned long _junk; \
CALL_FN_W_v(_junk,fnptr); } while (0)
#define CALL_FN_v_W(fnptr, arg1) \
do { volatile unsigned long _junk; \
CALL_FN_W_W(_junk,fnptr,arg1); } while (0)
#define CALL_FN_v_WW(fnptr, arg1,arg2) \
do { volatile unsigned long _junk; \
CALL_FN_W_WW(_junk,fnptr,arg1,arg2); } while (0)
#define CALL_FN_v_WWW(fnptr, arg1,arg2,arg3) \
do { volatile unsigned long _junk; \
CALL_FN_W_WWW(_junk,fnptr,arg1,arg2,arg3); } while (0)
#define CALL_FN_v_WWWW(fnptr, arg1,arg2,arg3,arg4) \
do { volatile unsigned long _junk; \
CALL_FN_W_WWWW(_junk,fnptr,arg1,arg2,arg3,arg4); } while (0)
#define CALL_FN_v_5W(fnptr, arg1,arg2,arg3,arg4,arg5) \
do { volatile unsigned long _junk; \
CALL_FN_W_5W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5); } while (0)
#define CALL_FN_v_6W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6) \
do { volatile unsigned long _junk; \
CALL_FN_W_6W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6); } while (0)
#define CALL_FN_v_7W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6,arg7) \
do { volatile unsigned long _junk; \
CALL_FN_W_7W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6,arg7); } while (0)
/* ------------------------- x86-{linux,darwin} ---------------- */
#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin)
/* These regs are trashed by the hidden call. No need to mention eax
as gcc can already see that, plus causes gcc to bomb. */
#define __CALLER_SAVED_REGS /*"eax"*/ "ecx", "edx"
/* These CALL_FN_ macros assume that on x86-linux, sizeof(unsigned
long) == 4. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[1]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[2]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
__asm__ volatile( \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $4, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
__asm__ volatile( \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $8, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[4]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
__asm__ volatile( \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $12, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[5]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
__asm__ volatile( \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $16, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[6]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
__asm__ volatile( \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $20, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[7]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
__asm__ volatile( \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $24, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[8]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
__asm__ volatile( \
"pushl 28(%%eax)\n\t" \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $28, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[9]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
__asm__ volatile( \
"pushl 32(%%eax)\n\t" \
"pushl 28(%%eax)\n\t" \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $32, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[10]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
__asm__ volatile( \
"pushl 36(%%eax)\n\t" \
"pushl 32(%%eax)\n\t" \
"pushl 28(%%eax)\n\t" \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $36, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[11]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
__asm__ volatile( \
"pushl 40(%%eax)\n\t" \
"pushl 36(%%eax)\n\t" \
"pushl 32(%%eax)\n\t" \
"pushl 28(%%eax)\n\t" \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $40, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
arg6,arg7,arg8,arg9,arg10, \
arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[12]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
_argvec[11] = (unsigned long)(arg11); \
__asm__ volatile( \
"pushl 44(%%eax)\n\t" \
"pushl 40(%%eax)\n\t" \
"pushl 36(%%eax)\n\t" \
"pushl 32(%%eax)\n\t" \
"pushl 28(%%eax)\n\t" \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $44, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
arg6,arg7,arg8,arg9,arg10, \
arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[13]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
_argvec[11] = (unsigned long)(arg11); \
_argvec[12] = (unsigned long)(arg12); \
__asm__ volatile( \
"pushl 48(%%eax)\n\t" \
"pushl 44(%%eax)\n\t" \
"pushl 40(%%eax)\n\t" \
"pushl 36(%%eax)\n\t" \
"pushl 32(%%eax)\n\t" \
"pushl 28(%%eax)\n\t" \
"pushl 24(%%eax)\n\t" \
"pushl 20(%%eax)\n\t" \
"pushl 16(%%eax)\n\t" \
"pushl 12(%%eax)\n\t" \
"pushl 8(%%eax)\n\t" \
"pushl 4(%%eax)\n\t" \
"movl (%%eax), %%eax\n\t" /* target->%eax */ \
VALGRIND_CALL_NOREDIR_EAX \
"addl $48, %%esp\n" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_x86_linux || PLAT_x86_darwin */
/* ------------------------ amd64-{linux,darwin} --------------- */
#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin)
/* ARGREGS: rdi rsi rdx rcx r8 r9 (the rest on stack in R-to-L order) */
/* These regs are trashed by the hidden call. */
#define __CALLER_SAVED_REGS /*"rax",*/ "rcx", "rdx", "rsi", \
"rdi", "r8", "r9", "r10", "r11"
/* These CALL_FN_ macros assume that on amd64-linux, sizeof(unsigned
long) == 8. */
/* NB 9 Sept 07. There is a nasty kludge here in all these CALL_FN_
macros. In order not to trash the stack redzone, we need to drop
%rsp by 128 before the hidden call, and restore afterwards. The
nastyness is that it is only by luck that the stack still appears
to be unwindable during the hidden call - since then the behaviour
of any routine using this macro does not match what the CFI data
says. Sigh.
Why is this important? Imagine that a wrapper has a stack
allocated local, and passes to the hidden call, a pointer to it.
Because gcc does not know about the hidden call, it may allocate
that local in the redzone. Unfortunately the hidden call may then
trash it before it comes to use it. So we must step clear of the
redzone, for the duration of the hidden call, to make it safe.
Probably the same problem afflicts the other redzone-style ABIs too
(ppc64-linux, ppc32-aix5, ppc64-aix5); but for those, the stack is
self describing (none of this CFI nonsense) so at least messing
with the stack pointer doesn't give a danger of non-unwindable
stack. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[1]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[2]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[4]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[5]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[6]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[7]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
"addq $128,%%rsp\n\t" \
VALGRIND_CALL_NOREDIR_RAX \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[8]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"pushq 56(%%rax)\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $8, %%rsp\n" \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[9]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"pushq 64(%%rax)\n\t" \
"pushq 56(%%rax)\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $16, %%rsp\n" \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[10]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"pushq 72(%%rax)\n\t" \
"pushq 64(%%rax)\n\t" \
"pushq 56(%%rax)\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $24, %%rsp\n" \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[11]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"pushq 80(%%rax)\n\t" \
"pushq 72(%%rax)\n\t" \
"pushq 64(%%rax)\n\t" \
"pushq 56(%%rax)\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $32, %%rsp\n" \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[12]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
_argvec[11] = (unsigned long)(arg11); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"pushq 88(%%rax)\n\t" \
"pushq 80(%%rax)\n\t" \
"pushq 72(%%rax)\n\t" \
"pushq 64(%%rax)\n\t" \
"pushq 56(%%rax)\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $40, %%rsp\n" \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[13]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
_argvec[11] = (unsigned long)(arg11); \
_argvec[12] = (unsigned long)(arg12); \
__asm__ volatile( \
"subq $128,%%rsp\n\t" \
"pushq 96(%%rax)\n\t" \
"pushq 88(%%rax)\n\t" \
"pushq 80(%%rax)\n\t" \
"pushq 72(%%rax)\n\t" \
"pushq 64(%%rax)\n\t" \
"pushq 56(%%rax)\n\t" \
"movq 48(%%rax), %%r9\n\t" \
"movq 40(%%rax), %%r8\n\t" \
"movq 32(%%rax), %%rcx\n\t" \
"movq 24(%%rax), %%rdx\n\t" \
"movq 16(%%rax), %%rsi\n\t" \
"movq 8(%%rax), %%rdi\n\t" \
"movq (%%rax), %%rax\n\t" /* target->%rax */ \
VALGRIND_CALL_NOREDIR_RAX \
"addq $48, %%rsp\n" \
"addq $128,%%rsp\n\t" \
: /*out*/ "=a" (_res) \
: /*in*/ "a" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_amd64_linux || PLAT_amd64_darwin */
/* ------------------------ ppc32-linux ------------------------ */
#if defined(PLAT_ppc32_linux)
/* This is useful for finding out about the on-stack stuff:
extern int f9 ( int,int,int,int,int,int,int,int,int );
extern int f10 ( int,int,int,int,int,int,int,int,int,int );
extern int f11 ( int,int,int,int,int,int,int,int,int,int,int );
extern int f12 ( int,int,int,int,int,int,int,int,int,int,int,int );
int g9 ( void ) {
return f9(11,22,33,44,55,66,77,88,99);
}
int g10 ( void ) {
return f10(11,22,33,44,55,66,77,88,99,110);
}
int g11 ( void ) {
return f11(11,22,33,44,55,66,77,88,99,110,121);
}
int g12 ( void ) {
return f12(11,22,33,44,55,66,77,88,99,110,121,132);
}
*/
/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
/* These regs are trashed by the hidden call. */
#define __CALLER_SAVED_REGS \
"lr", "ctr", "xer", \
"cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
"r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
"r11", "r12", "r13"
/* These CALL_FN_ macros assume that on ppc32-linux,
sizeof(unsigned long) == 4. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[1]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[2]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[4]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[5]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[6]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[7]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[8]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
_argvec[7] = (unsigned long)arg7; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 9,28(11)\n\t" \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[9]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
_argvec[7] = (unsigned long)arg7; \
_argvec[8] = (unsigned long)arg8; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 9,28(11)\n\t" \
"lwz 10,32(11)\n\t" /* arg8->r10 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[10]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
_argvec[7] = (unsigned long)arg7; \
_argvec[8] = (unsigned long)arg8; \
_argvec[9] = (unsigned long)arg9; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"addi 1,1,-16\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,8(1)\n\t" \
/* args1-8 */ \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 9,28(11)\n\t" \
"lwz 10,32(11)\n\t" /* arg8->r10 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"addi 1,1,16\n\t" \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[11]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
_argvec[7] = (unsigned long)arg7; \
_argvec[8] = (unsigned long)arg8; \
_argvec[9] = (unsigned long)arg9; \
_argvec[10] = (unsigned long)arg10; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"addi 1,1,-16\n\t" \
/* arg10 */ \
"lwz 3,40(11)\n\t" \
"stw 3,12(1)\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,8(1)\n\t" \
/* args1-8 */ \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 9,28(11)\n\t" \
"lwz 10,32(11)\n\t" /* arg8->r10 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"addi 1,1,16\n\t" \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[12]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
_argvec[7] = (unsigned long)arg7; \
_argvec[8] = (unsigned long)arg8; \
_argvec[9] = (unsigned long)arg9; \
_argvec[10] = (unsigned long)arg10; \
_argvec[11] = (unsigned long)arg11; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"addi 1,1,-32\n\t" \
/* arg11 */ \
"lwz 3,44(11)\n\t" \
"stw 3,16(1)\n\t" \
/* arg10 */ \
"lwz 3,40(11)\n\t" \
"stw 3,12(1)\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,8(1)\n\t" \
/* args1-8 */ \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 9,28(11)\n\t" \
"lwz 10,32(11)\n\t" /* arg8->r10 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"addi 1,1,32\n\t" \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[13]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)arg1; \
_argvec[2] = (unsigned long)arg2; \
_argvec[3] = (unsigned long)arg3; \
_argvec[4] = (unsigned long)arg4; \
_argvec[5] = (unsigned long)arg5; \
_argvec[6] = (unsigned long)arg6; \
_argvec[7] = (unsigned long)arg7; \
_argvec[8] = (unsigned long)arg8; \
_argvec[9] = (unsigned long)arg9; \
_argvec[10] = (unsigned long)arg10; \
_argvec[11] = (unsigned long)arg11; \
_argvec[12] = (unsigned long)arg12; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"addi 1,1,-32\n\t" \
/* arg12 */ \
"lwz 3,48(11)\n\t" \
"stw 3,20(1)\n\t" \
/* arg11 */ \
"lwz 3,44(11)\n\t" \
"stw 3,16(1)\n\t" \
/* arg10 */ \
"lwz 3,40(11)\n\t" \
"stw 3,12(1)\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,8(1)\n\t" \
/* args1-8 */ \
"lwz 3,4(11)\n\t" /* arg1->r3 */ \
"lwz 4,8(11)\n\t" \
"lwz 5,12(11)\n\t" \
"lwz 6,16(11)\n\t" /* arg4->r6 */ \
"lwz 7,20(11)\n\t" \
"lwz 8,24(11)\n\t" \
"lwz 9,28(11)\n\t" \
"lwz 10,32(11)\n\t" /* arg8->r10 */ \
"lwz 11,0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"addi 1,1,32\n\t" \
"mr %0,3" \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_ppc32_linux */
/* ------------------------ ppc64-linux ------------------------ */
#if defined(PLAT_ppc64_linux)
/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
/* These regs are trashed by the hidden call. */
#define __CALLER_SAVED_REGS \
"lr", "ctr", "xer", \
"cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
"r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
"r11", "r12", "r13"
/* These CALL_FN_ macros assume that on ppc64-linux, sizeof(unsigned
long) == 8. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+0]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+1]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+2]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+3]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+4]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+5]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+6]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+7]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+8]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)" /* restore tocptr */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+9]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"addi 1,1,-128\n\t" /* expand stack frame */ \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
"addi 1,1,128" /* restore frame */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+10]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"addi 1,1,-128\n\t" /* expand stack frame */ \
/* arg10 */ \
"ld 3,80(11)\n\t" \
"std 3,120(1)\n\t" \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
"addi 1,1,128" /* restore frame */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+11]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
_argvec[2+11] = (unsigned long)arg11; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"addi 1,1,-144\n\t" /* expand stack frame */ \
/* arg11 */ \
"ld 3,88(11)\n\t" \
"std 3,128(1)\n\t" \
/* arg10 */ \
"ld 3,80(11)\n\t" \
"std 3,120(1)\n\t" \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
"addi 1,1,144" /* restore frame */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+12]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
_argvec[2+11] = (unsigned long)arg11; \
_argvec[2+12] = (unsigned long)arg12; \
__asm__ volatile( \
"mr 11,%1\n\t" \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"addi 1,1,-144\n\t" /* expand stack frame */ \
/* arg12 */ \
"ld 3,96(11)\n\t" \
"std 3,136(1)\n\t" \
/* arg11 */ \
"ld 3,88(11)\n\t" \
"std 3,128(1)\n\t" \
/* arg10 */ \
"ld 3,80(11)\n\t" \
"std 3,120(1)\n\t" \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
"addi 1,1,144" /* restore frame */ \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_ppc64_linux */
/* ------------------------- arm-linux ------------------------- */
#if defined(PLAT_arm_linux)
/* These regs are trashed by the hidden call. */
#define __CALLER_SAVED_REGS "r0", "r1", "r2", "r3","r4","r14"
/* These CALL_FN_ macros assume that on arm-linux, sizeof(unsigned
long) == 4. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[1]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"mov %0, r0\n" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[2]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
__asm__ volatile( \
"ldr r0, [%1, #4] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"mov %0, r0\n" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
__asm__ volatile( \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"mov %0, r0\n" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[4]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
__asm__ volatile( \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"mov %0, r0\n" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[5]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
__asm__ volatile( \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[6]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
__asm__ volatile( \
"ldr r0, [%1, #20] \n\t" \
"push {r0} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #4 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[7]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
__asm__ volatile( \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"push {r0, r1} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #8 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[8]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
__asm__ volatile( \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"ldr r2, [%1, #28] \n\t" \
"push {r0, r1, r2} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #12 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[9]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
__asm__ volatile( \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"ldr r2, [%1, #28] \n\t" \
"ldr r3, [%1, #32] \n\t" \
"push {r0, r1, r2, r3} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #16 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[10]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
__asm__ volatile( \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"ldr r2, [%1, #28] \n\t" \
"ldr r3, [%1, #32] \n\t" \
"ldr r4, [%1, #36] \n\t" \
"push {r0, r1, r2, r3, r4} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #20 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[11]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
__asm__ volatile( \
"ldr r0, [%1, #40] \n\t" \
"push {r0} \n\t" \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"ldr r2, [%1, #28] \n\t" \
"ldr r3, [%1, #32] \n\t" \
"ldr r4, [%1, #36] \n\t" \
"push {r0, r1, r2, r3, r4} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #24 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
arg6,arg7,arg8,arg9,arg10, \
arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[12]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
_argvec[11] = (unsigned long)(arg11); \
__asm__ volatile( \
"ldr r0, [%1, #40] \n\t" \
"ldr r1, [%1, #44] \n\t" \
"push {r0, r1} \n\t" \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"ldr r2, [%1, #28] \n\t" \
"ldr r3, [%1, #32] \n\t" \
"ldr r4, [%1, #36] \n\t" \
"push {r0, r1, r2, r3, r4} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #28 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory",__CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
arg6,arg7,arg8,arg9,arg10, \
arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[13]; \
volatile unsigned long _res; \
_argvec[0] = (unsigned long)_orig.nraddr; \
_argvec[1] = (unsigned long)(arg1); \
_argvec[2] = (unsigned long)(arg2); \
_argvec[3] = (unsigned long)(arg3); \
_argvec[4] = (unsigned long)(arg4); \
_argvec[5] = (unsigned long)(arg5); \
_argvec[6] = (unsigned long)(arg6); \
_argvec[7] = (unsigned long)(arg7); \
_argvec[8] = (unsigned long)(arg8); \
_argvec[9] = (unsigned long)(arg9); \
_argvec[10] = (unsigned long)(arg10); \
_argvec[11] = (unsigned long)(arg11); \
_argvec[12] = (unsigned long)(arg12); \
__asm__ volatile( \
"ldr r0, [%1, #40] \n\t" \
"ldr r1, [%1, #44] \n\t" \
"ldr r2, [%1, #48] \n\t" \
"push {r0, r1, r2} \n\t" \
"ldr r0, [%1, #20] \n\t" \
"ldr r1, [%1, #24] \n\t" \
"ldr r2, [%1, #28] \n\t" \
"ldr r3, [%1, #32] \n\t" \
"ldr r4, [%1, #36] \n\t" \
"push {r0, r1, r2, r3, r4} \n\t" \
"ldr r0, [%1, #4] \n\t" \
"ldr r1, [%1, #8] \n\t" \
"ldr r2, [%1, #12] \n\t" \
"ldr r3, [%1, #16] \n\t" \
"ldr r4, [%1] \n\t" /* target->r4 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
"add sp, sp, #32 \n\t" \
"mov %0, r0" \
: /*out*/ "=r" (_res) \
: /*in*/ "0" (&_argvec[0]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_arm_linux */
/* ------------------------ ppc32-aix5 ------------------------- */
#if defined(PLAT_ppc32_aix5)
/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
/* These regs are trashed by the hidden call. */
#define __CALLER_SAVED_REGS \
"lr", "ctr", "xer", \
"cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
"r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
"r11", "r12", "r13"
/* Expand the stack frame, copying enough info that unwinding
still works. Trashes r3. */
#define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \
"addi 1,1,-" #_n_fr "\n\t" \
"lwz 3," #_n_fr "(1)\n\t" \
"stw 3,0(1)\n\t"
#define VG_CONTRACT_FRAME_BY(_n_fr) \
"addi 1,1," #_n_fr "\n\t"
/* These CALL_FN_ macros assume that on ppc32-aix5, sizeof(unsigned
long) == 4. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+0]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+1]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+2]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+3]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+4]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+5]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+6]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+7]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 9, 28(11)\n\t" /* arg7->r9 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+8]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 9, 28(11)\n\t" /* arg7->r9 */ \
"lwz 10, 32(11)\n\t" /* arg8->r10 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+9]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(64) \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,56(1)\n\t" \
/* args1-8 */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 9, 28(11)\n\t" /* arg7->r9 */ \
"lwz 10, 32(11)\n\t" /* arg8->r10 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(64) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+10]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(64) \
/* arg10 */ \
"lwz 3,40(11)\n\t" \
"stw 3,60(1)\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,56(1)\n\t" \
/* args1-8 */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 9, 28(11)\n\t" /* arg7->r9 */ \
"lwz 10, 32(11)\n\t" /* arg8->r10 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(64) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+11]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
_argvec[2+11] = (unsigned long)arg11; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(72) \
/* arg11 */ \
"lwz 3,44(11)\n\t" \
"stw 3,64(1)\n\t" \
/* arg10 */ \
"lwz 3,40(11)\n\t" \
"stw 3,60(1)\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,56(1)\n\t" \
/* args1-8 */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 9, 28(11)\n\t" /* arg7->r9 */ \
"lwz 10, 32(11)\n\t" /* arg8->r10 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(72) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+12]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
_argvec[2+11] = (unsigned long)arg11; \
_argvec[2+12] = (unsigned long)arg12; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"stw 2,-8(11)\n\t" /* save tocptr */ \
"lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(72) \
/* arg12 */ \
"lwz 3,48(11)\n\t" \
"stw 3,68(1)\n\t" \
/* arg11 */ \
"lwz 3,44(11)\n\t" \
"stw 3,64(1)\n\t" \
/* arg10 */ \
"lwz 3,40(11)\n\t" \
"stw 3,60(1)\n\t" \
/* arg9 */ \
"lwz 3,36(11)\n\t" \
"stw 3,56(1)\n\t" \
/* args1-8 */ \
"lwz 3, 4(11)\n\t" /* arg1->r3 */ \
"lwz 4, 8(11)\n\t" /* arg2->r4 */ \
"lwz 5, 12(11)\n\t" /* arg3->r5 */ \
"lwz 6, 16(11)\n\t" /* arg4->r6 */ \
"lwz 7, 20(11)\n\t" /* arg5->r7 */ \
"lwz 8, 24(11)\n\t" /* arg6->r8 */ \
"lwz 9, 28(11)\n\t" /* arg7->r9 */ \
"lwz 10, 32(11)\n\t" /* arg8->r10 */ \
"lwz 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"lwz 2,-8(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(72) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_ppc32_aix5 */
/* ------------------------ ppc64-aix5 ------------------------- */
#if defined(PLAT_ppc64_aix5)
/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
/* These regs are trashed by the hidden call. */
#define __CALLER_SAVED_REGS \
"lr", "ctr", "xer", \
"cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
"r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
"r11", "r12", "r13"
/* Expand the stack frame, copying enough info that unwinding
still works. Trashes r3. */
#define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \
"addi 1,1,-" #_n_fr "\n\t" \
"ld 3," #_n_fr "(1)\n\t" \
"std 3,0(1)\n\t"
#define VG_CONTRACT_FRAME_BY(_n_fr) \
"addi 1,1," #_n_fr "\n\t"
/* These CALL_FN_ macros assume that on ppc64-aix5, sizeof(unsigned
long) == 8. */
#define CALL_FN_W_v(lval, orig) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+0]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_W(lval, orig, arg1) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+1]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+2]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+3]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+4]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+5]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+6]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+7]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+8]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+9]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(128) \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(128) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+10]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(128) \
/* arg10 */ \
"ld 3,80(11)\n\t" \
"std 3,120(1)\n\t" \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(128) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+11]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
_argvec[2+11] = (unsigned long)arg11; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(144) \
/* arg11 */ \
"ld 3,88(11)\n\t" \
"std 3,128(1)\n\t" \
/* arg10 */ \
"ld 3,80(11)\n\t" \
"std 3,120(1)\n\t" \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(144) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
arg7,arg8,arg9,arg10,arg11,arg12) \
do { \
volatile OrigFn _orig = (orig); \
volatile unsigned long _argvec[3+12]; \
volatile unsigned long _res; \
/* _argvec[0] holds current r2 across the call */ \
_argvec[1] = (unsigned long)_orig.r2; \
_argvec[2] = (unsigned long)_orig.nraddr; \
_argvec[2+1] = (unsigned long)arg1; \
_argvec[2+2] = (unsigned long)arg2; \
_argvec[2+3] = (unsigned long)arg3; \
_argvec[2+4] = (unsigned long)arg4; \
_argvec[2+5] = (unsigned long)arg5; \
_argvec[2+6] = (unsigned long)arg6; \
_argvec[2+7] = (unsigned long)arg7; \
_argvec[2+8] = (unsigned long)arg8; \
_argvec[2+9] = (unsigned long)arg9; \
_argvec[2+10] = (unsigned long)arg10; \
_argvec[2+11] = (unsigned long)arg11; \
_argvec[2+12] = (unsigned long)arg12; \
__asm__ volatile( \
"mr 11,%1\n\t" \
VG_EXPAND_FRAME_BY_trashes_r3(512) \
"std 2,-16(11)\n\t" /* save tocptr */ \
"ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
VG_EXPAND_FRAME_BY_trashes_r3(144) \
/* arg12 */ \
"ld 3,96(11)\n\t" \
"std 3,136(1)\n\t" \
/* arg11 */ \
"ld 3,88(11)\n\t" \
"std 3,128(1)\n\t" \
/* arg10 */ \
"ld 3,80(11)\n\t" \
"std 3,120(1)\n\t" \
/* arg9 */ \
"ld 3,72(11)\n\t" \
"std 3,112(1)\n\t" \
/* args1-8 */ \
"ld 3, 8(11)\n\t" /* arg1->r3 */ \
"ld 4, 16(11)\n\t" /* arg2->r4 */ \
"ld 5, 24(11)\n\t" /* arg3->r5 */ \
"ld 6, 32(11)\n\t" /* arg4->r6 */ \
"ld 7, 40(11)\n\t" /* arg5->r7 */ \
"ld 8, 48(11)\n\t" /* arg6->r8 */ \
"ld 9, 56(11)\n\t" /* arg7->r9 */ \
"ld 10, 64(11)\n\t" /* arg8->r10 */ \
"ld 11, 0(11)\n\t" /* target->r11 */ \
VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
"mr 11,%1\n\t" \
"mr %0,3\n\t" \
"ld 2,-16(11)\n\t" /* restore tocptr */ \
VG_CONTRACT_FRAME_BY(144) \
VG_CONTRACT_FRAME_BY(512) \
: /*out*/ "=r" (_res) \
: /*in*/ "r" (&_argvec[2]) \
: /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
); \
lval = (__typeof__(lval)) _res; \
} while (0)
#endif /* PLAT_ppc64_aix5 */
/* ------------------------------------------------------------------ */
/* ARCHITECTURE INDEPENDENT MACROS for CLIENT REQUESTS. */
/* */
/* ------------------------------------------------------------------ */
/* Some request codes. There are many more of these, but most are not
exposed to end-user view. These are the public ones, all of the
form 0x1000 + small_number.
Core ones are in the range 0x00000000--0x0000ffff. The non-public
ones start at 0x2000.
*/
/* These macros are used by tools -- they must be public, but don't
embed them into other programs. */
#define VG_USERREQ_TOOL_BASE(a,b) \
((unsigned int)(((a)&0xff) << 24 | ((b)&0xff) << 16))
#define VG_IS_TOOL_USERREQ(a, b, v) \
(VG_USERREQ_TOOL_BASE(a,b) == ((v) & 0xffff0000))
/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !!
This enum comprises an ABI exported by Valgrind to programs
which use client requests. DO NOT CHANGE THE ORDER OF THESE
ENTRIES, NOR DELETE ANY -- add new ones at the end. */
typedef
enum { VG_USERREQ__RUNNING_ON_VALGRIND = 0x1001,
VG_USERREQ__DISCARD_TRANSLATIONS = 0x1002,
/* These allow any function to be called from the simulated
CPU but run on the real CPU. Nb: the first arg passed to
the function is always the ThreadId of the running
thread! So CLIENT_CALL0 actually requires a 1 arg
function, etc. */
VG_USERREQ__CLIENT_CALL0 = 0x1101,
VG_USERREQ__CLIENT_CALL1 = 0x1102,
VG_USERREQ__CLIENT_CALL2 = 0x1103,
VG_USERREQ__CLIENT_CALL3 = 0x1104,
/* Can be useful in regression testing suites -- eg. can
send Valgrind's output to /dev/null and still count
errors. */
VG_USERREQ__COUNT_ERRORS = 0x1201,
/* These are useful and can be interpreted by any tool that
tracks malloc() et al, by using vg_replace_malloc.c. */
VG_USERREQ__MALLOCLIKE_BLOCK = 0x1301,
VG_USERREQ__FREELIKE_BLOCK = 0x1302,
/* Memory pool support. */
VG_USERREQ__CREATE_MEMPOOL = 0x1303,
VG_USERREQ__DESTROY_MEMPOOL = 0x1304,
VG_USERREQ__MEMPOOL_ALLOC = 0x1305,
VG_USERREQ__MEMPOOL_FREE = 0x1306,
VG_USERREQ__MEMPOOL_TRIM = 0x1307,
VG_USERREQ__MOVE_MEMPOOL = 0x1308,
VG_USERREQ__MEMPOOL_CHANGE = 0x1309,
VG_USERREQ__MEMPOOL_EXISTS = 0x130a,
/* Allow printfs to valgrind log. */
/* The first two pass the va_list argument by value, which
assumes it is the same size as or smaller than a UWord,
which generally isn't the case. Hence are deprecated.
The second two pass the vargs by reference and so are
immune to this problem. */
/* both :: char* fmt, va_list vargs (DEPRECATED) */
VG_USERREQ__PRINTF = 0x1401,
VG_USERREQ__PRINTF_BACKTRACE = 0x1402,
/* both :: char* fmt, va_list* vargs */
VG_USERREQ__PRINTF_VALIST_BY_REF = 0x1403,
VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF = 0x1404,
/* Stack support. */
VG_USERREQ__STACK_REGISTER = 0x1501,
VG_USERREQ__STACK_DEREGISTER = 0x1502,
VG_USERREQ__STACK_CHANGE = 0x1503,
/* Wine support */
VG_USERREQ__LOAD_PDB_DEBUGINFO = 0x1601
} Vg_ClientRequest;
#if !defined(__GNUC__)
# define __extension__ /* */
#endif
/* Returns the number of Valgrinds this code is running under. That
is, 0 if running natively, 1 if running under Valgrind, 2 if
running under Valgrind which is running under another Valgrind,
etc. */
#define RUNNING_ON_VALGRIND __extension__ \
({unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0 /* if not */, \
VG_USERREQ__RUNNING_ON_VALGRIND, \
0, 0, 0, 0, 0); \
_qzz_res; \
})
/* Discard translation of code in the range [_qzz_addr .. _qzz_addr +
_qzz_len - 1]. Useful if you are debugging a JITter or some such,
since it provides a way to make sure valgrind will retranslate the
invalidated area. Returns no value. */
#define VALGRIND_DISCARD_TRANSLATIONS(_qzz_addr,_qzz_len) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__DISCARD_TRANSLATIONS, \
_qzz_addr, _qzz_len, 0, 0, 0); \
}
/* These requests are for getting Valgrind itself to print something.
Possibly with a backtrace. This is a really ugly hack. The return value
is the number of characters printed, excluding the "**<pid>** " part at the
start and the backtrace (if present). */
#if defined(NVALGRIND)
# define VALGRIND_PRINTF(...)
# define VALGRIND_PRINTF_BACKTRACE(...)
#else /* NVALGRIND */
/* Modern GCC will optimize the static routine out if unused,
and unused attribute will shut down warnings about it. */
static int VALGRIND_PRINTF(const char *format, ...)
__attribute__((format(__printf__, 1, 2), __unused__));
static int
VALGRIND_PRINTF(const char *format, ...)
{
unsigned long _qzz_res;
va_list vargs;
va_start(vargs, format);
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0,
VG_USERREQ__PRINTF_VALIST_BY_REF,
(unsigned long)format,
(unsigned long)&vargs,
0, 0, 0);
va_end(vargs);
return (int)_qzz_res;
}
static int VALGRIND_PRINTF_BACKTRACE(const char *format, ...)
__attribute__((format(__printf__, 1, 2), __unused__));
static int
VALGRIND_PRINTF_BACKTRACE(const char *format, ...)
{
unsigned long _qzz_res;
va_list vargs;
va_start(vargs, format);
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0,
VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF,
(unsigned long)format,
(unsigned long)&vargs,
0, 0, 0);
va_end(vargs);
return (int)_qzz_res;
}
#endif /* NVALGRIND */
/* These requests allow control to move from the simulated CPU to the
real CPU, calling an arbitrary function.
Note that the current ThreadId is inserted as the first argument.
So this call:
VALGRIND_NON_SIMD_CALL2(f, arg1, arg2)
requires f to have this signature:
Word f(Word tid, Word arg1, Word arg2)
where "Word" is a word-sized type.
Note that these client requests are not entirely reliable. For example,
if you call a function with them that subsequently calls printf(),
there's a high chance Valgrind will crash. Generally, your prospects of
these working are made higher if the called function does not refer to
any global variables, and does not refer to any libc or other functions
(printf et al). Any kind of entanglement with libc or dynamic linking is
likely to have a bad outcome, for tricky reasons which we've grappled
with a lot in the past.
*/
#define VALGRIND_NON_SIMD_CALL0(_qyy_fn) \
__extension__ \
({unsigned long _qyy_res; \
VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
VG_USERREQ__CLIENT_CALL0, \
_qyy_fn, \
0, 0, 0, 0); \
_qyy_res; \
})
#define VALGRIND_NON_SIMD_CALL1(_qyy_fn, _qyy_arg1) \
__extension__ \
({unsigned long _qyy_res; \
VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
VG_USERREQ__CLIENT_CALL1, \
_qyy_fn, \
_qyy_arg1, 0, 0, 0); \
_qyy_res; \
})
#define VALGRIND_NON_SIMD_CALL2(_qyy_fn, _qyy_arg1, _qyy_arg2) \
__extension__ \
({unsigned long _qyy_res; \
VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
VG_USERREQ__CLIENT_CALL2, \
_qyy_fn, \
_qyy_arg1, _qyy_arg2, 0, 0); \
_qyy_res; \
})
#define VALGRIND_NON_SIMD_CALL3(_qyy_fn, _qyy_arg1, _qyy_arg2, _qyy_arg3) \
__extension__ \
({unsigned long _qyy_res; \
VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
VG_USERREQ__CLIENT_CALL3, \
_qyy_fn, \
_qyy_arg1, _qyy_arg2, \
_qyy_arg3, 0); \
_qyy_res; \
})
/* Counts the number of errors that have been recorded by a tool. Nb:
the tool must record the errors with VG_(maybe_record_error)() or
VG_(unique_error)() for them to be counted. */
#define VALGRIND_COUNT_ERRORS \
__extension__ \
({unsigned int _qyy_res; \
VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
VG_USERREQ__COUNT_ERRORS, \
0, 0, 0, 0, 0); \
_qyy_res; \
})
/* Several Valgrind tools (Memcheck, Massif, Helgrind, DRD) rely on knowing
when heap blocks are allocated in order to give accurate results. This
happens automatically for the standard allocator functions such as
malloc(), calloc(), realloc(), memalign(), new, new[], free(), delete,
delete[], etc.
But if your program uses a custom allocator, this doesn't automatically
happen, and Valgrind will not do as well. For example, if you allocate
superblocks with mmap() and then allocates chunks of the superblocks, all
Valgrind's observations will be at the mmap() level and it won't know that
the chunks should be considered separate entities. In Memcheck's case,
that means you probably won't get heap block overrun detection (because
there won't be redzones marked as unaddressable) and you definitely won't
get any leak detection.
The following client requests allow a custom allocator to be annotated so
that it can be handled accurately by Valgrind.
VALGRIND_MALLOCLIKE_BLOCK marks a region of memory as having been allocated
by a malloc()-like function. For Memcheck (an illustrative case), this
does two things:
- It records that the block has been allocated. This means any addresses
within the block mentioned in error messages will be
identified as belonging to the block. It also means that if the block
isn't freed it will be detected by the leak checker.
- It marks the block as being addressable and undefined (if 'is_zeroed' is
not set), or addressable and defined (if 'is_zeroed' is set). This
controls how accesses to the block by the program are handled.
'addr' is the start of the usable block (ie. after any
redzone), 'sizeB' is its size. 'rzB' is the redzone size if the allocator
can apply redzones -- these are blocks of padding at the start and end of
each block. Adding redzones is recommended as it makes it much more likely
Valgrind will spot block overruns. `is_zeroed' indicates if the memory is
zeroed (or filled with another predictable value), as is the case for
calloc().
VALGRIND_MALLOCLIKE_BLOCK should be put immediately after the point where a
heap block -- that will be used by the client program -- is allocated.
It's best to put it at the outermost level of the allocator if possible;
for example, if you have a function my_alloc() which calls
internal_alloc(), and the client request is put inside internal_alloc(),
stack traces relating to the heap block will contain entries for both
my_alloc() and internal_alloc(), which is probably not what you want.
For Memcheck users: if you use VALGRIND_MALLOCLIKE_BLOCK to carve out
custom blocks from within a heap block, B, that has been allocated with
malloc/calloc/new/etc, then block B will be *ignored* during leak-checking
-- the custom blocks will take precedence.
VALGRIND_FREELIKE_BLOCK is the partner to VALGRIND_MALLOCLIKE_BLOCK. For
Memcheck, it does two things:
- It records that the block has been deallocated. This assumes that the
block was annotated as having been allocated via
VALGRIND_MALLOCLIKE_BLOCK. Otherwise, an error will be issued.
- It marks the block as being unaddressable.
VALGRIND_FREELIKE_BLOCK should be put immediately after the point where a
heap block is deallocated.
In many cases, these two client requests will not be enough to get your
allocator working well with Memcheck. More specifically, if your allocator
writes to freed blocks in any way then a VALGRIND_MAKE_MEM_UNDEFINED call
will be necessary to mark the memory as addressable just before the zeroing
occurs, otherwise you'll get a lot of invalid write errors. For example,
you'll need to do this if your allocator recycles freed blocks, but it
zeroes them before handing them back out (via VALGRIND_MALLOCLIKE_BLOCK).
Alternatively, if your allocator reuses freed blocks for allocator-internal
data structures, VALGRIND_MAKE_MEM_UNDEFINED calls will also be necessary.
Really, what's happening is a blurring of the lines between the client
program and the allocator... after VALGRIND_FREELIKE_BLOCK is called, the
memory should be considered unaddressable to the client program, but the
allocator knows more than the rest of the client program and so may be able
to safely access it. Extra client requests are necessary for Valgrind to
understand the distinction between the allocator and the rest of the
program.
Note: there is currently no VALGRIND_REALLOCLIKE_BLOCK client request; it
has to be emulated with MALLOCLIKE/FREELIKE and memory copying.
Ignored if addr == 0.
*/
#define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MALLOCLIKE_BLOCK, \
addr, sizeB, rzB, is_zeroed, 0); \
}
/* See the comment for VALGRIND_MALLOCLIKE_BLOCK for details.
Ignored if addr == 0.
*/
#define VALGRIND_FREELIKE_BLOCK(addr, rzB) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__FREELIKE_BLOCK, \
addr, rzB, 0, 0, 0); \
}
/* Create a memory pool. */
#define VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__CREATE_MEMPOOL, \
pool, rzB, is_zeroed, 0, 0); \
}
/* Destroy a memory pool. */
#define VALGRIND_DESTROY_MEMPOOL(pool) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__DESTROY_MEMPOOL, \
pool, 0, 0, 0, 0); \
}
/* Associate a piece of memory with a memory pool. */
#define VALGRIND_MEMPOOL_ALLOC(pool, addr, size) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MEMPOOL_ALLOC, \
pool, addr, size, 0, 0); \
}
/* Disassociate a piece of memory from a memory pool. */
#define VALGRIND_MEMPOOL_FREE(pool, addr) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MEMPOOL_FREE, \
pool, addr, 0, 0, 0); \
}
/* Disassociate any pieces outside a particular range. */
#define VALGRIND_MEMPOOL_TRIM(pool, addr, size) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MEMPOOL_TRIM, \
pool, addr, size, 0, 0); \
}
/* Resize and/or move a piece associated with a memory pool. */
#define VALGRIND_MOVE_MEMPOOL(poolA, poolB) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MOVE_MEMPOOL, \
poolA, poolB, 0, 0, 0); \
}
/* Resize and/or move a piece associated with a memory pool. */
#define VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB, size) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MEMPOOL_CHANGE, \
pool, addrA, addrB, size, 0); \
}
/* Return 1 if a mempool exists, else 0. */
#define VALGRIND_MEMPOOL_EXISTS(pool) \
__extension__ \
({unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__MEMPOOL_EXISTS, \
pool, 0, 0, 0, 0); \
_qzz_res; \
})
/* Mark a piece of memory as being a stack. Returns a stack id. */
#define VALGRIND_STACK_REGISTER(start, end) \
__extension__ \
({unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__STACK_REGISTER, \
start, end, 0, 0, 0); \
_qzz_res; \
})
/* Unmark the piece of memory associated with a stack id as being a
stack. */
#define VALGRIND_STACK_DEREGISTER(id) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__STACK_DEREGISTER, \
id, 0, 0, 0, 0); \
}
/* Change the start and end address of the stack id. */
#define VALGRIND_STACK_CHANGE(id, start, end) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__STACK_CHANGE, \
id, start, end, 0, 0); \
}
/* Load PDB debug info for Wine PE image_map. */
#define VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta) \
{unsigned int _qzz_res; \
VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
VG_USERREQ__LOAD_PDB_DEBUGINFO, \
fd, ptr, total_size, delta, 0); \
}
#undef PLAT_x86_linux
#undef PLAT_amd64_linux
#undef PLAT_ppc32_linux
#undef PLAT_ppc64_linux
#undef PLAT_arm_linux
#undef PLAT_ppc32_aix5
#undef PLAT_ppc64_aix5
#endif /* __VALGRIND_H */
| 267,511
|
C++
|
.h
| 4,195
| 55.279857
| 81
| 0.315649
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,276
|
utils.h
|
openalpr_openalpr/src/openalpr/support/windows/utils.h
|
#include <math.h>
static inline double round(double val)
{
return floor(val + 0.5);
}
| 90
|
C++
|
.h
| 5
| 16.2
| 38
| 0.722892
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
12,278
|
unistd_partial.h
|
openalpr_openalpr/src/openalpr/support/windows/unistd_partial.h
|
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This file intended to serve as a drop-in replacement for
* unistd.h on Windows
* Please add functionality as neeeded
*/
#include <stdlib.h>
#include <io.h>
//#include <getopt.h> /* getopt from: http://www.pwilson.net/sample.html. */
#include <process.h> /* for getpid() and the exec..() family */
#define srandom srand
#define random rand
/* Values for the second argument to access.
These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
//#define X_OK 1 /* execute permission - unsupported in windows*/
#define F_OK 0 /* Test for existence. */
#define access _access
#define ftruncate _chsize
#define ssize_t int
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
//typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif /* unistd.h */
| 1,218
|
C++
|
.h
| 34
| 34.411765
| 76
| 0.67432
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
12,281
|
tesseract_ocr.h
|
openalpr_openalpr/src/openalpr/ocr/tesseract_ocr.h
|
/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENALPR_TESSERACTOCR_H
#define OPENALPR_TESSERACTOCR_H
#include <vector>
#include "utility.h"
#include "config.h"
#include "pipeline_data.h"
#include "constants.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "support/filesystem.h"
#include "support/version.h"
#include "ocr.h"
#include "tesseract/baseapi.h"
namespace alpr
{
class TesseractOcr : public OCR
{
public:
TesseractOcr(Config* config);
virtual ~TesseractOcr();
private:
std::vector<OcrChar> recognize_line(int line_index, PipelineData* pipeline_data);
void segment(PipelineData* pipeline_data);
tesseract::TessBaseAPI tesseract;
};
}
#endif // OPENALPR_TESSERACTOCR_H
| 1,474
|
C++
|
.h
| 44
| 30.659091
| 87
| 0.758156
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,300
|
com_openalpr_jni_Alpr.h
|
openalpr_openalpr/src/bindings/java/com_openalpr_jni_Alpr.h
|
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_openalpr_jni_Alpr */
#ifndef _Included_com_openalpr_jni_Alpr
#define _Included_com_openalpr_jni_Alpr
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_openalpr_jni_Alpr
* Method: initialize
* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_initialize
(JNIEnv *, jobject, jstring, jstring, jstring);
/*
* Class: com_openalpr_jni_Alpr
* Method: dispose
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_dispose
(JNIEnv *, jobject);
/*
* Class: com_openalpr_jni_Alpr
* Method: is_loaded
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_com_openalpr_jni_Alpr_is_1loaded
(JNIEnv *, jobject);
/*
* Class: com_openalpr_jni_Alpr
* Method: native_recognize
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_native_1recognize__Ljava_lang_String_2
(JNIEnv *, jobject, jstring);
/*
* Class: com_openalpr_jni_Alpr
* Method: native_recognize
* Signature: ([B)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_native_1recognize___3B
(JNIEnv *, jobject, jbyteArray);
/*
* Class: com_openalpr_jni_Alpr
* Method: native_recognize
* Signature: (JIII)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_native_1recognize__JIII
(JNIEnv *, jobject, jlong, jint, jint, jint);
/*
* Class: com_openalpr_jni_Alpr
* Method: set_default_region
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_set_1default_1region
(JNIEnv *, jobject, jstring);
/*
* Class: com_openalpr_jni_Alpr
* Method: detect_region
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_detect_1region
(JNIEnv *, jobject, jboolean);
/*
* Class: com_openalpr_jni_Alpr
* Method: set_top_n
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_com_openalpr_jni_Alpr_set_1top_1n
(JNIEnv *, jobject, jint);
/*
* Class: com_openalpr_jni_Alpr
* Method: get_version
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_openalpr_jni_Alpr_get_1version
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
| 2,353
|
C++
|
.h
| 82
| 26.829268
| 91
| 0.718584
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
12,301
|
openalprgo.h
|
openalpr_openalpr/src/bindings/go/openalprgo.h
|
#if defined(_MSC_VER)
// Microsoft
#define OPENALPR_EXPORT __declspec(dllexport)
#else
// do nothing
#define OPENALPR_EXPORT
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Alpr;
OPENALPR_EXPORT Alpr AlprInit(char* country, char* configFile, char* runtimeDir);
OPENALPR_EXPORT void SetDetectRegion(Alpr alpr, int detectRegion);
OPENALPR_EXPORT void SetTopN(Alpr alpr, int topN);
OPENALPR_EXPORT void SetDefaultRegion(Alpr alpr, char* region);
OPENALPR_EXPORT int IsLoaded(Alpr alpr);
OPENALPR_EXPORT void Unload(Alpr alpr);
OPENALPR_EXPORT char* RecognizeByFilePath(Alpr alpr, char* filePath);
OPENALPR_EXPORT char* RecognizeByBlob(Alpr alpr, char* imageBytes, int len);
OPENALPR_EXPORT char* GetVersion();
#ifdef __cplusplus
}
#endif
| 765
|
C++
|
.h
| 23
| 31.565217
| 82
| 0.788904
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
12,302
|
beanstalk.h
|
openalpr_openalpr/src/daemon/beanstalk.h
|
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/fcntl.h>
#define BS_MAJOR_VERSION 1
#define BS_MINOR_VERSION 2
#define BS_PATCH_VERSION 0
#define BS_STATUS_OK 0
#define BS_STATUS_FAIL -1
#define BS_STATUS_EXPECTED_CRLF -2
#define BS_STATUS_JOB_TOO_BIG -3
#define BS_STATUS_DRAINING -4
#define BS_STATUS_TIMED_OUT -5
#define BS_STATUS_NOT_FOUND -6
#define BS_STATUS_DEADLINE_SOON -7
#define BS_STATUS_BURIED -8
#define BS_STATUS_NOT_IGNORED -9
#ifdef __cplusplus
extern "C" {
#endif
typedef struct bs_message {
char *data;
char *status;
size_t size;
} BSM;
typedef struct bs_job {
int64_t id;
char *data;
size_t size;
} BSJ;
// optional polling call, returns 1 if the socket is ready of the rw operation specified.
// rw: 1 => read, 2 => write, 3 => read/write
// fd: file descriptor of the socket
typedef int (*bs_poll_function)(int rw, int fd);
/* Handle DSO symbol visibility - Stolen from zmq.h */
#if defined _WIN32
# if defined DLL_EXPORT
# define BSC_EXPORT __declspec(dllexport)
# else
# define BSC_EXPORT __declspec(dllimport)
# endif
#else
# if defined __SUNPRO_C || defined __SUNPRO_CC
# define BSC_EXPORT __global
# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER
# define BSC_EXPORT __attribute__ ((visibility("default")))
# else
# define BSC_EXPORT
# endif
#endif
// export version
BSC_EXPORT void bs_version(int *major, int *minor, int *patch);
// polling setup
BSC_EXPORT void bs_start_polling(bs_poll_function f);
BSC_EXPORT void bs_reset_polling(void);
// returns a descriptive text of the error code.
BSC_EXPORT const char* bs_status_text(int code);
BSC_EXPORT void bs_free_message(BSM* m);
BSC_EXPORT void bs_free_job(BSJ *job);
// returns socket descriptor or BS_STATUS_FAIL
BSC_EXPORT int bs_connect(char *host, int port);
BSC_EXPORT int bs_connect_with_timeout(char *host, int port, float secs);
// returns job id or one of the negative failure codes.
BSC_EXPORT int64_t bs_put(int fd, uint32_t priority, uint32_t delay, uint32_t ttr, char *data, size_t bytes);
// rest return BS_STATUS_OK or one of the failure codes.
BSC_EXPORT int bs_disconnect(int fd);
BSC_EXPORT int bs_use(int fd, char *tube);
BSC_EXPORT int bs_watch(int fd, char *tube);
BSC_EXPORT int bs_ignore(int fd, char *tube);
BSC_EXPORT int bs_delete(int fd, int64_t job);
BSC_EXPORT int bs_reserve(int fd, BSJ **job);
BSC_EXPORT int bs_reserve_with_timeout(int fd, uint32_t ttl, BSJ **job);
BSC_EXPORT int bs_release(int fd, int64_t id, uint32_t priority, uint32_t delay);
BSC_EXPORT int bs_bury(int fd, int64_t id, uint32_t priority);
BSC_EXPORT int bs_touch(int fd, int64_t id);
BSC_EXPORT int bs_peek(int fd, int64_t id, BSJ **job);
BSC_EXPORT int bs_peek_ready(int fd, BSJ **job);
BSC_EXPORT int bs_peek_delayed(int fd, BSJ **job);
BSC_EXPORT int bs_peek_buried(int fd, BSJ **job);
BSC_EXPORT int bs_kick(int fd, int bound);
BSC_EXPORT int bs_list_tube_used(int fd, char **tube);
BSC_EXPORT int bs_list_tubes(int fd, char **yaml);
BSC_EXPORT int bs_list_tubes_watched(int fd, char **yaml);
BSC_EXPORT int bs_stats(int fd, char **yaml);
BSC_EXPORT int bs_stats_job(int fd, int64_t id, char **yaml);
BSC_EXPORT int bs_stats_tube(int fd, char *tube, char **yaml);
#ifdef __cplusplus
}
#endif
| 3,475
|
C++
|
.h
| 94
| 35.43617
| 109
| 0.710972
|
openalpr/openalpr
| 10,994
| 2,489
| 519
|
AGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
12,307
|
SettingsDialogPaletteTabTest.cpp
|
xournalpp_xournalpp/test/gtk_tests/dialog/SettingsDialogPaletteTabTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include "gui/GladeSearchpath.h"
#include "gui/dialog/SettingsDialogPaletteTab.h"
#include "util/PathUtil.h"
#include "util/Stacktrace.h"
#include "GtkTest.h"
#include "config-test.h"
void createAndSetupWidgets(GtkApplication* app, GtkGrid** grid, GtkLabel** mainLabel, GtkListBox** optionsList) {
GtkWidget* window = gtk_application_window_new(app);
*grid = GTK_GRID(gtk_grid_new());
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(*grid));
*mainLabel = GTK_LABEL(gtk_label_new(""));
*optionsList = GTK_LIST_BOX(gtk_list_box_new());
gtk_grid_attach(*grid, GTK_WIDGET(*mainLabel), 0, 0, 1, 1);
gtk_grid_attach(*grid, GTK_WIDGET(*optionsList), 0, 1, 1, 1);
}
class UnrenderedPaletteTabTest: public GtkTest {
void runTest(GtkApplication* app) override {
GtkGrid* grid = nullptr;
GtkLabel* mainLabel = nullptr;
GtkListBox* optionsList = nullptr;
createAndSetupWidgets(app, &grid, &mainLabel, &optionsList);
const fs::path palettePath{GET_TESTFILE("palettes/xournalpp.gpl")};
GladeSearchpath gladeSearchPath{};
gladeSearchPath.addSearchDirectory(Util::getDataPath() / "ui");
const std::vector<fs::path> paletteDirectories{palettePath.parent_path()};
SettingsDialogPaletteTab paletteTab{&gladeSearchPath, paletteDirectories};
EXPECT_EQ(paletteTab.getSelectedPalette(), std::nullopt);
}
};
TEST_F(UnrenderedPaletteTabTest, unrenderedPaletteTabShouldYieldNoSelectedPalette) {}
class RenderedPaletteTabTest: public GtkTest {
void runTest(GtkApplication* app) override {
GtkGrid* grid = nullptr;
GtkLabel* mainLabel = nullptr;
GtkListBox* optionsList = nullptr;
createAndSetupWidgets(app, &grid, &mainLabel, &optionsList);
const fs::path palettePath{GET_TESTFILE("palettes/xournalpp.gpl")};
GladeSearchpath gladeSearchPath{};
gladeSearchPath.addSearchDirectory(Util::getDataPath() / "ui");
const std::vector<fs::path> paletteDirectories{palettePath.parent_path()};
SettingsDialogPaletteTab paletteTab{&gladeSearchPath, paletteDirectories};
paletteTab.renderPaletteTab(palettePath);
EXPECT_EQ(palettePath.u8string(), paletteTab.getSelectedPalette().value().u8string());
}
};
TEST_F(RenderedPaletteTabTest, renderedPaletteTabShouldNotChangeSelectedColorPalette) {}
| 2,555
|
C++
|
.cpp
| 56
| 40.482143
| 113
| 0.728296
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,308
|
GtkTest.cpp
|
xournalpp_xournalpp/test/gtk_tests/dialog/GtkTest.cpp
|
//
// Created by hermannt on 11.06.23.
//
#include "GtkTest.h"
// Setting up the testing environment
void GtkTest::SetUp() {
argn = 1;
argv = new char*[2];
argv[0] = "xournalpp_test";
argv[1] = nullptr;
app = gtk_application_new("com.github.xournalpp.xournalpp.test", G_APPLICATION_FLAGS_NONE);
g_signal_connect(app, "activate", G_CALLBACK(applicationCallback), this);
g_application_run(G_APPLICATION(app), argn, argv);
}
// This the callback in which the actual test is run
// It needs to be a callback because it requires the GtkApplication to be running already.
void GtkTest::applicationCallback(GtkApplication* app, gpointer userData) {
auto* test = static_cast<GtkTest*>(userData);
// run the actual test
test->runTest(app);
// Quit the application to avoid waiting indefinitely fo the test to finish
g_application_quit(G_APPLICATION(app));
}
| 902
|
C++
|
.cpp
| 23
| 35.913043
| 95
| 0.720824
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,309
|
I18nTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/I18nTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <cstdlib>
#include <ctime>
#include <gtest/gtest.h>
#include "util/i18n.h"
#include "config-test.h"
using namespace std;
TEST(UtilI18n, testNoPlaceholder) {
string msg = FS(FORMAT_STR("test123") % 1 % 2 % 3);
EXPECT_EQ(std::string("test123"), msg);
}
TEST(UtilI18n, testEscape) {
string msg = FS(FORMAT_STR("test{{123") % 1 % 2 % 3);
EXPECT_EQ(std::string("test{123"), msg);
}
TEST(UtilI18n, testReplace) {
string msg = FS(FORMAT_STR("aa {1} bb {1} {2}") % 1 % 2 % 3);
EXPECT_EQ(std::string("aa 1 bb 1 2"), msg);
}
TEST(UtilI18n, testMissing) {
string msg = FS(FORMAT_STR("aa {1} bb {1} {2}"));
EXPECT_EQ(std::string("aa {1} bb {1} {2}"), msg);
}
TEST(UtilI18n, testOrder) {
string msg = FS(FORMAT_STR(".. {2} .. {1} -- {2} {1}") % "a" % "b");
EXPECT_EQ(std::string(".. b .. a -- b a"), msg);
}
TEST(UtilI18n, testLatexString) {
string command =
FS(FORMAT_STR("{1} -m 0 \"\\png\\usepackage{{color}}\\color{{{2}}}\\dpi{{{3}}}\\normalsize {4}\" -o {5}") %
"abc" % "red" % 45 % "asdf" % "asdf.png");
EXPECT_EQ(std::string("abc -m 0 \"\\png\\usepackage{color}\\color{red}\\dpi{45}\\normalsize asdf\" -o asdf.png"),
command);
}
TEST(UtilI18n, test3) {
string msg = FS(FORMAT_STR(" of {1}{2}") % 5 % 6);
EXPECT_EQ(std::string(" of 56"), msg);
}
TEST(UtilI18n, test16bit) {
string msg = FS(FORMAT_STR("{1} = {2} and {3}") % 60123 % 60123U % -65536);
EXPECT_EQ(std::string("60123 = 60123 and -65536"), msg);
}
TEST(UtilI18n, test32bit) {
string msg = FS(FORMAT_STR("{1} and {2}") % 4294967295U % -12345678);
EXPECT_EQ(std::string("4294967295 and -12345678"), msg);
}
TEST(UtilI18n, test64bit) {
string msg = FS(FORMAT_STR("{1} and {2}") % 1234567890123456789U % -1234567890123456789);
EXPECT_EQ(std::string("1234567890123456789 and -1234567890123456789"), msg);
}
| 2,082
|
C++
|
.cpp
| 59
| 31.711864
| 119
| 0.608196
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,310
|
ElementRangeTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/ElementRangeTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <ostream>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "util/ElementRange.h"
bool operator==(const ElementRangeEntry& lhs, const ElementRangeEntry& rhs) {
return lhs.first == rhs.first && lhs.last == rhs.last;
}
TEST(UtilElementRange, testParse) {
std::string ranges = "1, 2-, -3, 4-5, -";
ElementRangeVector result{{0, 0}, {1, 9}, {0, 2}, {3, 4}, {0, 9}};
auto v_10 = ElementRange::parse(ranges, 10);
ASSERT_EQ(v_10.size(), result.size());
auto it1 = v_10.cbegin();
auto it2 = result.cbegin();
while (it1 != v_10.cend()) { ASSERT_EQ(*it1++, *it2++); }
}
TEST(UtilElementRange, testInvalid) {
const std::vector<std::string> bad_inputs = {
"github", "", " \t\t \n\r\n \r\r ", "1-3, 6; HELLOWORLD ; 4- : -5,, 6-5, 99-, -", "5-11",
"0-3", "6-5"};
size_t maxCount = 10;
for (auto& bad_input: bad_inputs) {
try {
auto actual = ElementRange::parse(bad_input, maxCount);
FAIL() << "std::invalid_argument not thrown for bad input.";
} catch (const std::invalid_argument&) {
// good, exception is thrown as it should
} catch (const std::exception& e) { FAIL() << e.what(); } catch (...) {
FAIL() << "Unexpected exception caught.";
}
}
}
TEST(UtilElementRange, testPageCountIsZero) {
try {
auto actual = ElementRange::parse("", 0);
FAIL() << "std::logic_error not thrown when maxCount equals 0.";
} catch (const std::logic_error&) {
// good, exception is thrown as it should
} catch (const std::exception& e) { FAIL() << e.what(); } catch (...) {
FAIL() << "Unexpected exception caught.";
}
}
| 1,923
|
C++
|
.cpp
| 53
| 31.113208
| 118
| 0.584499
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,311
|
StringUtilsTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/StringUtilsTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <cstdlib>
#include <ctime>
#include <gtest/gtest.h>
#include "util/StringUtils.h"
#include "config-test.h"
using namespace std;
TEST(UtilStringUtils, testStartWith) {
EXPECT_EQ(true, StringUtils::startsWith("asdfsfdafdasfda", "asdf"));
EXPECT_EQ(false, StringUtils::startsWith("111111111111111", "2222"));
EXPECT_EQ(false, StringUtils::startsWith("122221111111111", "2222"));
EXPECT_EQ(false, StringUtils::startsWith("", "asdf"));
EXPECT_EQ(true, StringUtils::startsWith("aaaaaaa", ""));
}
TEST(UtilStringUtils, testSplit) {
vector<string> splitted = StringUtils::split("a,,b,c,d,e,f", ',');
EXPECT_EQ(7, (int)splitted.size());
EXPECT_EQ(std::string("a"), splitted[0]);
EXPECT_EQ(std::string(""), splitted[1]);
}
TEST(UtilStringUtils, testSplitEmpty) {
vector<string> splitted = StringUtils::split("", ',');
EXPECT_EQ(0, (int)splitted.size());
}
TEST(UtilStringUtils, testSplitOne) {
vector<string> splitted = StringUtils::split("aa", ',');
EXPECT_EQ(1, (int)splitted.size());
EXPECT_EQ(std::string("aa"), splitted[0]);
}
TEST(UtilStringUtils, testEndsWith) {
EXPECT_EQ(true, StringUtils::endsWith("asdfsfdafdasfda.xoj", ".xoj"));
EXPECT_EQ(false, StringUtils::endsWith("111111111111111", "2222"));
EXPECT_EQ(false, StringUtils::endsWith("111111111122221", "2222"));
EXPECT_EQ(false, StringUtils::endsWith("", "asdf"));
EXPECT_EQ(true, StringUtils::endsWith("aaaaaaa", ""));
}
TEST(UtilStringUtils, testCompare) {
EXPECT_EQ(true, StringUtils::iequals("", ""));
EXPECT_EQ(true, StringUtils::iequals("aaaaaaaa", "aAAAaaaa"));
EXPECT_EQ(true, StringUtils::iequals("äää", "ÄÄÄ"));
EXPECT_EQ(true, StringUtils::iequals("ööaa", "Ööaa"));
EXPECT_EQ(false, StringUtils::iequals("ööaa", "ööaaa"));
}
| 2,000
|
C++
|
.cpp
| 52
| 34.865385
| 74
| 0.689781
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,312
|
RAIIWrappersTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/RAIIWrappersTest.cpp
|
#include <gtest/gtest.h>
#include "util/raii/CairoWrappers.h"
#include "util/raii/GObjectSPtr.h"
namespace {
class TestData {
public:
TestData() { nbData++; };
~TestData() { nbData--; };
int value = 2;
int ref_count = 1;
static int nbData;
};
int TestData::nbData = 0;
class TestDataHandler {
public:
static TestData* ref(TestData* p) {
p->ref_count++;
return p;
}
static void unref(TestData* p) {
p->ref_count--;
if (p->ref_count == 0) {
delete (p);
}
}
constexpr static auto adopt = [](TestData* p) { return p; };
};
}; // namespace
using TestRAII = xoj::util::CLibrariesSPtr<TestData, TestDataHandler>;
TEST(UtilsRAII, testCLibbrairiesSPtr_Constructors) {
{
TestRAII t; // Default constructor
EXPECT_EQ(t.get(), nullptr);
EXPECT_FALSE(t);
EXPECT_EQ(TestData::nbData, 0);
TestData* p = nullptr;
TestRAII t1(p = new TestData(), xoj::util::adopt); // Adoption
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 1);
TestRAII t2(std::move(t1)); // move constructor
EXPECT_EQ(t1.get(), nullptr);
EXPECT_EQ(t2.get(), p);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(TestData::nbData, 1);
TestRAII t3(t2); // copy constructor
EXPECT_EQ(t2.get(), p);
EXPECT_EQ(t3.get(), p);
EXPECT_EQ(p->ref_count, 2);
EXPECT_EQ(TestData::nbData, 1);
TestRAII t4(t2.get(), xoj::util::ref); // ref
EXPECT_EQ(t4.get(), p);
EXPECT_EQ(p->ref_count, 3);
EXPECT_EQ(TestData::nbData, 1);
}
EXPECT_EQ(TestData::nbData, 0);
}
TEST(UtilsRAII, testCLibbrairiesSPtr_MoveAssignments) {
{
TestData* p = nullptr;
TestData* q = nullptr;
TestRAII t1(p = new TestData(), xoj::util::adopt);
TestRAII t2(q = new TestData(), xoj::util::adopt);
EXPECT_EQ(TestData::nbData, 2);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t2.get(), q);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(q->ref_count, 1);
t1->value = 4;
t2->value = 14;
std::swap(t1, t2);
EXPECT_EQ(t1->value, 14);
EXPECT_EQ(t2->value, 4);
EXPECT_EQ(TestData::nbData, 2);
EXPECT_EQ(t1.get(), q);
EXPECT_EQ(t2.get(), p);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(q->ref_count, 1);
t1 = std::move(t2); // move assignment - non empty to non empty - different data
q = nullptr;
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t1->value, 4);
EXPECT_EQ(t2.get(), nullptr);
EXPECT_TRUE(t1);
EXPECT_FALSE(t2);
TestRAII t3(p, xoj::util::ref);
EXPECT_EQ(p->ref_count, 2);
t1 = std::move(t3); // move assignment - non empty to non empty - same data
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t1->value, 4);
EXPECT_EQ(t2.get(), nullptr);
EXPECT_TRUE(t1);
EXPECT_FALSE(t2);
t2 = std::move(t1); // move assignment - non empty to empty
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(t1.get(), nullptr);
EXPECT_EQ(t2->value, 4);
EXPECT_EQ(t2.get(), p);
t2 = std::move(t1); // move assignment - empty to non-empty
p = nullptr;
EXPECT_EQ(TestData::nbData, 0);
EXPECT_EQ(t1.get(), nullptr);
EXPECT_EQ(t2.get(), nullptr);
t2 = std::move(t1); // move assignment - empty to empty
EXPECT_EQ(TestData::nbData, 0);
EXPECT_EQ(t1.get(), nullptr);
EXPECT_EQ(t2.get(), nullptr);
}
EXPECT_EQ(TestData::nbData, 0);
}
TEST(UtilsRAII, testCLibbrairiesSPtr_CopyAssignments) {
{
TestData* p = nullptr;
TestData* q = nullptr;
TestRAII t1(p = new TestData(), xoj::util::adopt);
TestRAII t2(q = new TestData(), xoj::util::adopt);
EXPECT_EQ(TestData::nbData, 2);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t2.get(), q);
EXPECT_EQ(p->ref_count, 1);
EXPECT_EQ(q->ref_count, 1);
t1->value = 4;
t2->value = 14;
t2 = t1; // copy assignment - non empty to non empty - different data
q = nullptr;
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 2);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t2.get(), p);
EXPECT_EQ(t2->value, 4);
t2 = t1; // copy assignment - non empty to non empty - same data
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 2);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t2.get(), p);
EXPECT_EQ(t2->value, 4);
TestRAII t3;
t2 = t3; // copy assignment - empty to non-empty
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 1); // t1
EXPECT_EQ(t2.get(), nullptr);
EXPECT_EQ(t3.get(), nullptr);
t3 = t1; // copy assignment - non empty to empty
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(p->ref_count, 2); // t{1,3}
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t3->value, 4);
EXPECT_EQ(t3.get(), p);
TestRAII t4;
t2 = t4; // copy assignment - empty to empty
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(t2.get(), nullptr);
EXPECT_EQ(t4.get(), nullptr);
}
EXPECT_EQ(TestData::nbData, 0);
}
TEST(UtilsRAII, testCLibbrairiesSPtr_Reset) {
{
TestData* p = nullptr;
TestData* q = nullptr;
TestRAII t1(p = new TestData(), xoj::util::adopt);
TestRAII t2;
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(t1.get(), p);
EXPECT_EQ(t2.get(), nullptr);
EXPECT_EQ(p->ref_count, 1);
t1->value = 4;
t2.reset(q = new TestData(), xoj::util::adopt); // Reset - non-nullptr to empty
EXPECT_EQ(TestData::nbData, 2);
EXPECT_EQ(t2.get(), q);
EXPECT_TRUE(t2);
EXPECT_EQ(q->ref_count, 1);
t2.reset(q = new TestData(), xoj::util::adopt); // Reset - non-nullptr to non-empty
EXPECT_EQ(t2.get(), q);
EXPECT_EQ(TestData::nbData, 2);
t1.reset(); // Reset - nullptr to non-empty
p = nullptr;
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(t1.get(), nullptr);
t1.reset(); // Reset - nullptr to empty
EXPECT_EQ(TestData::nbData, 1);
EXPECT_EQ(t1.get(), nullptr);
}
EXPECT_EQ(TestData::nbData, 0);
}
/**
* Test GObject smart pointer
*/
namespace {
G_BEGIN_DECLS
#define TEST_OBJECT_TYPE test_object_get_type()
G_DECLARE_FINAL_TYPE(TestObject, test_object, TEST, OBJECT, GObject)
TestObject* test_object_new(void);
struct _TestObject {
GObject parent_instance;
};
int TestObjectCount = 0;
G_DEFINE_TYPE(TestObject, test_object, G_TYPE_OBJECT)
static void test_object_init(TestObject* self) { TestObjectCount++; }
static void test_object_dispose(GObject* gobject) {
TestObjectCount--;
G_OBJECT_CLASS(test_object_parent_class)->dispose(gobject);
}
static void test_object_finalize(GObject* gobject) { G_OBJECT_CLASS(test_object_parent_class)->finalize(gobject); }
static void test_object_class_init(TestObjectClass* klass) {
GObjectClass* object_class = G_OBJECT_CLASS(klass);
object_class->dispose = test_object_dispose;
object_class->finalize = test_object_finalize;
}
G_END_DECLS
}; // namespace
TEST(UtilsRAII, testGObjectSPtrConstructors) {
using TestPtr = xoj::util::GObjectSPtr<TestObject>;
EXPECT_EQ(TestObjectCount, 0);
{
TestPtr t(TEST_OBJECT(g_object_new(TEST_OBJECT_TYPE, nullptr)), xoj::util::adopt);
EXPECT_FALSE(g_object_is_floating(t.get()));
EXPECT_EQ(TestObjectCount, 1);
}
EXPECT_EQ(TestObjectCount, 0);
{
TestObject* t = TEST_OBJECT(g_object_new(TEST_OBJECT_TYPE, nullptr));
EXPECT_FALSE(g_object_is_floating(t));
g_object_force_floating(G_OBJECT(t));
EXPECT_TRUE(g_object_is_floating(t));
EXPECT_EQ(TestObjectCount, 1);
TestPtr t1(t, xoj::util::adopt); // Adopt a floating ref
EXPECT_EQ(t1.get(), t);
EXPECT_FALSE(g_object_is_floating(t1.get()));
}
EXPECT_EQ(TestObjectCount, 0);
{
TestObject* t = TEST_OBJECT(g_object_new(TEST_OBJECT_TYPE, nullptr));
EXPECT_EQ(TestObjectCount, 1);
TestPtr t1(t, xoj::util::ref);
g_object_unref(t);
EXPECT_EQ(TestObjectCount, 1);
}
EXPECT_EQ(TestObjectCount, 0);
}
TEST(UtilsRAII, testGObjectSPtrReset) {
using TestPtr = xoj::util::GObjectSPtr<TestObject>;
EXPECT_EQ(TestObjectCount, 0);
{
TestPtr t;
t.reset(TEST_OBJECT(g_object_new(TEST_OBJECT_TYPE, nullptr)), xoj::util::adopt);
EXPECT_FALSE(g_object_is_floating(t.get()));
EXPECT_EQ(TestObjectCount, 1);
}
EXPECT_EQ(TestObjectCount, 0);
{
TestObject* t = TEST_OBJECT(g_object_new(TEST_OBJECT_TYPE, nullptr));
EXPECT_FALSE(g_object_is_floating(t));
g_object_force_floating(G_OBJECT(t));
EXPECT_TRUE(g_object_is_floating(t));
EXPECT_EQ(TestObjectCount, 1);
TestPtr t1;
t1.reset(t, xoj::util::adopt); // Adopt a floating ref
EXPECT_EQ(t1.get(), t);
EXPECT_FALSE(g_object_is_floating(t1.get()));
}
EXPECT_EQ(TestObjectCount, 0);
{
TestObject* t = TEST_OBJECT(g_object_new(TEST_OBJECT_TYPE, nullptr));
EXPECT_EQ(TestObjectCount, 1);
TestPtr t1;
t1.reset(t, xoj::util::ref);
g_object_unref(t);
EXPECT_EQ(TestObjectCount, 1);
}
EXPECT_EQ(TestObjectCount, 0);
}
| 9,831
|
C++
|
.cpp
| 277
| 28.33213
| 115
| 0.590431
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,313
|
PathTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/PathTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <gtest/gtest.h>
#include "util/PathUtil.h"
#include "filesystem.h"
using namespace std;
TEST(UtilPath, testUnsupportedUri) {
auto a = Util::fromUri("http://localhost/test.txt");
EXPECT_EQ(true, !a);
auto b = Util::fromUri("file://invalid");
EXPECT_EQ(true, !b);
}
TEST(UtilPath, testPathFromUri) {
auto b = Util::fromUri("file:///tmp/test.txt");
EXPECT_EQ(false, !b);
EXPECT_EQ(G_DIR_SEPARATOR_S + string("tmp") + G_DIR_SEPARATOR_S + string("test.txt"), b->string());
}
TEST(UtilPath, testPathIsChildOf) {
EXPECT_TRUE(Util::isChildOrEquivalent("C:/Users/Subdir", "C:/Users"));
EXPECT_TRUE(Util::isChildOrEquivalent("C:/Users/Subdir", "C:/Users/"));
EXPECT_TRUE(Util::isChildOrEquivalent("C:/Users/Subdir/", "C:/Users/"));
EXPECT_TRUE(Util::isChildOrEquivalent("C:/Users/Subdir/", "C:/Users"));
EXPECT_TRUE(Util::isChildOrEquivalent("C:/Users/Subdir/", "C:/Users/Subdir/"));
EXPECT_TRUE(Util::isChildOrEquivalent("D:/Users/Subdir", "D:/Users"));
EXPECT_TRUE(!Util::isChildOrEquivalent("D:/Users/Subdir", "D:/users"));
EXPECT_TRUE(!Util::isChildOrEquivalent("C:/A/B", "C:/B/A"));
EXPECT_TRUE(!Util::isChildOrEquivalent("C:/B/A", "C:/A/B"));
EXPECT_TRUE(!Util::isChildOrEquivalent("D:/Users/Subdir", "C:/Users"));
EXPECT_TRUE(!Util::isChildOrEquivalent("D:/Users/Subdir", "C:/Users"));
// Todo add a symlink test
}
TEST(UtilPath, testClearExtensions) {
// These tests use the preferred separator (i.e. "\\" on Windows and "/" on POSIX)
auto a = fs::path("C:") / "test" / "abc" / "xyz.txt";
fs::path old_path(a);
Util::clearExtensions(a);
EXPECT_EQ(old_path.string(), a.string());
a = fs::path("C:") / "test" / "abc" / "xyz";
old_path = a;
a += ".xopp";
Util::clearExtensions(a);
EXPECT_EQ(old_path.string(), a.string());
// The following tests use the generic separator which works on all systems
auto b = fs::path("/test/asdf.TXT");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.TXT"), b.string());
Util::clearExtensions(b, ".txt");
EXPECT_EQ(string("/test/asdf"), b.string());
b = fs::path("/test/asdf.asdf/asdf");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.asdf/asdf"), b.string());
b = fs::path("/test/asdf.PDF");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.PDF"), b.string());
Util::clearExtensions(b, ".pdf");
EXPECT_EQ(string("/test/asdf"), b.string());
b = fs::path("/test/asdf.PDF.xoj");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.PDF"), b.string());
b = fs::path("/test/asdf.PDF.xoj");
Util::clearExtensions(b, ".Pdf");
EXPECT_EQ(string("/test/asdf"), b.string());
b = fs::path("/test/asdf.pdf.pdf");
Util::clearExtensions(b, ".pdf");
EXPECT_EQ(string("/test/asdf.pdf"), b.string());
b = fs::path("/test/asdf.xopp.xopp");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.xopp"), b.string());
b = fs::path("/test/asdf.PDF.xopp");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.PDF"), b.string());
b = fs::path("/test/asdf.SVG.xopp");
Util::clearExtensions(b, ".svg");
EXPECT_EQ(string("/test/asdf"), b.string());
b = fs::path("/test/asdf.xoj");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf"), b.string());
b = fs::path("/test/asdf.xopp");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf"), b.string());
b = fs::path("/test/asdf.pdf");
Util::clearExtensions(b);
EXPECT_EQ(string("/test/asdf.pdf"), b.string());
}
| 3,783
|
C++
|
.cpp
| 92
| 36.684783
| 103
| 0.634279
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,314
|
RangeTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/RangeTest.cpp
|
#include <array>
#include <gtest/gtest.h>
#include "util/Range.h"
namespace {
struct TestData {
TestData(const Range& rg, bool isEmpty, bool isValid): rg(rg), isEmpty(isEmpty), isValid(isValid) {}
Range rg;
bool isEmpty;
bool isValid;
};
std::array<TestData, 5> testData = {
//
TestData(Range(), true, false), //
TestData(Range(1.0, 0.0), false, true), //
TestData(Range(0.0, 0.0, 1.0, 1.0), false, true), //
TestData(Range(0.0, 0.0, -1.0, 1.0), false, false), //
TestData(Range(0.0, 0.0, 1.0, 0.0), false, true) //
};
bool equal(const Range& r1, const Range& r2) {
return r1.minX == r2.minX && r1.minY == r2.minY && r1.maxX == r2.maxX && r1.maxY == r2.maxY;
}
}; // namespace
TEST(UtilRange, testEmptyValid) {
for (auto& d: testData) {
EXPECT_EQ(d.rg.empty(), d.isEmpty);
EXPECT_EQ(d.rg.isValid(), d.isValid);
}
}
TEST(UtilRange, testUnite) {
Range emptyRange;
for (auto& d: testData) {
EXPECT_TRUE(equal(d.rg.unite(emptyRange), d.rg));
}
// intersecting ranges
EXPECT_TRUE(equal(Range(0.0, -1.0, 1.0, 2.0).unite(Range(0.5, 1.0, 0.6, 3.0)), Range(0.0, -1.0, 1.0, 3.0)));
// subrange
EXPECT_TRUE(equal(Range(0.0, -1.0, 1.0, 2.0).unite(Range(0.5, 1.0, 0.6, 1.5)), Range(0.0, -1.0, 1.0, 2.0)));
// disjoint ranges
EXPECT_TRUE(equal(Range(0.0, -1.0, 1.0, 2.0).unite(Range(1.5, 3.0, 2.0, 4.0)), Range(0.0, -1.0, 2.0, 4.0)));
}
TEST(UtilRange, testIntersect) {
Range emptyRange;
for (auto& d: testData) {
EXPECT_TRUE(d.rg.intersect(emptyRange).empty());
}
// intersecting ranges
EXPECT_TRUE(equal(Range(0.0, -1.0, 1.0, 2.0).intersect(Range(0.5, 1.0, 0.6, 3.0)), Range(0.5, 1.0, 0.6, 2.0)));
// subrange
EXPECT_TRUE(equal(Range(0.0, -1.0, 1.0, 2.0).intersect(Range(0.5, 1.0, 0.6, 1.5)), Range(0.5, 1.0, 0.6, 1.5)));
// disjoint ranges
EXPECT_TRUE(Range(0.0, -1.0, 1.0, 2.0).intersect(Range(1.5, 3.0, 2.0, 4.0)).empty());
}
| 2,050
|
C++
|
.cpp
| 52
| 34.769231
| 115
| 0.574447
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,315
|
IntervalTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/IntervalTest.cpp
|
#include <array>
#include <map>
#include <gtest/gtest.h>
#include "util/UnionOfIntervals.h"
TEST(UtilIntervals, testInterval) {
std::array<Interval<double>, 4> intervals = {Interval<double>::getInterval(12.34, 1),
Interval<double>::getInterval(0, 2), Interval<double>(3, 4),
Interval<double>(-0.2, 3)};
// Test intersection
std::map<std::pair<size_t, size_t>, std::optional<Interval<double>>> intersections = {
{{0, 1}, Interval<double>(1, 2)}, {{0, 2}, Interval<double>(3, 4)}, {{0, 3}, Interval<double>(1, 3)},
{{1, 2}, std::nullopt}, {{1, 3}, Interval<double>(0, 2)}, {{2, 3}, std::nullopt}};
for (size_t i = 0; i < intervals.size() - 1; ++i) {
for (size_t j = i + 1; j < intervals.size(); ++j) {
auto intersection = intersections[{i, j}];
auto intersectionAB = intervals[i].intersect(intervals[j]);
EXPECT_EQ(intersectionAB.has_value(), intersection.has_value());
auto intersectionBA = intervals[j].intersect(intervals[i]);
EXPECT_EQ(intersectionBA.has_value(), intersection.has_value());
if (intersection.has_value()) {
EXPECT_EQ(intersectionBA.value().min, intersection.value().min);
EXPECT_EQ(intersectionBA.value().max, intersection.value().max);
EXPECT_EQ(intersectionAB.value().min, intersection.value().min);
EXPECT_EQ(intersectionAB.value().max, intersection.value().max);
}
}
}
// Test isContainedIn
std::array<std::array<bool, 4>, 4> isContainedIn = {
std::array<bool, 4>{true, false, false, false}, std::array<bool, 4>{false, true, false, true},
std::array<bool, 4>{true, false, true, false}, std::array<bool, 4>{false, false, false, true}};
for (size_t i = 0; i < intervals.size(); ++i) {
for (size_t j = 0; j < intervals.size(); ++j) {
EXPECT_EQ(isContainedIn[i][j], intervals[i].isContainedIn(intervals[j]));
}
}
// Test IntervalIteratable
std::vector<Interval<double>> expectedResults = {{1, 12.34}, {0, 2}, {3, 4}, {-0.2, 3}};
size_t i = 0;
for (auto interval: expectedResults) {
EXPECT_EQ(interval.min, intervals[i].min);
EXPECT_EQ(interval.max, intervals[i].max);
++i;
}
// Test envelop
std::array<Interval<double>, 4> envelop2point5 = {Interval<double>{1, 12.34}, Interval<double>{0, 2.5},
Interval<double>{2.5, 4}, Interval<double>{-0.2, 3}};
for (size_t i = 0; i < intervals.size(); ++i) {
intervals[i].envelop(2.5);
EXPECT_EQ(intervals[i].min, envelop2point5[i].min);
EXPECT_EQ(intervals[i].max, envelop2point5[i].max);
}
}
TEST(UtilIntervals, testUnionOfIntervals) {
std::vector<double> bounds = {0, 1, 3, 5, 7, 10};
UnionOfIntervals<double> intervals;
intervals.appendData(bounds);
{ // Test clone
auto clone = intervals.cloneToIntervalVector();
EXPECT_TRUE(bounds.size() % 2 == 0);
EXPECT_EQ(clone.size(), bounds.size() / 2);
auto it = bounds.begin();
for (auto& interval: clone) {
EXPECT_EQ(interval.min, *it);
++it;
EXPECT_EQ(interval.max, *it);
++it;
}
}
{ // Test unite
UnionOfIntervals<double> intervals2;
std::vector<double> bounds2 = {-2, -1, -0.5, 0.5, 2.5, 3.5, 4, 8};
intervals2.appendData(bounds2);
intervals2.unite(intervals.getData());
auto unionOfTheTwo = intervals2.cloneToIntervalVector();
std::vector<Interval<double>> expectedRes = {{-2, -1}, {-0.5, 1}, {2.5, 10}};
EXPECT_EQ(expectedRes.size(), unionOfTheTwo.size());
auto it = unionOfTheTwo.begin();
for (auto& interval: expectedRes) {
EXPECT_EQ(interval.min, it->min);
EXPECT_EQ(interval.max, it->max);
++it;
}
}
{ // Test intersect
UnionOfIntervals<double> intervals2;
std::vector<double> bounds2 = {-2, -1, -0.5, 0.5, 2.5, 3.5, 4, 8};
intervals2.appendData(bounds2);
intervals2.intersect(intervals.getData());
auto interOfTheTwo = intervals2.cloneToIntervalVector();
std::vector<Interval<double>> expectedRes = {{0, 0.5}, {3, 3.5}, {4, 5}, {7, 8}};
EXPECT_EQ(expectedRes.size(), interOfTheTwo.size());
auto it = interOfTheTwo.begin();
for (auto& interval: expectedRes) {
EXPECT_EQ(interval.min, it->min);
EXPECT_EQ(interval.max, it->max);
++it;
}
}
}
| 4,757
|
C++
|
.cpp
| 100
| 37.66
| 113
| 0.566135
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,316
|
TinySmallVectorTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/TinySmallVectorTest.cpp
|
#include <array>
#include <map>
#include <gtest/gtest.h>
#include "util/SmallVector.h"
#include "util/TinyVector.h"
namespace {
class TestData {
public:
TestData() { nbData++; };
~TestData() { nbData--; };
TestData(double t, bool duplicate): t(t) {
if (duplicate) {
u = t;
}
nbData++;
}
TestData(double t, double u): t(t), u(u) { nbData++; }
TestData(const TestData& other): t(other.t), u(other.u) { nbData++; }
TestData(TestData&& other): t(other.t), u(other.u) { nbData++; }
TestData& operator=(const TestData& other) {
t = other.t;
u = other.u;
return *this;
}
TestData& operator=(TestData&& other) {
t = other.t;
u = other.u;
return *this;
}
double t = 0.0;
double u = 0.0;
bool operator==(const TestData& other) const { return t == other.t && u == other.u; }
static int nbData;
};
int TestData::nbData = 0;
}; // namespace
TEST(UtilsVectors, testTinyVector) {
TestData::nbData = 0;
{ // scope for vec. To test destructor after.
TinyVector<TestData, 5> vec;
EXPECT_EQ(vec.size(), 0);
EXPECT_TRUE(vec.empty());
{ // d1 scope, for a correct TestData::nbData
TestData d1(1.0, 2.0);
vec.push_back(d1);
EXPECT_EQ(vec.size(), 1);
vec.push_back(std::move(d1));
EXPECT_EQ(vec.size(), 2);
vec.emplace_back(d1);
EXPECT_EQ(vec.size(), 3);
vec.emplace_back(3.0, true);
EXPECT_EQ(vec.size(), 4);
vec.emplace_back(4.0, false);
EXPECT_EQ(vec.size(), 5);
}
EXPECT_EQ(TestData::nbData, 5);
EXPECT_EQ(vec[0], vec.front());
EXPECT_EQ(vec[0], TestData(1.0, 2.0));
EXPECT_EQ(vec[1], TestData(1.0, 2.0));
EXPECT_EQ(vec[2], TestData(1.0, 2.0));
EXPECT_EQ(vec[3], TestData(3.0, 3.0));
EXPECT_EQ(vec[4], TestData(4.0, 0.0));
EXPECT_EQ(vec.back(), vec[4]);
// try {
// vec.push_back(d1);
// FAIL() << "TinyVector should have thrown std::length_error";
// } catch (const std::length_error& e) {}
//
// try {
// vec.push_back(std::move(d1));
// FAIL() << "TinyVector should have thrown std::length_error";
// } catch (const std::length_error& e) {}
//
// try {
// vec.emplace_back(d1);
// FAIL() << "TinyVector should have thrown std::length_error";
// } catch (const std::length_error& e) {}
vec.pop_back();
EXPECT_EQ(vec.size(), 4);
EXPECT_EQ(TestData::nbData, 4);
// Test range loop
for (auto& d: vec) { d.u += d.t; }
EXPECT_EQ(vec[0], TestData(1.0, 3.0));
EXPECT_EQ(vec[1], TestData(1.0, 3.0));
EXPECT_EQ(vec[2], TestData(1.0, 3.0));
EXPECT_EQ(vec[3], TestData(3.0, 6.0));
// Test clear
vec.clear();
EXPECT_TRUE(vec.empty());
EXPECT_EQ(vec.size(), 0);
EXPECT_EQ(TestData::nbData, 0);
vec.emplace_back(3.0, true);
vec.emplace_back(4.0, false);
vec.emplace_back(5.0, true);
vec.emplace_back(6.0, false);
EXPECT_EQ(vec.size(), 4);
EXPECT_EQ(TestData::nbData, 4);
{ // Test copy/move assignment
auto vec2 = vec;
EXPECT_EQ(vec2.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 8);
auto vec3 = std::move(vec2);
EXPECT_TRUE(vec2.empty());
EXPECT_EQ(vec3.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 8);
// Self assignment
auto* vec4 = &vec3;
vec3 = *vec4;
EXPECT_EQ(vec3.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 8);
vec3 = std::move(*vec4);
EXPECT_EQ(vec3.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 8);
// Swap
vec2.emplace_back(1.0, 2.0);
std::swap(vec2, vec3);
EXPECT_EQ(vec2.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(vec3.size(), 1);
EXPECT_EQ(TestData::nbData, 9);
}
EXPECT_EQ(TestData::nbData, 4);
{ // Test copy/move constructor
auto vec2(vec);
EXPECT_EQ(vec2.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 8);
auto vec3(std::move(vec2));
EXPECT_TRUE(vec2.empty());
EXPECT_EQ(vec3.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 8);
}
EXPECT_EQ(TestData::nbData, 4);
} // end of scope for vec
EXPECT_EQ(TestData::nbData, 0);
}
TEST(UtilsVectors, testSmallVectorPushPop) {
TestData::nbData = 0;
SmallVector<TestData, 3> vec;
EXPECT_EQ(vec.size(), 0);
EXPECT_TRUE(vec.empty());
TestData d1(1.0, 2.0);
TestData d2(-1.0, -2.0);
TestData d3(-1.0, 2.0);
EXPECT_EQ(TestData::nbData, 0 + 3); // 3 for d1, d2 and d3
vec.push_back(d1);
EXPECT_EQ(vec.size(), 1);
vec.push_back(std::move(d2));
EXPECT_EQ(vec.size(), 2);
vec.emplace_back(d3);
EXPECT_EQ(vec.size(), 3);
EXPECT_EQ(TestData::nbData, 3 + 3); // 3 for d1, d2 and d3
vec.emplace_back(3.0, true); // Move from stack to heap
EXPECT_EQ(vec.size(), 4);
vec.emplace_back(4.0, false);
EXPECT_EQ(vec.size(), 5);
EXPECT_EQ(TestData::nbData, 5 + 3); // 3 for d1, d2 and d3
EXPECT_EQ(vec[0], vec.front());
EXPECT_EQ(vec[0], d1);
EXPECT_EQ(vec[1], d2);
EXPECT_EQ(vec[2], d3);
EXPECT_EQ(vec[3], TestData(3.0, 3.0));
EXPECT_EQ(vec[4], TestData(4.0, 0.0));
EXPECT_EQ(vec.back(), vec[4]);
vec.pop_back();
EXPECT_EQ(vec.size(), 4);
EXPECT_EQ(TestData::nbData, 4 + 3);
vec.pop_back(); // Move from heap to stack
EXPECT_EQ(vec.size(), 3);
EXPECT_EQ(TestData::nbData, 3 + 3); // 3 for d1, d2 and d3
vec.pop_back();
EXPECT_EQ(vec.size(), 2);
EXPECT_EQ(vec.front(), d1);
EXPECT_EQ(vec.back(), d2);
// Loop in stack
for (auto& d: vec) { d.t += d.u; }
EXPECT_EQ(vec.front(), TestData(3.0, 2.0));
EXPECT_EQ(vec.back(), TestData(-3.0, -2.0));
EXPECT_EQ(TestData::nbData, 3 + 2);
vec.emplace_back(d3);
EXPECT_EQ(vec.size(), 3);
vec.emplace_back(3.0, true);
EXPECT_EQ(vec.size(), 4);
vec.emplace_back(4.0, false);
EXPECT_EQ(vec.size(), 5);
EXPECT_EQ(TestData::nbData, 5 + 3); // 3 for d1, d2 and d3
// Loop in heap
for (auto& d: vec) { d.u += d.t; }
EXPECT_EQ(vec[0], TestData(3.0, 5.0));
EXPECT_EQ(vec[1], TestData(-3.0, -5.0));
EXPECT_EQ(vec[2], TestData(-1.0, 1.0));
EXPECT_EQ(vec[3], TestData(3.0, 6.0));
EXPECT_EQ(vec[4], TestData(4.0, 4.0));
vec.clear();
EXPECT_TRUE(vec.empty());
EXPECT_EQ(vec.size(), 0);
EXPECT_EQ(TestData::nbData, 0 + 3); // 3 for d1, d2 and d3
}
TEST(UtilsVectors, testSmallVectorCopyMove) {
TestData::nbData = 0;
{ // copy and move assignments in stack
SmallVector<TestData, 3> vec = {TestData(3.0, 1.0), TestData(-3.0, -3.0)};
EXPECT_EQ(vec.size(), 2);
EXPECT_EQ(TestData::nbData, 2);
auto vec2 = vec;
EXPECT_EQ(vec2.size(), 2);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2);
auto vec3 = std::move(vec2);
EXPECT_EQ(vec2.size(), 0);
EXPECT_EQ(vec3.size(), 2);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2);
// Self assignment
auto* vec4 = &vec3;
vec3 = *vec4;
EXPECT_EQ(vec3.size(), 2);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2);
vec3 = std::move(*vec4);
EXPECT_EQ(vec3.size(), 2);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2);
// Swap
vec2.emplace_back(1.0, true);
std::swap(vec2, vec3);
EXPECT_EQ(vec2.size(), 2);
EXPECT_EQ(vec3.size(), 1);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2 + 1);
}
{ // copy and move constructor in stack
SmallVector<TestData, 3> vec{TestData(3.0, 1.0), TestData(-3.0, -3.0)};
EXPECT_EQ(vec.size(), 2);
EXPECT_EQ(TestData::nbData, 2);
SmallVector<TestData, 3> vec2(vec);
EXPECT_EQ(vec2.size(), 2);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2);
SmallVector<TestData, 3> vec3(std::move(vec2));
EXPECT_EQ(vec2.size(), 0);
EXPECT_EQ(vec3.size(), 2);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 2 + 2);
}
{ // assignment in heap
SmallVector<TestData, 3> vec = {TestData(1.0, 2.0), TestData(1.0, 3.0), TestData(2.0, 2.0), TestData(4.0, 2.0),
TestData(-1.0, 2.0)};
EXPECT_EQ(TestData::nbData, 5);
auto vec2 = vec;
EXPECT_EQ(vec2.size(), 5);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5);
auto vec3 = std::move(vec2);
EXPECT_EQ(vec2.size(), 0);
EXPECT_EQ(vec3.size(), 5);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5);
// Self assignment
auto* vec4 = &vec3;
vec3 = *vec4;
EXPECT_EQ(vec3.size(), 5);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5);
vec3 = std::move(*vec4);
EXPECT_EQ(vec3.size(), 5);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5);
// Swap
vec2.emplace_back(-1.0, true);
std::swap(vec2, vec3); // stack to heap
EXPECT_EQ(vec2.size(), 5);
EXPECT_EQ(vec3.size(), 1);
EXPECT_EQ(vec3.front(), TestData(-1.0, true));
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5 + 1);
std::swap(vec2, vec3); // heap to stack
EXPECT_EQ(vec2.size(), 1);
EXPECT_EQ(vec3.size(), 5);
EXPECT_EQ(vec2.front(), TestData(-1.0, true));
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5 + 1);
vec2.emplace_back(2.0, 3.0);
vec2.emplace_back(3.0, -3.0);
vec2.emplace_back(4.0, 5.0);
EXPECT_EQ(vec2.size(), 4);
EXPECT_EQ(TestData::nbData, 5 + 5 + 4);
std::swap(vec2, vec3); // heap to heap
EXPECT_EQ(vec2.size(), 5);
EXPECT_EQ(vec3.size(), 4);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5 + 4);
}
{ // copy and move constructor in heap
SmallVector<TestData, 3> vec{TestData(1.0, 2.0), TestData(1.0, 3.0), TestData(2.0, 2.0), TestData(4.0, 2.0),
TestData(-1.0, 2.0)};
EXPECT_EQ(TestData::nbData, 5);
SmallVector<TestData, 3> vec2(vec);
EXPECT_EQ(vec2.size(), 5);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec2.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5);
SmallVector<TestData, 3> vec3(std::move(vec2));
EXPECT_EQ(vec2.size(), 0);
EXPECT_EQ(vec3.size(), 5);
EXPECT_TRUE(std::equal(vec.begin(), vec.end(), vec3.begin()));
EXPECT_EQ(TestData::nbData, 5 + 5);
}
EXPECT_EQ(TestData::nbData, 0);
}
| 12,354
|
C++
|
.cpp
| 314
| 30.949045
| 119
| 0.537499
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,317
|
XojPreviewExtractorTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/XojPreviewExtractorTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <cstdlib>
#include <ctime>
#include <gtest/gtest.h>
#include "util/XojPreviewExtractor.h"
#include "config-test.h"
using namespace std;
TEST(UtilXojPreviewExtractor, testNonExistingFile) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("THIS FILE DOES NOT EXIST.xoj"));
EXPECT_EQ(PREVIEW_RESULT_COULD_NOT_OPEN_FILE, result);
}
TEST(UtilXojPreviewExtractor, testExtensionCheck) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("test.xoi"));
EXPECT_EQ(PREVIEW_RESULT_BAD_FILE_EXTENSION, result);
}
TEST(UtilXojPreviewExtractor, testLoadGzipped) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("preview-test.xoj"));
EXPECT_EQ(PREVIEW_RESULT_IMAGE_READ, result);
gsize dataLen = 0;
unsigned char* imageData = extractor.getData(dataLen);
EXPECT_EQ(string("CppUnitTestString"), string((char*)imageData, (size_t)dataLen));
}
TEST(UtilXojPreviewExtractor, testLoadGzipped2) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("preview-test2.xoj"));
EXPECT_EQ(PREVIEW_RESULT_IMAGE_READ, result);
gsize dataLen = 0;
extractor.getData(dataLen);
EXPECT_EQ((std::string::size_type)2856, dataLen);
}
TEST(UtilXojPreviewExtractor, testLoad1Unzipped) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("preview-test.unzipped.xoj"));
EXPECT_EQ(PREVIEW_RESULT_IMAGE_READ, result);
gsize dataLen = 0;
unsigned char* imageData = extractor.getData(dataLen);
EXPECT_EQ(string("CppUnitTestString"), string((char*)imageData, (size_t)dataLen));
}
TEST(UtilXojPreviewExtractor, testLoad1Zipped) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("packaged_xopp/testPreview.xopp"));
EXPECT_EQ(PREVIEW_RESULT_IMAGE_READ, result);
gsize dataLen = 0;
unsigned char* imageData = extractor.getData(dataLen);
EXPECT_EQ(string("CppUnitTestString \n"), string((char*)imageData, (size_t)dataLen));
}
TEST(UtilXojPreviewExtractor, testLoad2Zipped) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("packaged_xopp/testPreview2.xopp"));
EXPECT_EQ(PREVIEW_RESULT_IMAGE_READ, result);
gsize dataLen = 0;
extractor.getData(dataLen);
EXPECT_EQ((std::string::size_type)804, dataLen);
}
TEST(UtilXojPreviewExtractor, testNoPreview) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("preview-test-no-preview.unzipped.xoj"));
EXPECT_EQ(PREVIEW_RESULT_NO_PREVIEW, result);
}
TEST(UtilXojPreviewExtractor, testInvalidFile) {
XojPreviewExtractor extractor;
PreviewExtractResult result = extractor.readFile(GET_TESTFILE("preview-test-invalid.xoj"));
EXPECT_EQ(PREVIEW_RESULT_ERROR_READING_PREVIEW, result);
}
| 3,199
|
C++
|
.cpp
| 76
| 38.368421
| 107
| 0.770773
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,318
|
SaveNameUtilsTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/SaveNameUtilsTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <gtest/gtest.h>
#include "util/SaveNameUtils.h"
TEST(SaveNameUtils, testWildcardExpansion) {
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("", "defaultpath"), "");
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("%{name}}%{name}", "x"), "x}x");
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("%{name}", "defaultpath.pdf"), "defaultpath");
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("%{", "defaultpath"), "%{");
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("%{name%{name}}x", ""), "}x");
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("\\%\\{name%{name}}x", ""), "\\%\\{name}x");
EXPECT_EQ(SaveNameUtils::parseFilenameFromWildcardString("%{name}", " %{name}"), " %{name}");
}
| 966
|
C++
|
.cpp
| 21
| 43.047619
| 107
| 0.697131
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,319
|
ColorTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/ColorTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <cstdint>
#include <gtest/gtest.h>
#include "util/Color.h"
using namespace std;
bool operator==(GdkRGBA const& lhs, GdkRGBA const& rhs) noexcept {
auto tieer = [](GdkRGBA const& val) { return std::tie(val.red, val.blue, val.green, val.alpha); };
return tieer(lhs) == tieer(rhs);
}
std::ostream& operator<<(std::ostream& os, GdkRGBA const& val) {
return os << "GdkRGBA{" << val.red << "," << val.green << "," << val.blue << "," << val.alpha << "}";
}
TEST(UtilColor, testColorToRGB) {
Color color1{0U};
Color color2{0xffffffU};
Color color3{0x7f7f7fU};
Color color4{0x808080U};
auto rgb1 = GdkRGBA{0.0, 0.0, 0.0, 1.0};
auto rgb2 = GdkRGBA{1, 1, 1, 1.0};
auto rgb3 = GdkRGBA{0.5, 0.5, 0.5, 1.0};
auto rgb_t1 = Util::rgb_to_GdkRGBA(color1);
EXPECT_EQ(rgb1, rgb_t1);
auto rgb_t2 = Util::rgb_to_GdkRGBA(color2);
EXPECT_EQ(rgb2, rgb_t2);
auto rgb_t4 = Util::rgb_to_GdkRGBA(color4);
auto rgb_t3 = Util::rgb_to_GdkRGBA(color3);
auto rgb_t5 = GdkRGBA{(rgb_t3.red + rgb_t4.red) / 2, (rgb_t3.green + rgb_t4.green) / 2,
(rgb_t3.blue + rgb_t4.blue) / 2, 1};
EXPECT_EQ(rgb3, rgb_t5);
}
TEST(UtilColor, testColorToRGBAndBack) {
for (size_t i = 0U; i < 256U; ++i) {
uint8_t ii = static_cast<uint8_t>(i);
Color color{ii, ii, ii};
Color color2{ii, ii, ii, ii};
EXPECT_EQ(color, Util::GdkRGBA_to_rgb(Util::rgb_to_GdkRGBA(color)));
EXPECT_EQ(color2, Util::GdkRGBA_to_argb(Util::argb_to_GdkRGBA(color2)));
}
}
| 1,727
|
C++
|
.cpp
| 48
| 31.5625
| 105
| 0.61976
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,320
|
ObjectIOStreamTest.cpp
|
xournalpp_xournalpp/test/unit_tests/util/ObjectIOStreamTest.cpp
|
#include <array>
#include <cstdint>
#include <random>
#include <string>
#include <tuple>
#include <vector>
#include <cairo.h>
#include <gtest/gtest.h>
#include "model/Stroke.h"
#include "util/serializing/BinObjectEncoding.h"
#include "util/serializing/HexObjectEncoding.h"
#include "util/serializing/ObjectInputStream.h"
#include "util/serializing/ObjectOutputStream.h"
#include "util/serializing/Serializable.h"
template <typename T>
std::string serializeDataVector(const std::vector<T>& data) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeData(data);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeImage(cairo_surface_t* surf) {
ObjectOutputStream outStream(new BinObjectEncoding);
std::string data{reinterpret_cast<char*>(cairo_image_surface_get_data(surf))};
outStream.writeImage(data);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeString(const std::string& str) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeString(str);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeSizeT(size_t x) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeSizeT(x);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeDouble(double x) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeDouble(x);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeInt(int x) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeInt(x);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeUInt(uint32_t x) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeUInt(x);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
std::string serializeStroke(Stroke& stroke) {
ObjectOutputStream outStream(new BinObjectEncoding);
stroke.serialize(outStream);
auto outStr = outStream.getStr();
auto resStr = std::string{outStr->str, outStr->len};
g_string_free(outStr, true);
return resStr;
}
template <typename T>
void testReadDataType(const std::vector<T>& data) {
std::string str = serializeDataVector<T>(data);
ObjectInputStream stream;
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
std::vector<T> outputData;
stream.readData(outputData);
EXPECT_EQ(data, outputData);
}
TEST(UtilObjectIOStream, testReadData) {
testReadDataType(std::vector<char>{0, 42, -42});
testReadDataType(std::vector<long>{0, 42, -42});
testReadDataType(std::vector<long long>{0, 420000000000, -42000000000});
testReadDataType(std::vector<float>{0, 42., -42.});
testReadDataType(std::vector<double>{0, 42., -42.});
struct Data {
bool operator==(const Data& o) const { return s == o.s && f == o.f && b == o.b; }
size_t s;
float f;
bool b;
};
testReadDataType(std::vector<Data>{{243254, 0.4534314213f, true}, {2, -4243213.32f, false}});
}
TEST(UtilObjectIOStream, testReadImage) {
// Generate a "random" image and serialize/deserialize it.
std::mt19937 gen(4242);
std::uniform_int_distribution<uint16_t> distrib(0, 255);
const cairo_format_t format = CAIRO_FORMAT_ARGB32;
cairo_surface_t* surface = cairo_image_surface_create(format, 800, 800);
unsigned char* surfaceData = cairo_image_surface_get_data(surface);
int width = cairo_image_surface_get_width(surface);
int height = cairo_image_surface_get_height(surface);
for (int i = 0; i < width * height * 4; ++i) { surfaceData[i] = distrib(gen); }
std::string strSurface = serializeImage(surface);
ObjectInputStream stream;
EXPECT_TRUE(stream.read(&strSurface[0], strSurface.size() + 1));
std::string outputStr = stream.readImage();
cairo_surface_t* outputSurface =
cairo_image_surface_create_for_data(reinterpret_cast<unsigned char*>(outputStr.data()), format, width,
height, cairo_format_stride_for_width(format, width));
EXPECT_NE(outputSurface, nullptr);
int widthOutput = cairo_image_surface_get_width(outputSurface);
int heightOutput = cairo_image_surface_get_height(outputSurface);
unsigned char* outputData = cairo_image_surface_get_data(surface);
EXPECT_EQ(width, widthOutput);
EXPECT_EQ(height, heightOutput);
for (int i = 0; i < width * height * 4; ++i) { EXPECT_EQ(surfaceData[i], outputData[i]); }
cairo_surface_destroy(surface);
cairo_surface_destroy(outputSurface);
}
TEST(UtilObjectIOStream, testReadString) {
std::vector<std::string> stringToTest{
"", "Hello World", XML_VERSION_STR, "1337",
"Laborum beatae sit at. Tempore ex odio et non et iste et. Deleniti magni beatae quod praesentium dicta quas ducimus hic. Nemo vel est saepe voluptatibus. Sunt eveniet aut saepe consequatur fuga ad molestias.\n \
Culpa nulla saepe alias magni nemo magni. Sed sit sint repellat doloremque. Quo ipsum debitis quos impedit. Omnis expedita veritatis nihil sint et itaque possimus. Nobis est fugit vel omnis. Dolores architecto laudantium nihil rerum."};
std::vector<std::pair<std::string, std::string>> testData;
testData.reserve(stringToTest.size());
for (auto&& str: stringToTest) { testData.emplace_back(serializeString(str), str); }
for (auto&& data: testData) {
std::string& str = data.first;
std::string& x = data.second;
ObjectInputStream stream;
// The +1 stands for the \0 character
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
std::string output = stream.readString();
EXPECT_EQ(x, output);
}
}
TEST(UtilObjectIOStream, testReadSizeT) {
std::vector<size_t> sizeTToTest{0, 1, 42, 1337, 10000000, 10000000000};
std::vector<std::pair<std::string, size_t>> testData;
testData.reserve(sizeTToTest.size());
for (size_t number: sizeTToTest) { testData.emplace_back(serializeSizeT(number), number); }
for (auto&& data: testData) {
std::string& str = data.first;
size_t x = data.second;
ObjectInputStream stream;
// The +1 stands for the \0 character
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
size_t output = stream.readSizeT();
EXPECT_EQ(x, output);
}
}
TEST(UtilObjectIOStream, testReadInt) {
std::vector<int> intToTest{0, 1, -1, 42, -50000, -1337, 10000};
std::vector<std::pair<std::string, int>> testData;
testData.reserve(intToTest.size());
for (auto&& number: intToTest) { testData.emplace_back(serializeInt(number), number); }
for (auto&& data: testData) {
std::string& str = data.first;
int x = data.second;
ObjectInputStream stream;
// The +1 stands for the \0 character
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
int output = stream.readInt();
EXPECT_EQ(x, output);
}
}
TEST(UtilObjectIOStream, testReadUInt) {
std::vector<uint32_t> uintToTest{0, 1, 42, 144, 65000, 12345678, 4294967295};
std::vector<std::pair<std::string, uint32_t>> testData;
testData.reserve(uintToTest.size());
for (auto&& number: uintToTest) {
testData.emplace_back(serializeUInt(number), number);
}
for (auto&& data: testData) {
std::string& str = data.first;
uint32_t x = data.second;
ObjectInputStream stream;
// The +1 stands for the \0 character
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
uint32_t output = stream.readUInt();
EXPECT_EQ(x, output);
}
}
TEST(UtilObjectIOStream, testReadDouble) {
std::vector<double> doubleToTest{0., 0.5, 42., 46.5, -85.2, -1337, 1e50};
std::vector<std::pair<std::string, double>> testData;
testData.reserve(doubleToTest.size());
for (auto&& number: doubleToTest) { testData.emplace_back(serializeDouble(number), number); }
for (auto&& data: testData) {
std::string& str = data.first;
double dbl = data.second;
ObjectInputStream stream;
// The +1 stands for the \0 character
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
double output = stream.readDouble();
EXPECT_DOUBLE_EQ(dbl, output);
}
}
TEST(UtilObjectIOStream, testReadComplexObject) {
std::string objectName = "TestObject";
std::vector<std::string> subobjectNames = {"FirstTestSubobject", "SecondTestSubobject"};
double d = 42.;
std::string s = "Test";
int i = -1337;
size_t n = 1234567;
try {
for (size_t iterNum = 0; iterNum < subobjectNames.size(); ++iterNum) {
ObjectOutputStream outStream(new BinObjectEncoding);
outStream.writeObject(objectName.c_str());
outStream.writeDouble(d);
outStream.writeString(s);
outStream.writeObject(subobjectNames[iterNum].c_str());
if (iterNum == 0) {
outStream.writeInt(i);
} else {
outStream.writeSizeT(n);
outStream.writeSizeT(12 * n);
}
outStream.endObject();
outStream.writeDouble(-d);
outStream.endObject();
auto gstr = outStream.getStr();
std::string str(gstr->str, gstr->len);
g_string_free(gstr, true);
ObjectInputStream stream;
EXPECT_TRUE(stream.read(&str[0], str.size() + 1));
std::string outputName = stream.readObject();
EXPECT_EQ(outputName, objectName);
double outputD = stream.readDouble();
EXPECT_EQ(outputD, d);
std::string outputS = stream.readString();
EXPECT_EQ(outputS, s);
std::string nextsubname = stream.getNextObjectName();
EXPECT_EQ(nextsubname, subobjectNames[iterNum]);
std::string subname = stream.readObject();
EXPECT_EQ(subname, subobjectNames[iterNum]);
if (iterNum == 0) {
int outputI = stream.readInt();
EXPECT_EQ(outputI, i);
} else {
size_t outputN = stream.readSizeT();
EXPECT_EQ(outputN, n);
size_t output12N = stream.readSizeT();
EXPECT_EQ(output12N, 12 * n);
}
stream.endObject();
double outputMinusD = stream.readDouble();
EXPECT_EQ(outputMinusD, -d);
stream.endObject();
}
} catch (const InputStreamException& e) {
std::cerr << "InputStreamException testing complex object: " << e.what() << std::endl;
FAIL();
}
}
void assertStrokeEquality(const Stroke& stroke1, const Stroke& stroke2) {
EXPECT_EQ(stroke1.getAudioFilename(), stroke2.getAudioFilename());
EXPECT_EQ(stroke1.getToolType(), stroke2.getToolType());
EXPECT_EQ(stroke1.getFill(), stroke2.getFill());
EXPECT_EQ(stroke1.getWidth(), stroke2.getWidth());
double avgPressure1 = stroke1.getAvgPressure();
double avgPressure2 = stroke2.getAvgPressure();
if (!std::isnan(avgPressure1)) {
EXPECT_DOUBLE_EQ(avgPressure1, avgPressure2);
} else {
EXPECT_TRUE(std::isnan(avgPressure2));
}
std::vector<Point> points1 = stroke1.getPointVector();
std::vector<Point> points2 = stroke2.getPointVector();
EXPECT_EQ(points1.size(), points2.size());
for (size_t i = 0; i < points1.size(); ++i) { EXPECT_TRUE(points1[i].equalsPos(points2[i])); }
}
TEST(UtilObjectIOStream, testReadStroke) {
std::vector<Stroke> strokes(8);
// strokes[0]: empty stroke
strokes[1].addPoint(Point(42, 42));
strokes[1].addPoint(Point(42.1, 42.1));
strokes[1].addPoint(Point(1312., 8));
strokes[2].setWidth(42.);
strokes[3].setFill(245);
strokes[4].setToolType(StrokeTool::ERASER);
strokes[5].setAudioFilename("foo.mp3");
// strokes[6]: complex stroke
strokes[6].addPoint(Point(-1312., 8));
strokes[6].addPoint(Point(-42, -42));
strokes[6].addPoint(Point(42.1, -42.1));
strokes[6].setPressure({42., 1332.});
strokes[6].setWidth(1337.);
strokes[6].setFill(-1);
strokes[6].setToolType(StrokeTool::PEN);
strokes[6].setAudioFilename("assets/bar.mp3");
// strokes[7]: invalid stroke
strokes[7].addPoint(Point(0., 0.));
strokes[7].addPoint(Point(1., 2.));
strokes[7].addPoint(Point(1., 2.));
strokes[7].setPressure({42., 1332.});
strokes[7].setFill(-42);
strokes[7].setToolType(static_cast<StrokeTool::Value>(42));
strokes[7].setWidth(-1337.);
size_t i = 0;
try {
for (auto&& stroke: strokes) {
std::string out_string = serializeStroke(stroke);
ObjectInputStream istream;
istream.read(out_string.c_str(), out_string.size());
Stroke in_stroke;
in_stroke.readSerialized(istream);
assertStrokeEquality(stroke, in_stroke);
++i;
}
} catch (const InputStreamException& e) {
std::cerr << "InputStreamException testing stroke " << i << ": " << e.what() << std::endl;
FAIL();
}
}
| 13,871
|
C++
|
.cpp
| 327
| 35.691131
| 252
| 0.656076
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,321
|
ErasableStrokeTest.cpp
|
xournalpp_xournalpp/test/unit_tests/model/ErasableStrokeTest.cpp
|
#include <array>
#include <map>
#include <gtest/gtest.h>
#include "model/Stroke.h"
#include "model/eraser/ErasableStroke.h"
#include "model/eraser/ErasableStrokeOverlapTree.h"
#include "model/eraser/PaddedBox.h"
#include "util/Rectangle.h"
#include "util/SmallVector.h"
using xoj::util::Rectangle;
void assertRangesEq(const Range& r1, const Range& r2) {
ASSERT_EQ(r1.minX, r2.minX);
ASSERT_EQ(r1.minY, r2.minY);
ASSERT_EQ(r1.maxX, r2.maxX);
ASSERT_EQ(r1.maxY, r2.maxY);
}
TEST(ErasableStroke, testOverlapTree) {
// clang format off
std::vector<Point> testPath = {{0, 0}, {2, 2}, {5, 2}, {7, 4}, {3, 6}, {2, 8},
{5, 11}, {7, 10}, {7, 6}, {6, 7}, {4, 4}, {1, 3}};
// clang format on
Stroke stroke;
std::vector<Point>& strokePoints = const_cast<std::vector<Point>&>(stroke.getPointVector());
strokePoints.swap(testPath);
stroke.setWidth(2);
stroke.setFill(-1);
stroke.setToolType(StrokeTool::PEN);
std::array<ErasableStroke::OverlapTree, 6> trees;
trees[0].populate({{0, 0.0}, {3, 0.5}}, stroke);
trees[1].populate({{2, 0.5}, {5, 1.0}}, stroke);
trees[2].populate({{0, 0.5}, {0, 0.75}}, stroke);
trees[3].populate({{5, 0.0}, {9, 0.0}}, stroke);
trees[4].populate({{7, 0.5}, {9, 1.0}}, stroke);
trees[5].populate({{8, 0.0}, {10, 1.0}}, stroke);
auto makeRange = [](double x1, double y1, double width, double height) {
Range r(x1, y1);
r.addPoint(x1 + width, y1 + height);
return r;
};
// clang format off
Range overlapBoxes[2][5] = {{
makeRange(4, 2, 4, 4), // 0 and 1
makeRange(0, 0, 2.5, 2.5), // 0 and 2
makeRange(5, 5, 3, 1), // 0 and 3
makeRange(4, 3, 4, 3), // 0 and 4
makeRange(0, 2, 8, 4) // 0 and 5
},
{
Range(0, 0), // unused
Range(-10000, -10000), // 1 and 2 don't overlap
makeRange(1, 5, 7, 7), // 1 and 3
makeRange(3, 3, 5, 5), // 1 and 4
makeRange(2, 3, 6, 5) // 1 and 5
}};
// clang format on
auto singlePointRangeAtCenter = [](Range range) {
return Range(0.5 * (range.minX + range.maxX), 0.5 * (range.minY + range.maxY));
};
for (size_t i = 0; i < 2; i++) {
for (size_t j = i; j < 5; j++) {
Range range = singlePointRangeAtCenter(overlapBoxes[i][j]);
trees[i].addOverlapsToRange(trees[j + 1], 1, range);
assertRangesEq(range, overlapBoxes[i][j]);
}
}
}
TEST(ErasableStroke, testGetStrokes) {
std::array<Stroke, 3> strokes;
// Normal stroke
strokes[0].addPoint({0, 0, 2});
strokes[0].addPoint({2, 2, 2.5});
strokes[0].addPoint({5, 2, 3});
strokes[0].addPoint({7, 4, 2.5});
strokes[0].addPoint({3, 6, 2});
strokes[0].addPoint({2, 8, 1.5});
strokes[0].addPoint({5, 11, 1});
strokes[0].addPoint({7, 10, 1.5});
strokes[0].addPoint({7, 6, 2});
strokes[0].addPoint({6, 7, 2.5});
strokes[0].addPoint({4, 4, 3});
strokes[0].addPoint({1, 3});
strokes[0].setWidth(3);
strokes[0].setFill(-1);
strokes[0].setToolType(StrokeTool::PEN);
// Closed stroke. Filled. Audio
strokes[1].addPoint({0, 0, 2});
strokes[1].addPoint({2, 2, 2.5});
strokes[1].addPoint({5, 2, 3});
strokes[1].addPoint({1, 4, 2.5});
strokes[1].addPoint({3, 6, 2});
strokes[1].addPoint({0, 0});
strokes[1].setWidth(3);
strokes[1].setFill(123);
strokes[1].setToolType(StrokeTool::PEN);
strokes[1].setAudioFilename("assets/bar.mp3");
// Closed stroke. Highlighter.
strokes[2].addPoint({0, 0, 2});
strokes[2].addPoint({2, 2, 2.5});
strokes[2].addPoint({5, 2, 3});
strokes[2].addPoint({1, 4, 2.5});
strokes[2].addPoint({3, 6, 2});
strokes[2].addPoint({0, 0});
strokes[2].setWidth(3);
strokes[2].setFill(-1);
strokes[2].setToolType(StrokeTool::HIGHLIGHTER);
std::array<ErasableStroke, 3> erasables = {ErasableStroke(strokes[0]), ErasableStroke(strokes[1]),
ErasableStroke(strokes[2])};
std::array<bool, 3> areClosed = {false, true, true};
std::array<IntersectionParametersContainer, 3> fakeIntersections;
fakeIntersections[0] = {{1U, 0.5}, {2U, 0.5}, {3U, 0.5}, {4U, 0.5}};
fakeIntersections[1] = {{1U, 0.5}, {2U, 0.5}, {3U, 0.5}, {4U, 0.5}};
fakeIntersections[2] = {{0U, 0.0}, {2U, 0.5}, {3U, 0.5}, {4U, 1.0}};
std::array<std::vector<std::vector<Point>>, 3> resultingPaths;
resultingPaths[0] = std::vector<std::vector<Point>>(3);
resultingPaths[0][0] = {{0, 0, 2}, {2, 2, 2.5}, {3.5, 2}};
resultingPaths[0][1] = {{6, 3, 3}, {7, 4, 2.5}, {5, 5}};
resultingPaths[0][2] = {{2.5, 7, 2}, {2, 8, 1.5}, {5, 11, 1}, {7, 10, 1.5},
{7, 6, 2}, {6, 7, 2.5}, {4, 4, 3}, {1, 3}};
resultingPaths[1] = std::vector<std::vector<Point>>(2);
resultingPaths[1][0] = {{1.5, 3, 2}, {0, 0, 2}, {2, 2, 2.5}, {3.5, 2}};
resultingPaths[1][1] = {{3, 3, 3}, {1, 4, 2.5}, {2, 5}};
resultingPaths[2] = std::vector<std::vector<Point>>(1);
resultingPaths[2][0] = {{3, 3, 3}, {1, 4, 2.5}, {2, 5}};
unsigned int i = 0;
for (auto& erasable: erasables) {
strokes[i].setErasable(&erasable);
Range range(0, 0);
erasable.beginErasure(fakeIntersections[i], range);
ASSERT_EQ(erasable.isClosedStroke(), areClosed[i]);
auto res = erasable.getStrokes();
ASSERT_EQ(res.size(), resultingPaths[i].size());
for (unsigned int j = 0; j < res.size(); ++j) {
ASSERT_EQ(res[j]->getWidth(), strokes[i].getWidth());
ASSERT_EQ(res[j]->getFill(), strokes[i].getFill());
ASSERT_EQ(res[j]->getToolType(), strokes[i].getToolType());
ASSERT_EQ(res[j]->getAudioFilename(), strokes[i].getAudioFilename());
const auto& pts1 = res[j]->getPointVector();
const auto& pts2 = resultingPaths[i][j];
ASSERT_EQ(pts1.size(), pts2.size());
for (unsigned int k = 0; k < pts1.size(); ++k) {
ASSERT_EQ(pts1[k].x, pts2[k].x);
ASSERT_EQ(pts1[k].y, pts2[k].y);
ASSERT_EQ(pts1[k].z, pts2[k].z);
}
}
++i;
}
}
TEST(ErasableStroke, testIntersectWithPaddedBox) {
Stroke stroke;
stroke.addPoint({0, 0, 2}); // 0
stroke.addPoint({2, 2, 2.5}); // 1
stroke.addPoint({5, 2, 3}); // 2
stroke.addPoint({7, 4, 2.5}); // 3
stroke.addPoint({3, 6, 2}); // 4
stroke.addPoint({2, 8, 1.5}); // 5
stroke.addPoint({5, 11, 1}); // 6
stroke.addPoint({7, 10, 1.5}); // 7
stroke.addPoint({7, 6, 2}); // 8
stroke.addPoint({6, 7, 2.5}); // 9
stroke.addPoint({4, 4, 3}); // 10
stroke.addPoint({1, 3}); // 11 = (10, 1.0)
stroke.setWidth(3);
stroke.setFill(-1);
stroke.setToolType(StrokeTool::PEN);
std::array<PaddedBox, 10> boxes;
std::array<IntersectionParametersContainer, 10> expectedResult;
// Start in padding. Pass by inner box. End in padding, not going toward inner box.
boxes[0] = {Point(1, 1), 0.5, 3};
expectedResult[0] = {{0, 0.0}, {1, 2.0 / 3.0}};
// Start on inner box boundary. Pass inside. End in padding, not going toward inner box.
boxes[1] = {Point(1, 1), 1, 3};
expectedResult[1] = {{0, 0.0}, {1, 2.0 / 3.0}};
// Start in padding. Pass by inner box. End in padding going toward inner box
boxes[2] = {Point(1, 1), 1.9, 3.5};
expectedResult[2] = {{0, 0.0}, {1, 5.0 / 6.0}, {9, 5.0 / 6.0}, {10, 1.0}};
// Start on padding boundary, pass by inner box
boxes[3] = {Point(1, 1), 0.5, 1};
expectedResult[3] = {{0, 0.0}, {0, 1.0}};
// Intersect padding, not inner box
boxes[4] = {Point(2, 11), 1, 2};
expectedResult[4] = {};
// Intersect padding and inner box
boxes[5] = {Point(2, 8), 1, 4};
expectedResult[5] = {{3, 0.25}, {6, 0.5}};
// Intersect inner box and end in padding boundary
boxes[6] = {Point(2.5, 3.5), 0.5, 2};
expectedResult[6] = {{9, 0.75}, {10, 1.0}};
boxes[7] = {Point(6, 6), 1.1, 2};
expectedResult[7] = {{2, 1.0}, {3, .75}, {7, 0.5}, {9, 1.0}};
boxes[8] = {Point(7, 7.5), 1, 1.5};
expectedResult[8] = {{7, .25}, {9, 0.25}};
boxes[9] = {Point(6, 8), 0.5, 1};
expectedResult[9] = {};
for (unsigned int i = 0; i < boxes.size(); ++i) {
auto res = stroke.intersectWithPaddedBox(boxes[i]);
printf("Test box %u: ", i);
for (auto p: res) { printf("(%zu, %4.2f) ", p.index, p.t); }
printf("\n");
EXPECT_EQ(res.size(), expectedResult[i].size());
for (unsigned int j = 0; j < std::min(res.size(), expectedResult[i].size()); ++j) {
printf(" Found (%zu, %4.2f) - expected (%zu, %4.2f)\n", res[j].index, res[j].t,
expectedResult[i][j].index, expectedResult[i][j].t);
EXPECT_EQ(res[j].index, expectedResult[i][j].index);
EXPECT_DOUBLE_EQ(res[j].t, expectedResult[i][j].t);
}
}
}
| 9,519
|
C++
|
.cpp
| 208
| 37.120192
| 102
| 0.527149
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,322
|
LineStyleTest.cpp
|
xournalpp_xournalpp/test/unit_tests/model/LineStyleTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <config-test.h>
#include <gtest/gtest.h>
#include "model/LineStyle.h"
TEST(LineStyle, testLineStyle) {
LineStyle ls;
EXPECT_EQ(ls.hasDashes(), false);
EXPECT_EQ(ls.getDashes().empty(), true);
const double data2[] = {6, 2};
ls.setDashes(std::vector<double>(data2, data2 + 2));
const auto& dashes = ls.getDashes();
EXPECT_EQ(!dashes.empty(), true);
EXPECT_EQ(dashes.size(), 2);
EXPECT_EQ(dashes, std::vector<double>(data2, data2 + 2));
EXPECT_EQ(ls.hasDashes(), true);
}
| 698
|
C++
|
.cpp
| 25
| 24.72
| 61
| 0.668666
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,323
|
ColorPaletteTest.cpp
|
xournalpp_xournalpp/test/unit_tests/model/ColorPaletteTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <fstream>
#include <iostream>
#include <tuple>
#include <vector>
#include <config-test.h>
#include <gtest/gtest.h>
#include "gui/toolbarMenubar/model/ColorPalette.h"
#include "util/PathUtil.h"
std::string helper_read_file(fs::path path) {
std::ifstream fs{path};
std::stringstream stringStream{};
stringStream << fs.rdbuf();
return stringStream.str();
}
TEST(ColorPalette, testDefaultWrite) {
Palette::create_default(GET_TESTFILE("palettes/default_tmp.gpl"));
std::string createdDefault = helper_read_file(GET_TESTFILE("palettes/default_tmp.gpl"));
std::string fixedDefault = helper_read_file(GET_TESTFILE("palettes/default.gpl"));
EXPECT_EQ(fixedDefault, createdDefault);
fs::remove(GET_TESTFILE("palettes/default_tmp.gpl"));
}
TEST(ColorPalette, testDefaultLoad) {
Palette palette = Palette{GET_TESTFILE("palettes/default.gpl")};
palette.load();
Palette def = Palette{""};
def.load_default();
EXPECT_EQ((size_t)11, palette.size());
EXPECT_EQ(palette.getColorAt(0).getName(), def.getColorAt(0).getName());
EXPECT_EQ(palette.getColorAt(0).getIndex(), def.getColorAt(0).getIndex());
EXPECT_EQ(palette.getColorAt(0).getColorU16().alpha, def.getColorAt(0).getColorU16().alpha);
EXPECT_EQ(palette.getColorAt(0).getColorU16().red, def.getColorAt(0).getColorU16().red);
EXPECT_EQ(palette.getColorAt(0).getColorU16().green, def.getColorAt(0).getColorU16().green);
EXPECT_EQ(palette.getColorAt(0).getColorU16().blue, def.getColorAt(0).getColorU16().blue);
EXPECT_EQ(palette.getColorAt(10).getName(), def.getColorAt(10).getName());
EXPECT_EQ(palette.getColorAt(99).getName(), def.getColorAt(99).getName());
}
TEST(ColorPalette, testRainbowLoad) {
Palette palette = Palette{GET_TESTFILE("palettes/rainbow.gpl")};
palette.load();
EXPECT_EQ((size_t)6, palette.size());
EXPECT_EQ(palette.getColorAt(4).getName(), std::string{"Royal Blue"});
EXPECT_EQ(palette.getColorAt(4).getIndex(), (size_t)4);
EXPECT_EQ(palette.getColorAt(4).getColorU16().alpha, 0xFFFFU);
EXPECT_EQ(palette.getColorAt(4).getColorU16().red, 0U);
EXPECT_EQ(palette.getColorAt(4).getColorU16().green, 0x4D4DU);
EXPECT_EQ(palette.getColorAt(4).getColorU16().blue, 0xFFFFU);
EXPECT_EQ(palette.getColorAt(4).getColor(), Color{0xFF004DFFU});
}
TEST(ColorPalette, testOverflow) {
Palette palette = Palette{""};
palette.load_default();
EXPECT_EQ((size_t)11, palette.size());
EXPECT_EQ(palette.getColorAt(11).getColor(), palette.getColorAt(0).getColor());
EXPECT_EQ(palette.getColorAt(12).getColor(), palette.getColorAt(1).getColor());
}
TEST(ColorPalette, testNotExistLoad) {
Palette palette = Palette{GET_TESTFILE("palettes/the_question_to_the_answer_42.gpl")};
EXPECT_THROW(palette.load(), std::invalid_argument);
}
TEST(ColorPalette, testEmptyLoad) {
Palette palette = Palette{GET_TESTFILE("palettes/empty.gpl")};
EXPECT_THROW(palette.load(), std::invalid_argument);
}
TEST(ColorPalette, testWrongHeader) {
Palette palette = Palette{GET_TESTFILE("palettes/wrong_header.gpl")};
EXPECT_THROW(palette.load(), std::invalid_argument);
}
TEST(ColorPalette, testAttributesLoad) {
Palette palette = Palette{GET_TESTFILE("palettes/broken_attribute.gpl")};
EXPECT_THROW(palette.load(), std::invalid_argument);
Palette palette2 = Palette{GET_TESTFILE("palettes/not_broken_attribute.gpl")};
palette2.load();
EXPECT_EQ(std::string{"Gray"}, palette2.getColorAt(0).getName());
}
TEST(ColorPalette, testWrongColor) {
std::vector<std::tuple<fs::path, std::string>> path_exp{};
path_exp.push_back(std::make_tuple(GET_TESTFILE("palettes/bad_color_1.gpl"),
std::string{"RGB values bigger than 255 are not supported."}));
path_exp.push_back(
std::make_tuple(GET_TESTFILE("palettes/bad_color_2.gpl"), std::string{"The line 4 is malformed."}));
path_exp.push_back(
std::make_tuple(GET_TESTFILE("palettes/bad_color_3.gpl"), std::string{"The line 4 is malformed."}));
for (auto pe: path_exp) {
Palette palette = Palette{std::get<0>(pe)};
try {
palette.load();
FAIL();
} catch (const std::invalid_argument& e) {
// check exception
EXPECT_STREQ(std::get<1>(pe).c_str(), e.what());
}
}
}
| 4,578
|
C++
|
.cpp
| 103
| 39.640777
| 112
| 0.696922
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,324
|
StrokeStyleTest.cpp
|
xournalpp_xournalpp/test/unit_tests/model/StrokeStyleTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <config-test.h>
#include <gtest/gtest.h>
#include "model/StrokeStyle.h"
namespace {
constexpr double dashLinePattern[] = {6, 3};
constexpr double dashDotLinePattern[] = {6, 3, 0.5, 3};
constexpr double dotLinePattern[] = {0.5, 3};
constexpr double custPattern[] = {0.01, -1.0, 0.005};
} // namespace
TEST(StrokeStyle, testParseStyle) {
EXPECT_EQ(StrokeStyle::parseStyle("random"), LineStyle());
EXPECT_EQ(StrokeStyle::parseStyle("cust: "), LineStyle());
LineStyle l1;
double testData[] = {100, 200, 300};
l1.setDashes(std::vector<double>(testData, testData + 3));
EXPECT_EQ(StrokeStyle::parseStyle("cust: 100 200 300"), l1);
}
TEST(StrokeStyle, testFormatStyle) {
LineStyle dashLine;
dashLine.setDashes(std::vector<double>(dashLinePattern, dashLinePattern + 2));
EXPECT_EQ(StrokeStyle::formatStyle(dashLine), "dash");
LineStyle dashDot;
dashDot.setDashes(std::vector<double>(dashDotLinePattern, dashDotLinePattern + 4));
EXPECT_EQ(StrokeStyle::formatStyle(dashDot), "dashdot");
LineStyle dotLine;
dotLine.setDashes(std::vector<double>(dotLinePattern, dotLinePattern + 2));
EXPECT_EQ(StrokeStyle::formatStyle(dotLine), "dot");
LineStyle custLine;
custLine.setDashes(std::vector<double>(custPattern, custPattern + 3));
EXPECT_EQ(StrokeStyle::formatStyle(custLine), "cust: 0.01 -1.00 0.01");
}
| 1,556
|
C++
|
.cpp
| 41
| 34.756098
| 87
| 0.719124
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,325
|
ImageTest.cpp
|
xournalpp_xournalpp/test/unit_tests/model/ImageTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <fstream>
#include <config-test.h>
#include <gtest/gtest.h>
#include "model/Image.h"
TEST(Image, testGetImageApplyOrientation) {
auto image = Image();
// Image width is 500px and height 130px - but has exif data saying image should be
// rotated 90 deg CW to have correct orientation.
std::ifstream imageFile{GET_TESTFILE("images/r90.jpg"), std::ios::binary};
auto imageData = std::string(std::istreambuf_iterator<char>(imageFile), {});
GdkPixbufLoader* loader = gdk_pixbuf_loader_new();
gdk_pixbuf_loader_write(loader, reinterpret_cast<const guchar*>(imageData.c_str()), imageData.length(), nullptr);
gdk_pixbuf_loader_close(loader, nullptr);
GdkPixbuf* pixbuf = gdk_pixbuf_loader_get_pixbuf(loader);
// Image size before orientation
auto origImageSize = std::make_pair(gdk_pixbuf_get_width(pixbuf), gdk_pixbuf_get_height(pixbuf));
auto rotatedImageSize = std::make_pair(origImageSize.second, origImageSize.first);
g_object_unref(loader);
image.setImage(imageData);
// Test Image object has no size before the image has be rendered
EXPECT_EQ(image.getImageSize(), Image::NOSIZE);
// getImage render the image in a cairo surface
auto surface = image.getImage();
// Test image now have the correct size - which is the image has been rotated.
EXPECT_EQ(image.getImageSize(), rotatedImageSize);
EXPECT_EQ(image.getImageSize(), std::make_pair(130, 500));
EXPECT_EQ(std::make_pair(cairo_image_surface_get_width(surface), cairo_image_surface_get_height(surface)),
rotatedImageSize);
}
| 1,778
|
C++
|
.cpp
| 39
| 41.410256
| 117
| 0.723059
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,326
|
SettingsTest.cpp
|
xournalpp_xournalpp/test/unit_tests/control/SettingsTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <gtest/gtest.h>
#include "control/settings/Settings.h"
TEST(SettingsTest, testLoadDoesNotThrowForNonExistingFilePath) {
Settings settings{"non-existing-file-path"};
EXPECT_NO_THROW(settings.load());
}
| 395
|
C++
|
.cpp
| 16
| 22.4375
| 64
| 0.744681
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,327
|
LoadHandlerTest.cpp
|
xournalpp_xournalpp/test/unit_tests/control/LoadHandlerTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <cmath>
#include <filesystem>
#include <iostream>
#include <config-test.h>
#include <gtest/gtest.h>
#include "control/xojfile/LoadHandler.h"
#include "control/xojfile/SaveHandler.h"
#include "model/Element.h"
#include "model/Image.h"
#include "model/Stroke.h"
#include "model/Text.h"
#include "model/XojPage.h"
#include "util/PathUtil.h"
#include "filesystem.h"
using std::string;
// Common test Functions
/**
* Unit test implementation for the "suite.xopp" file and its derivatives.
* \param filepath The path to the actual file to load.
* \param tol The absolute tolerance used when checking stroke coordinate data.
*/
void testLoadStoreLoadHelper(const fs::path& filepath, double tol = 1e-8) {
auto getElements = [](Document* doc) {
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
const auto& elements = xoj::refElementContainer(layer->getElements());
EXPECT_EQ(8, static_cast<int>(elements.size()));
Stroke* e0 = (Stroke*)elements[0];
EXPECT_EQ(ELEMENT_STROKE, e0->getType());
Stroke* e1 = (Stroke*)elements[1];
EXPECT_EQ(ELEMENT_STROKE, e1->getType());
Stroke* e2 = (Stroke*)elements[2];
EXPECT_EQ(ELEMENT_STROKE, e2->getType());
Stroke* e3 = (Stroke*)elements[3];
EXPECT_EQ(ELEMENT_STROKE, e3->getType());
Stroke* e4 = (Stroke*)elements[4];
EXPECT_EQ(ELEMENT_STROKE, e4->getType());
Text* e5 = (Text*)elements[5];
EXPECT_EQ(ELEMENT_TEXT, e5->getType());
Stroke* e6 = (Stroke*)elements[6];
EXPECT_EQ(ELEMENT_STROKE, e6->getType());
Stroke* e7 = (Stroke*)elements[7];
EXPECT_EQ(ELEMENT_STROKE, e7->getType());
return elements;
};
LoadHandler handler;
auto doc1 = handler.loadDocument(filepath);
auto elements1 = getElements(doc1.get());
SaveHandler h;
h.prepareSave(doc1.get());
auto tmp = Util::getTmpDirSubfolder() / "save.xopp";
h.saveTo(tmp);
// Create a second loader so the first one doesn't free the memory
LoadHandler handler2;
auto doc2 = handler2.loadDocument(tmp);
auto elements2 = getElements(doc2.get());
// Check that the coordinates from both files don't differ more than the precision they were saved with
auto coordEq = [tol](double a, double b) { return std::abs(a - b) <= tol; };
for (unsigned long i = 0; i < elements1.size(); i++) {
Element* a = elements1.at(i);
Element* b = elements2.at(i);
EXPECT_EQ(a->getType(), b->getType());
EXPECT_TRUE(coordEq(a->getX(), b->getX()));
EXPECT_TRUE(coordEq(a->getY(), b->getY()));
EXPECT_TRUE(coordEq(a->getElementWidth(), b->getElementWidth()));
EXPECT_TRUE(coordEq(a->getElementHeight(), b->getElementHeight()));
EXPECT_EQ(a->getColor(), b->getColor());
switch (a->getType()) {
case ELEMENT_STROKE: {
auto sA = dynamic_cast<Stroke*>(a);
auto sB = dynamic_cast<Stroke*>(b);
EXPECT_EQ(sA->getPointCount(), sB->getPointCount());
EXPECT_EQ(sA->getToolType(), sB->getToolType());
EXPECT_EQ(sA->getLineStyle().hasDashes(), sB->getLineStyle().hasDashes());
EXPECT_TRUE(coordEq(sA->getAvgPressure(), sB->getAvgPressure()));
for (size_t j = 0; j < sA->getPointCount(); j++) {
Point pA = sA->getPoint(j);
Point pB = sB->getPoint(j);
EXPECT_TRUE(coordEq(pA.x, pB.x));
EXPECT_TRUE(coordEq(pA.y, pB.y));
EXPECT_TRUE(coordEq(pA.z, pB.z));
}
break;
}
case ELEMENT_TEXT: {
auto tA = dynamic_cast<Text*>(a);
auto tB = dynamic_cast<Text*>(b);
EXPECT_EQ(tA->getText(), tB->getText());
EXPECT_EQ(tA->getFontSize(), tB->getFontSize());
break;
}
default:
// If other elements are to be used in the test, implement extra comparisons
EXPECT_TRUE(false);
break;
}
}
}
void checkPageType(Document* doc, size_t pageIndex, string expectedText, PageType expectedBgType) {
PageRef page = doc->getPage(pageIndex);
PageType bgType = page->getBackgroundType();
EXPECT_TRUE(expectedBgType == bgType);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
auto&& element = layer->getElements().front();
EXPECT_EQ(ELEMENT_TEXT, element->getType());
Text* text = (Text*)element.get();
EXPECT_EQ(expectedText, text->getText());
}
void checkLayer(PageRef page, size_t layerIndex, string expectedText) {
Layer* layer = (*(*page).getLayers())[layerIndex];
auto&& element = layer->getElements().front();
EXPECT_EQ(ELEMENT_TEXT, element->getType());
Text* text = (Text*)element.get();
EXPECT_EQ(expectedText, text->getText());
}
TEST(ControlLoadHandler, testLoad) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("test1.xoj"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
auto&& element = layer->getElements().front();
EXPECT_EQ(ELEMENT_TEXT, element->getType());
Text* text = (Text*)element.get();
EXPECT_EQ(string("12345"), text->getText());
}
TEST(ControlLoadHandler, testLoadZipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/test.xopp"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
auto&& element = layer->getElements().front();
EXPECT_EQ(ELEMENT_TEXT, element->getType());
Text* text = (Text*)element.get();
EXPECT_EQ(string("12345"), text->getText());
}
TEST(ControlLoadHandler, testLoadUnzipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("test1.unzipped.xoj"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
auto&& element = layer->getElements().front();
EXPECT_EQ(ELEMENT_TEXT, element->getType());
Text* text = (Text*)element.get();
EXPECT_EQ(string("12345"), text->getText());
}
TEST(ControlLoadHandler, testPages) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("load/pages.xoj"));
EXPECT_EQ((size_t)6, doc->getPageCount());
}
TEST(ControlLoadHandler, testPagesZipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/pages.xopp"));
EXPECT_EQ((size_t)6, doc->getPageCount());
}
TEST(ControlLoadHandler, testPageType) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("load/pages.xoj"));
EXPECT_EQ((size_t)6, doc->getPageCount());
checkPageType(doc.get(), 0, "p1", PageType(PageTypeFormat::Plain));
checkPageType(doc.get(), 1, "p2", PageType(PageTypeFormat::Ruled));
checkPageType(doc.get(), 2, "p3", PageType(PageTypeFormat::Lined));
checkPageType(doc.get(), 3, "p4", PageType(PageTypeFormat::Staves));
checkPageType(doc.get(), 4, "p5", PageType(PageTypeFormat::Graph));
checkPageType(doc.get(), 5, "p6", PageType(PageTypeFormat::Image));
}
TEST(ControlLoadHandler, testPageTypeZipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/pages.xopp"));
EXPECT_EQ((size_t)6, doc->getPageCount());
checkPageType(doc.get(), 0, "p1", PageType(PageTypeFormat::Plain));
checkPageType(doc.get(), 1, "p2", PageType(PageTypeFormat::Ruled));
checkPageType(doc.get(), 2, "p3", PageType(PageTypeFormat::Lined));
checkPageType(doc.get(), 3, "p4", PageType(PageTypeFormat::Staves));
checkPageType(doc.get(), 4, "p5", PageType(PageTypeFormat::Graph));
checkPageType(doc.get(), 5, "p6", PageType(PageTypeFormat::Image));
}
TEST(ControlLoadHandler, testPageTypeFormatCopyFix) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("pageTypeFormatCopy.xopp"));
EXPECT_EQ((size_t)3, doc->getPageCount());
checkPageType(doc.get(), 0, "p1", PageType(PageTypeFormat::Lined));
checkPageType(doc.get(), 1, "p2", PageType(PageTypeFormat::Plain)); // PageTypeFormat::Copy in the file
checkPageType(doc.get(), 2, "p3", PageType(PageTypeFormat::Plain)); // PageTypeFormat::Plain in the file
}
TEST(ControlLoadHandler, testLayer) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("load/layer.xoj"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)3, (*page).getLayerCount());
checkLayer(page, 0, "l1");
checkLayer(page, 1, "l2");
checkLayer(page, 2, "l3");
}
TEST(ControlLoadHandler, testLayerZipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/layer.xopp"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)3, (*page).getLayerCount());
checkLayer(page, 0, "l1");
checkLayer(page, 1, "l2");
checkLayer(page, 2, "l3");
}
TEST(ControlLoadHandler, testText) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("load/text.xml"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
Text* t1 = (Text*)layer->getElements()[0].get();
EXPECT_EQ(ELEMENT_TEXT, t1->getType());
Text* t2 = (Text*)layer->getElements()[1].get();
EXPECT_EQ(ELEMENT_TEXT, t2->getType());
Text* t3 = (Text*)layer->getElements()[2].get();
EXPECT_EQ(ELEMENT_TEXT, t3->getType());
EXPECT_EQ(string("red"), t1->getText());
EXPECT_EQ(string("blue"), t2->getText());
EXPECT_EQ(string("green"), t3->getText());
EXPECT_EQ(Color(0xffff0000U), t1->getColor());
EXPECT_EQ(Color(0xff3333CCU), t2->getColor());
EXPECT_EQ(Color(0x00f000U), t3->getColor());
}
TEST(ControlLoadHandler, testTextZipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/text.xopp"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, (*page).getLayerCount());
Layer* layer = (*(*page).getLayers())[0];
Text* t1 = (Text*)layer->getElements()[0].get();
EXPECT_EQ(ELEMENT_TEXT, t1->getType());
Text* t2 = (Text*)layer->getElements()[1].get();
EXPECT_EQ(ELEMENT_TEXT, t2->getType());
Text* t3 = (Text*)layer->getElements()[2].get();
EXPECT_EQ(ELEMENT_TEXT, t3->getType());
EXPECT_EQ(string("red"), t1->getText());
EXPECT_EQ(string("blue"), t2->getText());
EXPECT_EQ(string("green"), t3->getText());
EXPECT_EQ(Color(0xffff0000U), t1->getColor());
EXPECT_EQ(Color(0xff3333CCU), t2->getColor());
EXPECT_EQ(Color(0x00f000U), t3->getColor());
}
TEST(ControlLoadHandler, testImageZipped) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/imgAttachment/new.xopp"));
EXPECT_EQ(1U, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ(1U, page->getLayerCount());
Layer* layer = (*page->getLayers())[0];
EXPECT_EQ(layer->getElements().size(), 1);
Image* img = dynamic_cast<Image*>(layer->getElements()[0].get());
EXPECT_TRUE(img);
}
namespace {
void checkImageFormat(Image* img, const char* formatName) {
GdkPixbufLoader* imgLoader = gdk_pixbuf_loader_new();
ASSERT_TRUE(gdk_pixbuf_loader_write(imgLoader, img->getRawData(), img->getRawDataLength(), nullptr));
ASSERT_TRUE(gdk_pixbuf_loader_close(imgLoader, nullptr));
GdkPixbufFormat* format = gdk_pixbuf_loader_get_format(imgLoader);
ASSERT_TRUE(format) << "could not determine image format";
auto gdkFormatName = gdk_pixbuf_format_get_name(format);
EXPECT_STREQ(gdkFormatName, formatName);
g_free(gdkFormatName);
g_object_unref(imgLoader);
}
} // namespace
TEST(ControlLoadHandler, imageLoadJpeg) {
// check loading of arbitrary image format (up to whatever is supported by GdkPixbuf)
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/imgAttachment/doc_with_jpg.xopp"));
ASSERT_TRUE(doc) << "doc should not be null";
ASSERT_EQ(1U, doc->getPageCount());
PageRef page = doc->getPage(0);
ASSERT_EQ(1U, page->getLayerCount());
Layer* layer = (*page->getLayers())[0];
ASSERT_EQ(layer->getElements().size(), 1);
Image* img = dynamic_cast<Image*>(layer->getElements()[0].get());
ASSERT_TRUE(img) << "element should be an image";
checkImageFormat(img, "jpeg");
}
// FIXME: create a SaveHandlerTest.cpp and move this test here
TEST(ControlLoadHandler, imageSaveJpegBackwardCompat) {
// File format version <= 4 requires images to be encoded as PNG in base64, but the version has not been bumped yet.
// For backward compatibility, check that loaded JPEG images are saved in PNG format.
// FIXME: use a path in CMAKE_BINARY_DIR or CMAKE_CURRENT_BINARY_DIR
const fs::path outPath = fs::temp_directory_path() / "xournalpp-test-units_ControlLoaderHandler_imageLoadJpeg.xopp";
// save journal containing JPEG image
{
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/imgAttachment/doc_with_jpg.xopp"));
ASSERT_TRUE(doc) << "doc with jpeg should not be null";
SaveHandler saver;
saver.prepareSave(doc.get());
saver.saveTo(outPath);
}
// check that the image is saved as PNG
LoadHandler handler;
auto doc = handler.loadDocument(outPath);
ASSERT_TRUE(doc) << "saved doc should not be null";
ASSERT_EQ(1U, doc->getPageCount());
PageRef page = doc->getPage(0);
ASSERT_EQ(1U, page->getLayerCount());
Layer* layer = (*page->getLayers())[0];
ASSERT_EQ(layer->getElements().size(), 1);
Image* img = dynamic_cast<Image*>(layer->getElements()[0].get());
ASSERT_TRUE(img) << "element should be an image";
checkImageFormat(img, "png");
}
TEST(ControlLoadHandler, testLoadStoreLoadDefault) {
testLoadStoreLoadHelper(GET_TESTFILE("packaged_xopp/suite.xopp"), /*tol=*/1e-8);
}
#ifdef __linux__
TEST(ControlLoadHandler, testLoadStoreLoadGerman) {
constexpr auto testLocale = "de_DE.UTF-8";
char* currentLocale = setlocale(LC_ALL, testLocale);
if (currentLocale == nullptr) {
auto environ = g_get_environ();
bool isCI = g_environ_getenv(environ, "CI");
g_strfreev(environ);
if (isCI) {
EXPECT_TRUE(false);
} else {
std::cout << "Skipping testLoadStoreLoadGerman! Consider generating the 'de_DE.UTF-8' locale on your "
"system."
<< std::endl;
}
}
testLoadStoreLoadHelper(GET_TESTFILE("packaged_xopp/suite.xopp"), /*tol=*/1e-8);
setlocale(LC_ALL, "C");
}
#endif
// Backwards compatibility test that checks that full-precision float strings can be loaded.
// See https://github.com/xournalpp/xournalpp/pull/4065
TEST(ControlLoadHandler, testLoadStoreLoadFloatBwCompat) {
testLoadStoreLoadHelper(GET_TESTFILE("packaged_xopp/suite_float_bw_compat.xopp"), /*tol=*/1e-5);
}
TEST(ControlLoadHandler, testStrokeWidthRecovery) {
LoadHandler handler;
auto doc = handler.loadDocument(GET_TESTFILE("packaged_xopp/stroke/width_recovery.xopp"));
EXPECT_EQ((size_t)1, doc->getPageCount());
PageRef page = doc->getPage(0);
EXPECT_EQ((size_t)1, page->getLayerCount());
Layer* layer = (*(page->getLayers()))[0];
EXPECT_EQ(9U, layer->getElements().size());
auto* s1 = (Stroke*)layer->getElements()[0].get();
EXPECT_EQ(ELEMENT_STROKE, s1->getType());
for (auto& p: s1->getPointVector()) {
EXPECT_EQ(p.z, Point::NO_PRESSURE);
}
auto testPressureValues = [&elts = layer->getElements()](size_t n, const std::vector<double>& pressures) {
auto* s = (Stroke*)elts[n].get();
printf("Testing stroke %zu\n", n);
EXPECT_EQ(ELEMENT_STROKE, s->getType());
EXPECT_EQ(Color(0x0000ff00), s->getColor());
EXPECT_EQ(1.41, s->getWidth());
auto pts = s->getPointVector();
EXPECT_EQ(pts.size(), pressures.size());
EXPECT_EQ(std::mismatch(pressures.begin(), pressures.end(), pts.begin(),
[](double v, const Point& p) { return v == p.z; })
.first,
pressures.end());
};
// This stroke got its last point removed and a negative pressure value got straightened up
testPressureValues(1, {0.16, 0.16, 0.20, 0.22, 0.26, 0.14, Point::NO_PRESSURE});
// The stroke is split in 4 bits due to null pressure values at various places
testPressureValues(2, {0.16, Point::NO_PRESSURE});
testPressureValues(3, {0.28, 0.30, 0.34, 0.22, 0.18, Point::NO_PRESSURE});
testPressureValues(4, {0.16, 0.16, 0.22, 0.28, 0.30, Point::NO_PRESSURE});
testPressureValues(5, {0.30, 0.34, 0.34, 0.38, 0.40, 0.40, 0.42, 0.46, 0.46, 0.46, 0.50, 0.52, Point::NO_PRESSURE});
testPressureValues(
6, {0.56, 0.56, 0.58, 0.60, 0.56, 0.40, 0.32, 0.18, 0.12, 0.16, 0.16, 0.20, 0.22, Point::NO_PRESSURE});
// The stroke is split in 2 bits due to "nan" pressure values at various places
testPressureValues(7, {0.20, 0.30, 0.10, Point::NO_PRESSURE});
testPressureValues(8, {0.25, 0.30, 0.40, Point::NO_PRESSURE});
}
TEST(ControlLoadHandler, testLoadStoreCJK) {
LoadHandler handler;
auto filepath = string(GET_TESTFILE("cjk/测试.xopp"));
auto doc = handler.loadDocument(fs::u8path(filepath));
ASSERT_NE(doc.get(), nullptr);
EXPECT_STREQ(doc->getPdfFilepath().filename().u8string().c_str(), u8"测试.pdf");
EXPECT_EQ((size_t)2, doc->getPageCount());
const auto page = doc->getPage(0);
EXPECT_EQ((size_t)1, page->getLayerCount());
const auto* layer = (*page->getLayers())[0];
const auto& elements = layer->getElements();
ASSERT_EQ((size_t)3, layer->getElements().size());
auto check_element = [&](int i, const char* answer) {
EXPECT_EQ(ELEMENT_TEXT, elements[i]->getType());
auto* text = dynamic_cast<Text*>(elements[i].get());
ASSERT_NE(text, nullptr);
EXPECT_STREQ(text->getText().c_str(), answer);
};
check_element(0, u8"Test");
check_element(1, u8"测试");
check_element(2, u8"テスト");
}
| 19,154
|
C++
|
.cpp
| 419
| 39.539379
| 120
| 0.651573
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,328
|
ActionDatabaseTest.cpp
|
xournalpp_xournalpp/test/unit_tests/control/ActionDatabaseTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <string>
#include <config-test.h>
#include <gtest/gtest.h>
#include <gtk/gtk.h>
#include "control/actions/ActionProperties.h"
#include "gui/menus/menubar/Menubar.h"
#include "util/EnumIndexedArray.h"
#include "util/raii/GObjectSPtr.h"
#include "util/raii/GVariantSPtr.h"
#include "util/safe_casts.h" // for to_underlying Todo(cpp20) replace with <utility>
#include "filesystem.h"
/**
* Test if the GActions referred to in MENU_XML_FILE have a counterpart in enums/Action.h, and checks if the (optional)
* action target value has the same type as set in control/actions/ActionProperties.h
*/
constexpr auto MENU_XML_FILE = "mainmenubar.xml";
constexpr auto MENU_ID = "menubar";
namespace {
template <Action a, class U = void>
struct helper {
static void setup(EnumIndexedArray<const GVariantType*, Action>& expectedTypes) { expectedTypes[a] = nullptr; };
};
template <Action a>
struct helper<a, std::void_t<typename ActionProperties<a>::parameter_type>> {
static void setup(EnumIndexedArray<const GVariantType*, Action>& expectedTypes) {
expectedTypes[a] = gVariantType<typename ActionProperties<a>::parameter_type>();
}
};
template <size_t... As>
static auto setupImpl(std::index_sequence<As...>) {
EnumIndexedArray<const GVariantType*, Action> expectedTypes;
((helper<static_cast<Action>(As)>::setup(expectedTypes)), ...);
return expectedTypes;
}
static const auto expectedTypes = setupImpl(std::make_index_sequence<xoj::to_underlying(Action::ENUMERATOR_COUNT)>());
void exploreMenu(GMenuModel* m, int lvl = 1) {
int n = g_menu_model_get_n_items(m);
for (int i = 0; i < n; i++) {
xoj::util::GVariantSPtr val(g_menu_model_get_item_attribute_value(m, i, "action", nullptr), xoj::util::adopt);
if (val) {
std::string value = g_variant_get_string(val.get(), nullptr);
auto pos = value.find('.');
EXPECT_TRUE(pos != std::string::npos);
EXPECT_TRUE(pos != 0);
std::string prefix = value.substr(0, pos);
std::string action = value.substr(pos + 1);
std::cout << std::setw(2 * lvl) << lvl << " " << value << std::endl;
Action a = Action_fromString(action);
xoj::util::GVariantSPtr target(g_menu_model_get_item_attribute_value(m, i, "target", nullptr),
xoj::util::adopt);
if (target) {
EXPECT_TRUE(g_variant_type_equal(g_variant_get_type(target.get()), expectedTypes[a]));
} else {
EXPECT_TRUE(expectedTypes[a] == nullptr);
}
}
{
xoj::util::GObjectSPtr<GMenuLinkIter> it(g_menu_model_iterate_item_links(m, i), xoj::util::adopt);
while (g_menu_link_iter_next(it.get())) {
std::cout << std::setw(2 * lvl) << lvl << " " << g_menu_link_iter_get_name(it.get()) << std::endl;
xoj::util::GObjectSPtr<GMenuModel> subm(g_menu_link_iter_get_value(it.get()), xoj::util::adopt);
exploreMenu(subm.get(), lvl + 1);
}
}
}
}
}; // namespace
TEST(ActionDatabaseTest, testActionTargetMatch) {
xoj::util::GObjectSPtr<GtkBuilder> builder(gtk_builder_new(), xoj::util::adopt);
GError* error = nullptr;
auto filepath = fs::path(GET_UI_FOLDER) / MENU_XML_FILE;
if (!gtk_builder_add_from_file(builder.get(), filepath.u8string().c_str(), &error)) {
std::string msg = "Error loading menubar XML file ";
msg += filepath.u8string();
if (error != nullptr) {
msg += "\n";
msg += error->message;
g_error_free(error);
}
FAIL() << msg;
return;
}
GMenuModel* menu = G_MENU_MODEL(gtk_builder_get_object(builder.get(), MENU_ID));
ASSERT_TRUE(menu);
exploreMenu(menu);
}
| 4,037
|
C++
|
.cpp
| 96
| 35.489583
| 119
| 0.631056
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,329
|
ToolEnumsTest.cpp
|
xournalpp_xournalpp/test/unit_tests/control/ToolEnumsTest.cpp
|
/*
* Xournal++
*
* This file is part of the Xournal UnitTests
*
* @author Xournal++ Team
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include <string>
#include <config-test.h>
#include <gtest/gtest.h>
#include "control/ToolEnums.h"
/**
* Test whether the invariant
* fromString(toString(x)) == x
* holds.
*/
TEST(ToolEnumsTest, testToolSizeSerialization) {
for (unsigned int i = 0; i <= TOOL_SIZE_NONE; i++) {
auto toolSize = static_cast<ToolSize>(i);
std::string s = toolSizeToString(toolSize);
EXPECT_FALSE(s.empty());
EXPECT_EQ(toolSize, toolSizeFromString(s));
}
}
/**
* Test whether the invariant
* fromString(toString(x)) == x
* holds.
*/
TEST(ToolEnumsTest, testToolTypeSerialization) {
for (unsigned int i = 0; i < TOOL_END_ENTRY; i++) {
auto toolType = static_cast<ToolType>(i);
std::string s = toolTypeToString(toolType);
EXPECT_FALSE(s.empty());
EXPECT_EQ(toolType, toolTypeFromString(s));
}
}
| 1,047
|
C++
|
.cpp
| 40
| 22.625
| 56
| 0.658683
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,330
|
Assert.cpp
|
xournalpp_xournalpp/src/util/Assert.cpp
|
#include "util/Assert.h"
#include <cstdlib>
#include <glib.h>
#ifndef NDEBUG
namespace xoj::util {
void assertFailure(const char* expr, const std::string& msg, const char* fileName, int line, const char* funcName) {
g_critical("Assertion failed: %s\n%s in function %s\n at line %d of %s", expr,
(!msg.empty() ? std::string(" Message: ") + msg + "\n" : "").c_str(), funcName, line, fileName);
std::abort();
}
}; // namespace xoj::util
#endif
| 477
|
C++
|
.cpp
| 12
| 36.583333
| 116
| 0.636364
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.