2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
5 Stockfish is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Stockfish is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #if _WIN32_WINNT < 0x0601
24 #define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
32 // The needed Windows API for processor groups could be missed from old Windows
33 // versions, so instead of calling them directly (forcing the linker to resolve
34 // the calls at compile time), try to load them at runtime. To do this we need
35 // first to define the corresponding function pointers.
37 using fun1_t = bool(*)(LOGICAL_PROCESSOR_RELATIONSHIP,
38 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PDWORD);
39 using fun2_t = bool(*)(USHORT, PGROUP_AFFINITY);
40 using fun3_t = bool(*)(HANDLE, CONST GROUP_AFFINITY*, PGROUP_AFFINITY);
41 using fun4_t = bool(*)(USHORT, PGROUP_AFFINITY, USHORT, PUSHORT);
42 using fun5_t = WORD(*)();
43 using fun6_t = bool(*)(HANDLE, DWORD, PHANDLE);
44 using fun7_t = bool(*)(LPCSTR, LPCSTR, PLUID);
45 using fun8_t = bool(*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
57 #include <string_view>
61 #if defined(__linux__) && !defined(__ANDROID__)
65 #if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) || defined(__e2k__)
66 #define POSIXALIGNEDALLOC
74 // Version number or dev.
75 constexpr std::string_view version = "dev";
77 // Our fancy logging facility. The trick here is to replace cin.rdbuf() and
78 // cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
79 // can toggle the logging of std::cout and std:cin at runtime whilst preserving
80 // usual I/O functionality, all without changing a single line of code!
81 // Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
83 struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout
85 Tie(std::streambuf* b, std::streambuf* l) : buf(b), logBuf(l) {}
87 int sync() override { return logBuf->pubsync(), buf->pubsync(); }
88 int overflow(int c) override { return log(buf->sputc(char(c)), "<< "); }
89 int underflow() override { return buf->sgetc(); }
90 int uflow() override { return log(buf->sbumpc(), ">> "); }
92 std::streambuf *buf, *logBuf;
94 int log(int c, const char* prefix) {
96 static int last = '\n'; // Single log file
99 logBuf->sputn(prefix, 3);
101 return last = logBuf->sputc(char(c));
107 Logger() : in(std::cin.rdbuf(), file.rdbuf()), out(std::cout.rdbuf(), file.rdbuf()) {}
108 ~Logger() { start(""); }
114 static void start(const std::string& fname) {
118 if (l.file.is_open())
120 std::cout.rdbuf(l.out.buf);
121 std::cin.rdbuf(l.in.buf);
127 l.file.open(fname, std::ifstream::out);
129 if (!l.file.is_open())
131 std::cerr << "Unable to open debug log file " << fname << std::endl;
135 std::cin.rdbuf(&l.in);
136 std::cout.rdbuf(&l.out);
144 // engine_info() returns the full name of the current Stockfish version.
145 // For local dev compiles we try to append the commit sha and commit date
146 // from git if that fails only the local compilation date is set and "nogit" is specified:
147 // Stockfish dev-YYYYMMDD-SHA
149 // Stockfish dev-YYYYMMDD-nogit
151 // For releases (non-dev builds) we only include the version number:
154 std::string engine_info(bool to_uci) {
155 std::stringstream ss;
156 ss << "Stockfish " << version << std::setfill('0');
158 if constexpr (version == "dev")
162 ss << stringify(GIT_DATE);
164 constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
165 std::string month, day, year;
166 std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
168 date >> month >> day >> year;
169 ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4) << std::setw(2) << std::setfill('0') << day;
175 ss << stringify(GIT_SHA);
181 ss << (to_uci ? "\nid author ": " by ")
182 << "the Stockfish developers (see AUTHORS file)";
188 // compiler_info() returns a string trying to describe the compiler we use
190 std::string compiler_info() {
192 #define make_version_string(major, minor, patch) stringify(major) "." stringify(minor) "." stringify(patch)
194 // Predefined macros hell:
196 // __GNUC__ Compiler is GCC, Clang or ICX
197 // __clang__ Compiler is Clang or ICX
198 // __INTEL_LLVM_COMPILER Compiler is ICX
199 // _MSC_VER Compiler is MSVC
200 // _WIN32 Building on Windows (any)
201 // _WIN64 Building on Windows 64 bit
203 std::string compiler = "\nCompiled by : ";
205 #if defined(__INTEL_LLVM_COMPILER)
207 compiler += stringify(__INTEL_LLVM_COMPILER);
208 #elif defined(__clang__)
209 compiler += "clang++ ";
210 compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
213 compiler += "(version ";
214 compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
216 #elif defined(__e2k__) && defined(__LCC__)
217 #define dot_ver2(n) \
218 compiler += char('.'); \
219 compiler += char('0' + (n) / 10); \
220 compiler += char('0' + (n) % 10);
222 compiler += "MCST LCC ";
223 compiler += "(version ";
224 compiler += std::to_string(__LCC__ / 100);
225 dot_ver2(__LCC__ % 100)
226 dot_ver2(__LCC_MINOR__)
229 compiler += "g++ (GNUC) ";
230 compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
232 compiler += "Unknown compiler ";
233 compiler += "(unknown version)";
236 #if defined(__APPLE__)
237 compiler += " on Apple";
238 #elif defined(__CYGWIN__)
239 compiler += " on Cygwin";
240 #elif defined(__MINGW64__)
241 compiler += " on MinGW64";
242 #elif defined(__MINGW32__)
243 compiler += " on MinGW32";
244 #elif defined(__ANDROID__)
245 compiler += " on Android";
246 #elif defined(__linux__)
247 compiler += " on Linux";
248 #elif defined(_WIN64)
249 compiler += " on Microsoft Windows 64-bit";
250 #elif defined(_WIN32)
251 compiler += " on Microsoft Windows 32-bit";
253 compiler += " on unknown system";
256 compiler += "\nCompilation architecture : ";
258 compiler += stringify(ARCH);
260 compiler += "(undefined architecture)";
263 compiler += "\nCompilation settings : ";
264 compiler += (Is64Bit ? "64bit" : "32bit");
265 #if defined(USE_VNNI)
268 #if defined(USE_AVX512)
269 compiler += " AVX512";
271 compiler += (HasPext ? " BMI2" : "");
272 #if defined(USE_AVX2)
275 #if defined(USE_SSE41)
276 compiler += " SSE41";
278 #if defined(USE_SSSE3)
279 compiler += " SSSE3";
281 #if defined(USE_SSE2)
284 compiler += (HasPopCnt ? " POPCNT" : "");
285 #if defined(USE_NEON_DOTPROD)
286 compiler += " NEON_DOTPROD";
287 #elif defined(USE_NEON)
292 compiler += " DEBUG";
295 compiler += "\nCompiler __VERSION__ macro : ";
297 compiler += __VERSION__;
299 compiler += "(undefined macro)";
308 // Debug functions used mainly to collect run-time statistics
309 constexpr int MaxDebugSlots = 32;
315 std::atomic<int64_t> data[N] = { 0 };
317 constexpr inline std::atomic<int64_t>& operator[](int index) { return data[index]; }
320 DebugInfo<2> hit[MaxDebugSlots];
321 DebugInfo<2> mean[MaxDebugSlots];
322 DebugInfo<3> stdev[MaxDebugSlots];
323 DebugInfo<6> correl[MaxDebugSlots];
327 void dbg_hit_on(bool cond, int slot) {
334 void dbg_mean_of(int64_t value, int slot) {
337 mean[slot][1] += value;
340 void dbg_stdev_of(int64_t value, int slot) {
343 stdev[slot][1] += value;
344 stdev[slot][2] += value * value;
347 void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
350 correl[slot][1] += value1;
351 correl[slot][2] += value1 * value1;
352 correl[slot][3] += value2;
353 correl[slot][4] += value2 * value2;
354 correl[slot][5] += value1 * value2;
360 auto E = [&n](int64_t x) { return double(x) / n; };
361 auto sqr = [](double x) { return x * x; };
363 for (int i = 0; i < MaxDebugSlots; ++i)
365 std::cerr << "Hit #" << i
366 << ": Total " << n << " Hits " << hit[i][1]
367 << " Hit Rate (%) " << 100.0 * E(hit[i][1])
370 for (int i = 0; i < MaxDebugSlots; ++i)
371 if ((n = mean[i][0]))
373 std::cerr << "Mean #" << i
374 << ": Total " << n << " Mean " << E(mean[i][1])
378 for (int i = 0; i < MaxDebugSlots; ++i)
379 if ((n = stdev[i][0]))
381 double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
382 std::cerr << "Stdev #" << i
383 << ": Total " << n << " Stdev " << r
387 for (int i = 0; i < MaxDebugSlots; ++i)
388 if ((n = correl[i][0]))
390 double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
391 / ( sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
392 * sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
393 std::cerr << "Correl. #" << i
394 << ": Total " << n << " Coefficient " << r
400 // Used to serialize access to std::cout to avoid multiple threads writing at
403 std::ostream& operator<<(std::ostream& os, SyncCout sc) {
417 // Trampoline helper to avoid moving Logger to misc.h
418 void start_logger(const std::string& fname) { Logger::start(fname); }
421 // prefetch() preloads the given address in L1/L2 cache. This is a non-blocking
422 // function that doesn't stall the CPU waiting for data to be loaded from memory,
423 // which can be quite slow.
426 void prefetch(void*) {}
430 void prefetch(void* addr) {
432 # if defined(_MSC_VER)
433 _mm_prefetch((char*)addr, _MM_HINT_T0);
435 __builtin_prefetch(addr);
442 // std_aligned_alloc() is our wrapper for systems where the c++17 implementation
443 // does not guarantee the availability of aligned_alloc(). Memory allocated with
444 // std_aligned_alloc() must be freed with std_aligned_free().
446 void* std_aligned_alloc(size_t alignment, size_t size) {
448 #if defined(POSIXALIGNEDALLOC)
450 return posix_memalign(&mem, alignment, size) ? nullptr : mem;
451 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
452 return _mm_malloc(size, alignment);
453 #elif defined(_WIN32)
454 return _aligned_malloc(size, alignment);
456 return std::aligned_alloc(alignment, size);
460 void std_aligned_free(void* ptr) {
462 #if defined(POSIXALIGNEDALLOC)
464 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
466 #elif defined(_WIN32)
473 // aligned_large_pages_alloc() will return suitably aligned memory, if possible using large pages.
477 static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
483 HANDLE hProcessToken { };
487 const size_t largePageSize = GetLargePageMinimum();
491 // Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
493 HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
496 hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
498 auto fun6 = fun6_t((void(*)())GetProcAddress(hAdvapi32, "OpenProcessToken"));
501 auto fun7 = fun7_t((void(*)())GetProcAddress(hAdvapi32, "LookupPrivilegeValueA"));
504 auto fun8 = fun8_t((void(*)())GetProcAddress(hAdvapi32, "AdjustTokenPrivileges"));
508 // We need SeLockMemoryPrivilege, so try to enable it for the process
509 if (!fun6( // OpenProcessToken()
510 GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
513 if (fun7( // LookupPrivilegeValue(nullptr, SE_LOCK_MEMORY_NAME, &luid)
514 nullptr, "SeLockMemoryPrivilege", &luid))
516 TOKEN_PRIVILEGES tp { };
517 TOKEN_PRIVILEGES prevTp { };
520 tp.PrivilegeCount = 1;
521 tp.Privileges[0].Luid = luid;
522 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
524 // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges() succeeds,
525 // we still need to query GetLastError() to ensure that the privileges were actually obtained.
526 if (fun8( // AdjustTokenPrivileges()
527 hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp, &prevTpLen) &&
528 GetLastError() == ERROR_SUCCESS)
530 // Round up size to full pages and allocate
531 allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
533 nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
535 // Privilege no longer needed, restore previous state
536 fun8( // AdjustTokenPrivileges ()
537 hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
541 CloseHandle(hProcessToken);
548 void* aligned_large_pages_alloc(size_t allocSize) {
550 // Try to allocate large pages
551 void* mem = aligned_large_pages_alloc_windows(allocSize);
553 // Fall back to regular, page-aligned, allocation if necessary
555 mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
562 void* aligned_large_pages_alloc(size_t allocSize) {
564 #if defined(__linux__)
565 constexpr size_t alignment = 2 * 1024 * 1024; // assumed 2MB page size
567 constexpr size_t alignment = 4096; // assumed small page size
570 // round up to multiples of alignment
571 size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
572 void *mem = std_aligned_alloc(alignment, size);
573 #if defined(MADV_HUGEPAGE)
574 madvise(mem, size, MADV_HUGEPAGE);
582 // aligned_large_pages_free() will free the previously allocated ttmem
586 void aligned_large_pages_free(void* mem) {
588 if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
590 DWORD err = GetLastError();
591 std::cerr << "Failed to free large page memory. Error code: 0x"
593 << std::dec << std::endl;
600 void aligned_large_pages_free(void *mem) {
601 std_aligned_free(mem);
607 namespace WinProcGroup {
611 void bindThisThread(size_t) {}
615 // best_node() retrieves logical processor information using Windows specific
616 // API and returns the best node id for the thread with index idx. Original
617 // code from Texel by Peter Ă–sterlund.
619 static int best_node(size_t idx) {
624 DWORD returnLength = 0;
625 DWORD byteOffset = 0;
627 // Early exit if the needed API is not available at runtime
628 HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
629 auto fun1 = (fun1_t)(void(*)())GetProcAddress(k32, "GetLogicalProcessorInformationEx");
633 // First call to GetLogicalProcessorInformationEx() to get returnLength.
634 // We expect the call to fail due to null buffer.
635 if (fun1(RelationAll, nullptr, &returnLength))
638 // Once we know returnLength, allocate the buffer
639 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr;
640 ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(returnLength);
642 // Second call to GetLogicalProcessorInformationEx(), now we expect to succeed
643 if (!fun1(RelationAll, buffer, &returnLength))
649 while (byteOffset < returnLength)
651 if (ptr->Relationship == RelationNumaNode)
654 else if (ptr->Relationship == RelationProcessorCore)
657 threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
661 byteOffset += ptr->Size;
662 ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size);
667 std::vector<int> groups;
669 // Run as many threads as possible on the same node until the core limit is
670 // reached, then move on to filling the next node.
671 for (int n = 0; n < nodes; n++)
672 for (int i = 0; i < cores / nodes; i++)
675 // In case a core has more than one logical processor (we assume 2) and we
676 // have still threads to allocate, then spread them evenly across available
678 for (int t = 0; t < threads - cores; t++)
679 groups.push_back(t % nodes);
681 // If we still have more threads than the total number of logical processors
682 // then return -1 and let the OS to decide what to do.
683 return idx < groups.size() ? groups[idx] : -1;
687 // bindThisThread() sets the group affinity of the current thread
689 void bindThisThread(size_t idx) {
691 // Use only local variables to be thread-safe
692 int node = best_node(idx);
697 // Early exit if the needed API are not available at runtime
698 HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
699 auto fun2 = fun2_t((void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMaskEx"));
700 auto fun3 = fun3_t((void(*)())GetProcAddress(k32, "SetThreadGroupAffinity"));
701 auto fun4 = fun4_t((void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMask2"));
702 auto fun5 = fun5_t((void(*)())GetProcAddress(k32, "GetMaximumProcessorGroupCount"));
709 GROUP_AFFINITY affinity;
710 if (fun2(node, &affinity)) // GetNumaNodeProcessorMaskEx
711 fun3(GetCurrentThread(), &affinity, nullptr); // SetThreadGroupAffinity
715 // If a numa node has more than one processor group, we assume they are
716 // sized equal and we spread threads evenly across the groups.
717 USHORT elements, returnedElements;
718 elements = fun5(); // GetMaximumProcessorGroupCount
719 GROUP_AFFINITY *affinity = (GROUP_AFFINITY*)malloc(elements * sizeof(GROUP_AFFINITY));
720 if (fun4(node, affinity, elements, &returnedElements)) // GetNumaNodeProcessorMask2
721 fun3(GetCurrentThread(), &affinity[idx % returnedElements], nullptr); // SetThreadGroupAffinity
728 } // namespace WinProcGroup
732 #define GETCWD _getcwd
735 #define GETCWD getcwd
738 namespace CommandLine {
740 std::string argv0; // path+name of the executable binary, as given by argv[0]
741 std::string binaryDirectory; // path of the executable directory
742 std::string workingDirectory; // path of the working directory
744 void init([[maybe_unused]] int argc, char* argv[]) {
745 std::string pathSeparator;
747 // extract the path+name of the executable binary
751 pathSeparator = "\\";
753 // Under windows argv[0] may not have the extension. Also _get_pgmptr() had
754 // issues in some Windows 10 versions, so check returned values carefully.
755 char* pgmptr = nullptr;
756 if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
763 // extract the working directory
764 workingDirectory = "";
766 char* cwd = GETCWD(buff, 40000);
768 workingDirectory = cwd;
770 // extract the binary directory path from argv0
771 binaryDirectory = argv0;
772 size_t pos = binaryDirectory.find_last_of("\\/");
773 if (pos == std::string::npos)
774 binaryDirectory = "." + pathSeparator;
776 binaryDirectory.resize(pos + 1);
778 // pattern replacement: "./" at the start of path is replaced by the working directory
779 if (binaryDirectory.find("." + pathSeparator) == 0)
780 binaryDirectory.replace(0, 1, workingDirectory);
784 } // namespace CommandLine
786 } // namespace Stockfish