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
76 /// Version number or dev.
77 constexpr string_view version = "dev";
79 /// Our fancy logging facility. The trick here is to replace cin.rdbuf() and
80 /// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
81 /// can toggle the logging of std::cout and std:cin at runtime whilst preserving
82 /// usual I/O functionality, all without changing a single line of code!
83 /// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
85 struct Tie: public streambuf { // MSVC requires split streambuf for cin and cout
87 Tie(streambuf* b, streambuf* l) : buf(b), logBuf(l) {}
89 int sync() override { return logBuf->pubsync(), buf->pubsync(); }
90 int overflow(int c) override { return log(buf->sputc((char)c), "<< "); }
91 int underflow() override { return buf->sgetc(); }
92 int uflow() override { return log(buf->sbumpc(), ">> "); }
94 streambuf *buf, *logBuf;
96 int log(int c, const char* prefix) {
98 static int last = '\n'; // Single log file
101 logBuf->sputn(prefix, 3);
103 return last = logBuf->sputc((char)c);
109 Logger() : in(cin.rdbuf(), file.rdbuf()), out(cout.rdbuf(), file.rdbuf()) {}
110 ~Logger() { start(""); }
116 static void start(const std::string& fname) {
120 if (l.file.is_open())
122 cout.rdbuf(l.out.buf);
129 l.file.open(fname, ifstream::out);
131 if (!l.file.is_open())
133 cerr << "Unable to open debug log file " << fname << endl;
146 /// engine_info() returns the full name of the current Stockfish version.
147 /// For local dev compiles we try to append the commit sha and commit date
148 /// from git if that fails only the local compilation date is set and "nogit" is specified:
149 /// Stockfish dev-YYYYMMDD-SHA
151 /// Stockfish dev-YYYYMMDD-nogit
153 /// For releases (non dev builds) we only include the version number:
154 /// Stockfish version
156 string engine_info(bool to_uci) {
158 ss << "Stockfish " << version << setfill('0');
160 if constexpr (version == "dev")
164 ss << stringify(GIT_DATE);
166 constexpr string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
167 string month, day, year;
168 stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
170 date >> month >> day >> year;
171 ss << year << setw(2) << setfill('0') << (1 + months.find(month) / 4) << setw(2) << setfill('0') << day;
177 ss << stringify(GIT_SHA);
183 ss << (to_uci ? "\nid author ": " by ")
184 << "the Stockfish developers (see AUTHORS file)";
190 /// compiler_info() returns a string trying to describe the compiler we use
192 std::string compiler_info() {
194 #define make_version_string(major, minor, patch) stringify(major) "." stringify(minor) "." stringify(patch)
196 /// Predefined macros hell:
198 /// __GNUC__ Compiler is gcc, Clang or Intel on Linux
199 /// __INTEL_COMPILER Compiler is Intel
200 /// _MSC_VER Compiler is MSVC or Intel on Windows
201 /// _WIN32 Building on Windows (any)
202 /// _WIN64 Building on Windows 64 bit
204 std::string compiler = "\nCompiled by ";
207 compiler += "clang++ ";
208 compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
209 #elif __INTEL_COMPILER
210 compiler += "Intel compiler ";
211 compiler += "(version ";
212 compiler += stringify(__INTEL_COMPILER) " update " stringify(__INTEL_COMPILER_UPDATE);
216 compiler += "(version ";
217 compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
219 #elif defined(__e2k__) && defined(__LCC__)
220 #define dot_ver2(n) \
221 compiler += (char)'.'; \
222 compiler += (char)('0' + (n) / 10); \
223 compiler += (char)('0' + (n) % 10);
225 compiler += "MCST LCC ";
226 compiler += "(version ";
227 compiler += std::to_string(__LCC__ / 100);
228 dot_ver2(__LCC__ % 100)
229 dot_ver2(__LCC_MINOR__)
232 compiler += "g++ (GNUC) ";
233 compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
235 compiler += "Unknown compiler ";
236 compiler += "(unknown version)";
239 #if defined(__APPLE__)
240 compiler += " on Apple";
241 #elif defined(__CYGWIN__)
242 compiler += " on Cygwin";
243 #elif defined(__MINGW64__)
244 compiler += " on MinGW64";
245 #elif defined(__MINGW32__)
246 compiler += " on MinGW32";
247 #elif defined(__ANDROID__)
248 compiler += " on Android";
249 #elif defined(__linux__)
250 compiler += " on Linux";
251 #elif defined(_WIN64)
252 compiler += " on Microsoft Windows 64-bit";
253 #elif defined(_WIN32)
254 compiler += " on Microsoft Windows 32-bit";
256 compiler += " on unknown system";
259 compiler += "\nCompilation settings include: ";
260 compiler += (Is64Bit ? " 64bit" : " 32bit");
261 #if defined(USE_VNNI)
264 #if defined(USE_AVX512)
265 compiler += " AVX512";
267 compiler += (HasPext ? " BMI2" : "");
268 #if defined(USE_AVX2)
271 #if defined(USE_SSE41)
272 compiler += " SSE41";
274 #if defined(USE_SSSE3)
275 compiler += " SSSE3";
277 #if defined(USE_SSE2)
280 compiler += (HasPopCnt ? " POPCNT" : "");
284 #if defined(USE_NEON_DOTPROD)
285 compiler += " NEON_DOTPROD";
286 #elif defined(USE_NEON)
291 compiler += " DEBUG";
294 compiler += "\n__VERSION__ macro expands to: ";
296 compiler += __VERSION__;
298 compiler += "(undefined macro)";
306 /// Debug functions used mainly to collect run-time statistics
307 constexpr int MaxDebugSlots = 32;
313 std::atomic<int64_t> data[N] = { 0 };
315 constexpr inline std::atomic<int64_t>& operator[](int index) { return data[index]; }
318 DebugInfo<2> hit[MaxDebugSlots];
319 DebugInfo<2> mean[MaxDebugSlots];
320 DebugInfo<3> stdev[MaxDebugSlots];
321 DebugInfo<6> correl[MaxDebugSlots];
325 void dbg_hit_on(bool cond, int slot) {
332 void dbg_mean_of(int64_t value, int slot) {
335 mean[slot][1] += value;
338 void dbg_stdev_of(int64_t value, int slot) {
341 stdev[slot][1] += value;
342 stdev[slot][2] += value * value;
345 void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
348 correl[slot][1] += value1;
349 correl[slot][2] += value1 * value1;
350 correl[slot][3] += value2;
351 correl[slot][4] += value2 * value2;
352 correl[slot][5] += value1 * value2;
358 auto E = [&n](int64_t x) { return double(x) / n; };
359 auto sqr = [](double x) { return x * x; };
361 for (int i = 0; i < MaxDebugSlots; ++i)
363 std::cerr << "Hit #" << i
364 << ": Total " << n << " Hits " << hit[i][1]
365 << " Hit Rate (%) " << 100.0 * E(hit[i][1])
368 for (int i = 0; i < MaxDebugSlots; ++i)
369 if ((n = mean[i][0]))
371 std::cerr << "Mean #" << i
372 << ": Total " << n << " Mean " << E(mean[i][1])
376 for (int i = 0; i < MaxDebugSlots; ++i)
377 if ((n = stdev[i][0]))
379 double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
380 std::cerr << "Stdev #" << i
381 << ": Total " << n << " Stdev " << r
385 for (int i = 0; i < MaxDebugSlots; ++i)
386 if ((n = correl[i][0]))
388 double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
389 / ( sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
390 * sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
391 std::cerr << "Correl. #" << i
392 << ": Total " << n << " Coefficient " << r
398 /// Used to serialize access to std::cout to avoid multiple threads writing at
401 std::ostream& operator<<(std::ostream& os, SyncCout sc) {
415 /// Trampoline helper to avoid moving Logger to misc.h
416 void start_logger(const std::string& fname) { Logger::start(fname); }
419 /// prefetch() preloads the given address in L1/L2 cache. This is a non-blocking
420 /// function that doesn't stall the CPU waiting for data to be loaded from memory,
421 /// which can be quite slow.
424 void prefetch(void*) {}
428 void prefetch(void* addr) {
430 # if defined(__INTEL_COMPILER)
431 // This hack prevents prefetches from being optimized away by
432 // Intel compiler. Both MSVC and gcc seem not be affected by this.
436 # if defined(__INTEL_COMPILER) || defined(_MSC_VER)
437 _mm_prefetch((char*)addr, _MM_HINT_T0);
439 __builtin_prefetch(addr);
446 /// std_aligned_alloc() is our wrapper for systems where the c++17 implementation
447 /// does not guarantee the availability of aligned_alloc(). Memory allocated with
448 /// std_aligned_alloc() must be freed with std_aligned_free().
450 void* std_aligned_alloc(size_t alignment, size_t size) {
452 #if defined(POSIXALIGNEDALLOC)
454 return posix_memalign(&mem, alignment, size) ? nullptr : mem;
455 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
456 return _mm_malloc(size, alignment);
457 #elif defined(_WIN32)
458 return _aligned_malloc(size, alignment);
460 return std::aligned_alloc(alignment, size);
464 void std_aligned_free(void* ptr) {
466 #if defined(POSIXALIGNEDALLOC)
468 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
470 #elif defined(_WIN32)
477 /// aligned_large_pages_alloc() will return suitably aligned memory, if possible using large pages.
481 static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
487 HANDLE hProcessToken { };
491 const size_t largePageSize = GetLargePageMinimum();
495 // Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
497 HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
500 hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
502 auto fun6 = (fun6_t)(void(*)())GetProcAddress(hAdvapi32, "OpenProcessToken");
505 auto fun7 = (fun7_t)(void(*)())GetProcAddress(hAdvapi32, "LookupPrivilegeValueA");
508 auto fun8 = (fun8_t)(void(*)())GetProcAddress(hAdvapi32, "AdjustTokenPrivileges");
512 // We need SeLockMemoryPrivilege, so try to enable it for the process
513 if (!fun6( // OpenProcessToken()
514 GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
517 if (fun7( // LookupPrivilegeValue(nullptr, SE_LOCK_MEMORY_NAME, &luid)
518 nullptr, "SeLockMemoryPrivilege", &luid))
520 TOKEN_PRIVILEGES tp { };
521 TOKEN_PRIVILEGES prevTp { };
524 tp.PrivilegeCount = 1;
525 tp.Privileges[0].Luid = luid;
526 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
528 // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges() succeeds,
529 // we still need to query GetLastError() to ensure that the privileges were actually obtained.
530 if (fun8( // AdjustTokenPrivileges()
531 hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp, &prevTpLen) &&
532 GetLastError() == ERROR_SUCCESS)
534 // Round up size to full pages and allocate
535 allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
537 nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
539 // Privilege no longer needed, restore previous state
540 fun8( // AdjustTokenPrivileges ()
541 hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
545 CloseHandle(hProcessToken);
552 void* aligned_large_pages_alloc(size_t allocSize) {
554 // Try to allocate large pages
555 void* mem = aligned_large_pages_alloc_windows(allocSize);
557 // Fall back to regular, page aligned, allocation if necessary
559 mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
566 void* aligned_large_pages_alloc(size_t allocSize) {
568 #if defined(__linux__)
569 constexpr size_t alignment = 2 * 1024 * 1024; // assumed 2MB page size
571 constexpr size_t alignment = 4096; // assumed small page size
574 // round up to multiples of alignment
575 size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
576 void *mem = std_aligned_alloc(alignment, size);
577 #if defined(MADV_HUGEPAGE)
578 madvise(mem, size, MADV_HUGEPAGE);
586 /// aligned_large_pages_free() will free the previously allocated ttmem
590 void aligned_large_pages_free(void* mem) {
592 if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
594 DWORD err = GetLastError();
595 std::cerr << "Failed to free large page memory. Error code: 0x"
597 << std::dec << std::endl;
604 void aligned_large_pages_free(void *mem) {
605 std_aligned_free(mem);
611 namespace WinProcGroup {
615 void bindThisThread(size_t) {}
619 /// best_node() retrieves logical processor information using Windows specific
620 /// API and returns the best node id for the thread with index idx. Original
621 /// code from Texel by Peter Ă–sterlund.
623 static int best_node(size_t idx) {
628 DWORD returnLength = 0;
629 DWORD byteOffset = 0;
631 // Early exit if the needed API is not available at runtime
632 HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
633 auto fun1 = (fun1_t)(void(*)())GetProcAddress(k32, "GetLogicalProcessorInformationEx");
637 // First call to GetLogicalProcessorInformationEx() to get returnLength.
638 // We expect the call to fail due to null buffer.
639 if (fun1(RelationAll, nullptr, &returnLength))
642 // Once we know returnLength, allocate the buffer
643 SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr;
644 ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(returnLength);
646 // Second call to GetLogicalProcessorInformationEx(), now we expect to succeed
647 if (!fun1(RelationAll, buffer, &returnLength))
653 while (byteOffset < returnLength)
655 if (ptr->Relationship == RelationNumaNode)
658 else if (ptr->Relationship == RelationProcessorCore)
661 threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
665 byteOffset += ptr->Size;
666 ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size);
671 std::vector<int> groups;
673 // Run as many threads as possible on the same node until core limit is
674 // reached, then move on filling the next node.
675 for (int n = 0; n < nodes; n++)
676 for (int i = 0; i < cores / nodes; i++)
679 // In case a core has more than one logical processor (we assume 2) and we
680 // have still threads to allocate, then spread them evenly across available
682 for (int t = 0; t < threads - cores; t++)
683 groups.push_back(t % nodes);
685 // If we still have more threads than the total number of logical processors
686 // then return -1 and let the OS to decide what to do.
687 return idx < groups.size() ? groups[idx] : -1;
691 /// bindThisThread() set the group affinity of the current thread
693 void bindThisThread(size_t idx) {
695 // Use only local variables to be thread-safe
696 int node = best_node(idx);
701 // Early exit if the needed API are not available at runtime
702 HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
703 auto fun2 = (fun2_t)(void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMaskEx");
704 auto fun3 = (fun3_t)(void(*)())GetProcAddress(k32, "SetThreadGroupAffinity");
705 auto fun4 = (fun4_t)(void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMask2");
706 auto fun5 = (fun5_t)(void(*)())GetProcAddress(k32, "GetMaximumProcessorGroupCount");
713 GROUP_AFFINITY affinity;
714 if (fun2(node, &affinity)) // GetNumaNodeProcessorMaskEx
715 fun3(GetCurrentThread(), &affinity, nullptr); // SetThreadGroupAffinity
719 // If a numa node has more than one processor group, we assume they are
720 // sized equal and we spread threads evenly across the groups.
721 USHORT elements, returnedElements;
722 elements = fun5(); // GetMaximumProcessorGroupCount
723 GROUP_AFFINITY *affinity = (GROUP_AFFINITY*)malloc(elements * sizeof(GROUP_AFFINITY));
724 if (fun4(node, affinity, elements, &returnedElements)) // GetNumaNodeProcessorMask2
725 fun3(GetCurrentThread(), &affinity[idx % returnedElements], nullptr); // SetThreadGroupAffinity
732 } // namespace WinProcGroup
736 #define GETCWD _getcwd
739 #define GETCWD getcwd
742 namespace CommandLine {
744 string argv0; // path+name of the executable binary, as given by argv[0]
745 string binaryDirectory; // path of the executable directory
746 string workingDirectory; // path of the working directory
748 void init([[maybe_unused]] int argc, char* argv[]) {
749 string pathSeparator;
751 // extract the path+name of the executable binary
755 pathSeparator = "\\";
757 // Under windows argv[0] may not have the extension. Also _get_pgmptr() had
758 // issues in some windows 10 versions, so check returned values carefully.
759 char* pgmptr = nullptr;
760 if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
767 // extract the working directory
768 workingDirectory = "";
770 char* cwd = GETCWD(buff, 40000);
772 workingDirectory = cwd;
774 // extract the binary directory path from argv0
775 binaryDirectory = argv0;
776 size_t pos = binaryDirectory.find_last_of("\\/");
777 if (pos == std::string::npos)
778 binaryDirectory = "." + pathSeparator;
780 binaryDirectory.resize(pos + 1);
782 // pattern replacement: "./" at the start of path is replaced by the working directory
783 if (binaryDirectory.find("." + pathSeparator) == 0)
784 binaryDirectory.replace(0, 1, workingDirectory);
788 } // namespace CommandLine
790 } // namespace Stockfish