Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
3908 lines (3695 loc) · 186 KB
/
Copy pathmain.cpp
File metadata and controls
3908 lines (3695 loc) · 186 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "app_base.h"
#include "benchmark_results.h"
#include "cpu_benchmark.h"
#include "cpu_cli.h"
#include "complete_suite.h"
#include "result_quality.h"
#include "capture_naming.h"
#include "suite_process.h"
#include "gpu_memory_sweep.h"
#include "gpu_cache_probe.h"
#include "vulkan_membw_results.h"
#include "cpu_membw.h"
#include "gpu_engine.h"
#include "path_service.h"
#include "vulkan_membw.h"
#if defined(_WIN32) && defined(HAVE_VULKAN)
#include "renderdoc_app.h"
#endif
#ifdef HAVE_VULKAN
#include "vulkan_backend.h"
#endif
#ifdef HAVE_DX12
#include "dx12_backend.h"
#endif
#ifdef HAVE_DX11
#include "dx11_backend.h"
#endif
#ifdef HAVE_METAL
#include "metal_backend.h"
#include "metal_probe.h"
#endif
#ifdef HAVE_OPENGL
#include "opengl_backend.h"
#endif
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <map>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#if defined(__APPLE__)
#include <csignal>
#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>
#include <crt_externs.h>
#include <cerrno>
#endif
#if !defined(GPU_BENCH_NO_GLFW)
#include <GLFW/glfw3.h>
#endif
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <dxgi1_6.h>
#include <wrl/client.h>
#pragma comment(lib, "dxgi.lib")
// Hint NVIDIA Optimus and AMD Switchable Graphics to prefer the discrete GPU
// for OpenGL contexts. These must be exported from the final executable.
extern "C" {
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif
#ifdef HAVE_VULKAN
#include <vulkan/vulkan.h>
#endif
#ifdef HAVE_VULKAN
// On Windows the release binary delay-loads vulkan-1.dll. Older systems can
// therefore still launch and use Direct3D even when their display driver did
// not install a Vulkan runtime (for example, Direct3D 10-era adapters). Keep
// the module loaded once found so the delay-import thunk resolves against the
// same process-local loader. Other platforms retain their normal link model.
static bool VulkanLoaderAvailable() {
#ifdef _WIN32
static HMODULE loader = LoadLibraryW(L"vulkan-1.dll");
return loader != nullptr;
#else
return true;
#endif
}
#endif
static bool SafeStoi(const std::string& s, int& out) {
try { out = std::stoi(s); return true; }
catch (...) { return false; }
}
static bool SafeStod(const std::string& s, double& out) {
try {
std::size_t consumed = 0;
out = std::stod(s, &consumed);
return consumed == s.size() && std::isfinite(out);
} catch (...) {
return false;
}
}
static bool ParseCpuBenchmarkMode(const std::string& value,
gpu_bench::CpuBenchmarkMode& mode) {
if (value == "per-core" || value == "per_core" || value == "percore" ||
value == "single") {
mode = gpu_bench::CpuBenchmarkMode::PerCore;
return true;
}
if (value == "multi" || value == "multi-core" || value == "multi_core") {
mode = gpu_bench::CpuBenchmarkMode::MultiCore;
return true;
}
if (value == "all") {
mode = gpu_bench::CpuBenchmarkMode::All;
return true;
}
return false;
}
static std::string ExeDirectory(const char* argv0) {
#ifdef _WIN32
// argv is encoded with the active ANSI code page for a narrow main(), so
// it cannot faithfully represent every valid Windows installation path.
// Query the process image through the Unicode API and keep the project's
// existing UTF-8 string contract for backend shader paths.
std::wstring modulePath(32768, L'\0');
const DWORD length = GetModuleFileNameW(
nullptr, modulePath.data(), static_cast<DWORD>(modulePath.size()));
if (length > 0 && length < modulePath.size()) {
modulePath.resize(length);
std::string directory =
std::filesystem::path(modulePath).parent_path().u8string();
if (!directory.empty() && directory.back() != '/' && directory.back() != '\\')
directory += std::filesystem::path::preferred_separator;
return directory;
}
#endif
std::string path(argv0);
auto pos = path.find_last_of("\\/");
return pos != std::string::npos ? path.substr(0, pos + 1) : "";
}
#ifdef _WIN32
// A RenderDoc DLL can hook DirectX directly, but Vulkan discovers its capture
// layer through a manifest. Point the loader at an available matching manifest
// before the early GPU probe creates a Vulkan instance. This is process-local:
// no SDK, installer, administrator rights, or registry mutation is required.
static std::filesystem::path ConfigureBundledRenderDocLayer(
const std::string& shaderDir, bool captureRequested) {
if (!captureRequested) return {};
std::error_code ec;
auto exeDir = std::filesystem::absolute(
std::filesystem::u8path(shaderDir.empty() ? "." : shaderDir), ec);
if (ec) return {};
const std::filesystem::path candidates[] = {
exeDir / "tools" / "RenderDoc",
exeDir / ".." / "tools" / "RenderDoc",
exeDir / ".." / ".." / "tools" / "RenderDoc",
std::filesystem::path(L"C:\\Program Files\\RenderDoc"),
};
for (const auto& candidate : candidates) {
const auto dir = candidate.lexically_normal();
if (!std::filesystem::is_regular_file(dir / "renderdoc.json", ec) || ec) {
ec.clear();
continue;
}
if (!std::filesystem::is_regular_file(dir / "renderdoc.dll", ec) || ec) {
ec.clear();
continue;
}
// Override only the implicit-layer search for this capture process so
// the manifest and DLL always come from the same packaged version.
SetEnvironmentVariableW(L"VK_IMPLICIT_LAYER_PATH", dir.wstring().c_str());
SetEnvironmentVariableW(L"ENABLE_VULKAN_RENDERDOC_CAPTURE", L"1");
std::cout << "[RenderDoc] Configured Vulkan layer: "
<< dir.u8string() << "\n";
return dir / "renderdoc.dll";
}
return {};
}
#ifdef HAVE_VULKAN
// The bundled Vulkan layer is loaded by the early vkCreateInstance probe, well
// before AppBase::InitRenderDoc normally obtains the in-application API. GUI
// workers must disable RenderDoc's modal crash reporter before that probe can
// fault. Keep this explicit reference for the worker lifetime so the Vulkan
// loader reuses the exact DLL selected by ConfigureBundledRenderDocLayer.
static HMODULE g_guiWorkerRenderDocModule = nullptr;
static bool PrepareGuiWorkerRenderDocForVulkanProbe(
const std::filesystem::path& renderDocDll) {
if (renderDocDll.empty() || g_guiWorkerRenderDocModule)
return true;
HMODULE module = LoadLibraryW(renderDocDll.c_str());
if (!module) {
std::cerr << "[RenderDoc] Could not preload the bundled DLL before GPU probe (Win32 "
<< GetLastError() << ").\n";
return false;
}
auto getApi = reinterpret_cast<pRENDERDOC_GetAPI>(
GetProcAddress(module, "RENDERDOC_GetAPI"));
RENDERDOC_API_1_6_0* api = nullptr;
if (!getApi || getApi(eRENDERDOC_API_Version_1_6_0,
reinterpret_cast<void**>(&api)) != 1 ||
!api || !api->UnloadCrashHandler) {
std::cerr << "[RenderDoc] Bundled DLL did not expose the expected in-application API; "
"the early crash handler could not be disabled.\n";
FreeLibrary(module);
return false;
}
api->UnloadCrashHandler();
g_guiWorkerRenderDocModule = module;
std::cout << "[RenderDoc] Disabled the GUI worker crash handler before Vulkan GPU probe.\n";
return true;
}
#endif
#endif
#ifdef _WIN32
static LONG WINAPI CrashHandler(EXCEPTION_POINTERS* ep) {
DWORD code = ep->ExceptionRecord->ExceptionCode;
std::cout << "\n[CRASH] Unhandled exception: 0x"
<< std::hex << code << std::dec << std::endl;
// Name the module the fault is in: a driver's DLL tells a driver fault
// from one of ours without a debugger.
HMODULE faulting = nullptr;
char modulePath[MAX_PATH] = {};
const auto address = reinterpret_cast<const char*>(ep->ExceptionRecord->ExceptionAddress);
if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
address, &faulting) &&
GetModuleFileNameA(faulting, modulePath, MAX_PATH) > 0) {
std::cout << " -> in " << modulePath << " + 0x" << std::hex
<< static_cast<std::uintptr_t>(address - reinterpret_cast<const char*>(faulting))
<< std::dec << std::endl;
}
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
std::cout << " -> Access violation (segfault)" << std::endl; break;
case EXCEPTION_STACK_OVERFLOW:
std::cout << " -> Stack overflow" << std::endl; break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
std::cout << " -> Integer divide by zero" << std::endl; break;
default:
std::cout << " -> SEH exception code: 0x" << std::hex << code << std::endl; break;
}
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
// ---------------------------------------------------------------------------
// Lightweight API probe — enumerates GPUs and checks which backends each one
// supports, *without* creating a full device or window.
// ---------------------------------------------------------------------------
struct GpuInfo {
std::string name;
bool isSoftware = false;
bool isDiscrete = false;
std::uint64_t vramMB = 0;
bool supportsVulkan = false;
bool supportsDX12 = false;
bool supportsDX11 = false;
bool supportsDX11Compute = false;
std::uint32_t dx11FeatureLevel = 0;
bool supportsMetal = false;
bool supportsOpenGL = false;
bool supportsOpenGLCompute = false;
std::int32_t dxgiRawIndex = -1; // DXGI EnumAdapters1 index (stable across reordering)
std::int32_t vkPhysDevIndex = -1; // Vulkan vkEnumeratePhysicalDevices index
std::int64_t luidHigh = 0; // DXGI adapter LUID for cross-factory matching
std::int64_t luidLow = 0;
std::uint32_t dx12NodeIndex = 0; // physical node inside a linked DX12 adapter
std::uint32_t dx12NodeCount = 1;
};
struct CompleteSuiteJob {
std::int32_t gpuIndex = -1;
std::string gpuName;
bool software = false;
std::string backend;
std::string apiName;
std::string workload;
std::uint32_t particleCount = 0;
std::uint32_t burnSteps = 0;
bool headless = false;
bool captureRequired = false;
bool knownSupported = false;
std::string unsupportedReason;
};
struct SuiteAttemptState {
std::string status;
std::string reason;
};
static std::string SuiteJobKey(const CompleteSuiteJob& job) {
std::ostringstream out;
out << "suite_v2|" << job.gpuName << '|' << job.backend << '|'
<< job.workload << "|particles=" << job.particleCount
<< "|steps=" << job.burnSteps
<< "|headless=" << (job.headless ? 1 : 0)
<< "|capture=" << (job.captureRequired ? 1 : 0);
return out.str();
}
static std::filesystem::path SuiteStatusFilePath() {
return std::filesystem::path(gpu_bench::ResultsFilePath()).parent_path() /
"complete-suite-status.tsv";
}
static std::string SuiteTsvField(std::string value) {
for (char& c : value)
if (c == '\t' || c == '\r' || c == '\n') c = ' ';
return value;
}
static std::map<std::string, SuiteAttemptState> LoadSuiteAttemptStates() {
std::map<std::string, SuiteAttemptState> states;
std::ifstream input(SuiteStatusFilePath());
std::string line;
while (std::getline(input, line)) {
std::istringstream row(line);
std::string timestamp, key, status, reason;
if (!std::getline(row, timestamp, '\t') ||
!std::getline(row, key, '\t') ||
!std::getline(row, status, '\t'))
continue;
std::getline(row, reason);
states[key] = {status, reason};
}
return states;
}
static void AppendSuiteAttemptState(const CompleteSuiteJob& job,
const std::string& status,
const std::string& reason) {
std::ofstream output(SuiteStatusFilePath(), std::ios::app);
if (!output) return;
output << SuiteTsvField(gpu_bench::GenerateTimestamp()) << '\t'
<< SuiteTsvField(SuiteJobKey(job)) << '\t'
<< SuiteTsvField(status) << '\t'
<< SuiteTsvField(reason) << '\n';
}
static long long SuiteConfigInteger(const std::string& config,
const std::string& key,
long long fallback = 0) {
const std::string needle = key + "=";
auto pos = config.find(needle);
if (pos == std::string::npos) return fallback;
pos += needle.size();
auto end = config.find(';', pos);
try { return std::stoll(config.substr(pos, end - pos)); }
catch (...) { return fallback; }
}
static bool SuiteResultMatches(const gpu_bench::BenchmarkResult& result,
const CompleteSuiteJob& job) {
const bool cpuAll = job.workload == "cpu_all";
const bool workloadMatches = cpuAll
? result.workload == "cpu_single_core" || result.workload == "cpu_multi_core"
: result.workload == job.workload;
if (result.graphicsApi != job.apiName || !workloadMatches || result.headless != job.headless ||
!std::isfinite(result.score) || result.score <= 0) return false;
if (cpuAll && result.workloadVersion.find("_t15000ms_w200ms") == std::string::npos) return false;
#if defined(__APPLE__) && defined(__aarch64__)
if (cpuAll && result.workloadVersion.find("_kept_branch") == std::string::npos) return false;
#endif
if (job.backend != "cpu" && job.workload != "membw" && job.workload != "gpu_cache" &&
(result.warmupSec < 1.9 || result.durationSec < 11.0)) return false;
if (job.software) {
if (!result.isSoftware &&
result.deviceName.find("WARP") == std::string::npos &&
result.deviceName.find("Basic Render") == std::string::npos)
return false;
} else if (result.deviceName != job.gpuName) {
return false;
}
if (job.workload == "stream" && result.particleCount != job.particleCount)
return false;
#if defined(__APPLE__)
if (job.workload == "stream" && !job.headless &&
gpu_bench::ResultConfigValue(result, "renderCoverage") != "wrapped_ndc_v2")
return false;
if (job.workload == "stream" && job.headless && job.backend == "metal" &&
gpu_bench::ResultConfigValue(result, "timingMode") != "command_buffer_gpu_time")
return false;
if (job.workload == "stream" && job.backend == "vulkan" &&
gpu_bench::ResultConfigValue(result, "timingMode") != "synchronized_wall_clock")
return false;
#endif
if (job.workload == "membw" && job.backend == "vulkan" &&
!gpu_bench::CurrentVulkanMemoryContractVerified(result) &&
!gpu_bench::LegacyV1VulkanMemoryComparable(result)) return false;
if (job.workload == "gpu_burn" &&
SuiteConfigInteger(result.workloadConfig, "steps", -1) != job.burnSteps)
return false;
return true;
}
static bool SuiteResultHasCapture(const gpu_bench::BenchmarkResult& result) {
return SuiteConfigInteger(result.workloadConfig, "captureCount", 0) > 0;
}
// The worker names its capture after the device it actually opened, which for
// a software job ("Microsoft WARP (CPU Software Renderer)") differs from the
// enumerated name ("Microsoft Basic Render Driver"); pass the saved result's
// deviceName to look for that file too.
static bool SuiteCaptureExists(const CompleteSuiteJob& job,
const std::string& deviceName = {}) {
if (!job.captureRequired) return true;
gpu_bench::BenchmarkConfig captureConfig;
captureConfig.workload = job.workload == "stream" ? gpu_bench::Workload::Stream
: job.workload == "gpu_burn" ? gpu_bench::Workload::GpuBurnV1 : gpu_bench::Workload::CinematicLiquid;
captureConfig.particleCount = job.particleCount;
captureConfig.particlesOverridden = job.workload == "stream";
captureConfig.gpuBurnIter = job.burnSteps;
std::string expected = gpu_bench::CaptureFileStem(
job.apiName, deviceName.empty() ? job.gpuName : deviceName, captureConfig);
std::transform(expected.begin(), expected.end(), expected.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
std::error_code ec;
const auto directory = gpu_bench::paths::CapturesDirectory();
for (std::filesystem::directory_iterator it(directory, ec), end;
!ec && it != end; it.increment(ec)) {
const auto path = it->path();
auto name = path.filename().u8string();
std::transform(name.begin(), name.end(), name.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
const bool captureObject =
(it->is_regular_file(ec) && (path.extension() == ".rdc" || path.extension() == ".gputrace")) ||
(it->is_directory(ec) && path.extension() == ".gputrace");
if (captureObject && name.rfind(expected, 0) == 0)
return true;
}
return false;
}
static std::string QuoteSuiteProcessArg(const std::string& value) {
#ifdef _WIN32
std::string escaped;
escaped.reserve(value.size() + 2);
escaped.push_back('"');
for (char c : value) {
if (c == '"') escaped.push_back('\\');
escaped.push_back(c);
}
escaped.push_back('"');
return escaped;
#else
std::string escaped = "'";
for (char c : value)
escaped += c == '\'' ? "'\\''" : std::string(1, c);
escaped.push_back('\'');
return escaped;
#endif
}
static bool NameLooksIntegrated(const std::string& name) {
// Intel integrated: HD Graphics, UHD Graphics, Iris
if (name.find("Intel") != std::string::npos) {
if (name.find("Arc") != std::string::npos)
return false; // Intel Arc is discrete
return true; // all other Intel GPUs are integrated
}
// NVIDIA desktop GPUs are always discrete
if (name.find("NVIDIA") != std::string::npos ||
name.find("GeForce") != std::string::npos ||
name.find("Quadro") != std::string::npos ||
name.find("Tesla") != std::string::npos)
return false;
// AMD: discrete GPUs carry a model family (HD, RX, R9, R7, R5, Pro, VII, W)
if (name.find("Radeon") != std::string::npos) {
if (name.find("HD ") != std::string::npos ||
name.find("RX ") != std::string::npos ||
name.find("R9 ") != std::string::npos ||
name.find("R7 ") != std::string::npos ||
name.find("R5 ") != std::string::npos ||
name.find("VII") != std::string::npos ||
name.find("Pro ") != std::string::npos ||
name.find(" W") != std::string::npos)
return false; // discrete
return true; // generic "Radeon Graphics" = APU integrated
}
return false; // unknown vendor, assume discrete
}
static std::string CanonicalGpuMatchName(std::string name) {
// OpenGL commonly decorates the renderer ("/PCIe/SSE2") and some NVIDIA
// drivers omit the leading vendor name. Compare a lowercase alphanumeric
// form so these aliases attach to the existing DXGI/Vulkan adapter rather
// than creating a second, GL-only GPU row.
const auto slash = name.find('/');
if (slash != std::string::npos) name.resize(slash);
std::string canonical;
canonical.reserve(name.size());
for (unsigned char ch : name) {
if (std::isalnum(ch))
canonical.push_back(static_cast<char>(std::tolower(ch)));
}
return canonical;
}
static bool GpuNamesReferToSameAdapter(const std::string& a,
const std::string& b) {
const std::string ca = CanonicalGpuMatchName(a);
const std::string cb = CanonicalGpuMatchName(b);
if (ca.empty() || cb.empty()) return false;
if (ca == cb) return true;
const std::size_t shorter = (std::min)(ca.size(), cb.size());
return shorter >= 6 &&
(ca.find(cb) != std::string::npos ||
cb.find(ca) != std::string::npos);
}
static std::vector<GpuInfo> ProbeGpus(
[[maybe_unused]] const std::filesystem::path& guiWorkerRenderDocDll = {},
[[maybe_unused]] bool allowTranslatedApis = false) {
std::vector<GpuInfo> gpus;
#ifdef _WIN32
// --- DXGI enumeration (allow multiple identical GPUs, deduplicate by LUID) ---
Microsoft::WRL::ComPtr<IDXGIFactory2> factory;
if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) {
struct DevLuid { LONG high; DWORD low; };
std::vector<DevLuid> seen;
Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter;
for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) {
DXGI_ADAPTER_DESC1 desc{};
adapter->GetDesc1(&desc);
bool dup = false;
for (const auto& s : seen) {
if (s.high == desc.AdapterLuid.HighPart &&
s.low == desc.AdapterLuid.LowPart) {
dup = true; break;
}
}
if (dup) { adapter.Reset(); continue; }
seen.push_back({desc.AdapterLuid.HighPart, desc.AdapterLuid.LowPart});
GpuInfo info;
char name[256]{};
size_t converted = 0;
wcstombs_s(&converted, name, sizeof(name), desc.Description, _TRUNCATE);
info.name = name;
info.isSoftware = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0;
info.vramMB = desc.DedicatedVideoMemory / (1024 * 1024);
info.dxgiRawIndex = static_cast<std::int32_t>(i);
info.luidHigh = desc.AdapterLuid.HighPart;
info.luidLow = desc.AdapterLuid.LowPart;
#ifdef HAVE_DX12
{
extern std::uint32_t ProbeDX12NodeCount(IDXGIAdapter1*);
info.dx12NodeCount = ProbeDX12NodeCount(adapter.Get());
info.supportsDX12 = info.dx12NodeCount > 0;
}
#endif
#ifdef HAVE_DX11
{
D3D_FEATURE_LEVEL requested[] = {
D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0
};
D3D_FEATURE_LEVEL actual{};
Microsoft::WRL::ComPtr<ID3D11Device> probeDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext> probeContext;
const D3D_DRIVER_TYPE driverType = info.isSoftware
? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_UNKNOWN;
IDXGIAdapter* probeAdapter = info.isSoftware ? nullptr : adapter.Get();
HRESULT probeHr = D3D11CreateDevice(
probeAdapter, driverType, nullptr, 0,
requested, _countof(requested), D3D11_SDK_VERSION,
&probeDevice, &actual, &probeContext);
// The Windows 7 platform update's D3D11.0 runtime rejects an
// array containing FL11_1 with E_INVALIDARG. Retry without it
// so the native backend probe remains accurate there too.
if (probeHr == E_INVALIDARG) {
probeDevice.Reset();
probeContext.Reset();
probeHr = D3D11CreateDevice(
probeAdapter, driverType, nullptr, 0,
requested + 1, _countof(requested) - 1,
D3D11_SDK_VERSION,
&probeDevice, &actual, &probeContext);
}
if (SUCCEEDED(probeHr) && actual >= D3D_FEATURE_LEVEL_10_0) {
info.supportsDX11 = true;
info.dx11FeatureLevel = static_cast<std::uint32_t>(actual);
info.supportsDX11Compute = actual >= D3D_FEATURE_LEVEL_11_0;
if (!info.supportsDX11Compute) {
D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS options{};
info.supportsDX11Compute = SUCCEEDED(
probeDevice->CheckFeatureSupport(
D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS,
&options, sizeof(options))) &&
options.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x;
}
}
}
#endif
gpus.push_back(info);
adapter.Reset();
}
// DXGI exposes a linked-adapter set as one adapter. D3D12 exposes
// its physical GPUs as nodes of that one device, so expand those
// nodes into selectable benchmark rows while retaining the same LUID.
// DX11 has no equivalent node selector and therefore remains on the
// first/logical row only.
std::vector<GpuInfo> nodeExpanded;
for (const auto& gpu : gpus) {
nodeExpanded.push_back(gpu);
if (!gpu.isSoftware && gpu.supportsDX12 && gpu.dx12NodeCount > 1) {
for (std::uint32_t node = 1; node < gpu.dx12NodeCount; ++node) {
GpuInfo nodeGpu = gpu;
nodeGpu.dx12NodeIndex = node;
nodeGpu.supportsDX11 = false;
nodeGpu.supportsDX11Compute = false;
nodeGpu.dx11FeatureLevel = 0;
nodeGpu.supportsOpenGL = false;
nodeGpu.supportsVulkan = false;
nodeGpu.vkPhysDevIndex = -1;
nodeExpanded.push_back(std::move(nodeGpu));
}
}
}
gpus = std::move(nodeExpanded);
// --- DXGI 1.6: classify discrete vs integrated ---
// EnumAdapterByGpuPreference(HIGH_PERFORMANCE) returns the adapter
// Windows considers "high performance" first — typically the discrete GPU.
// Only use this heuristic when there are 2+ non-software GPUs; with a
// single GPU the preference order is meaningless and would incorrectly
// label an integrated GPU as discrete.
std::size_t hwGpuCount = 0;
for (const auto& g : gpus) { if (!g.isSoftware) ++hwGpuCount; }
if (hwGpuCount >= 2) {
Microsoft::WRL::ComPtr<IDXGIFactory6> factory6;
if (SUCCEEDED(factory.As(&factory6))) {
Microsoft::WRL::ComPtr<IDXGIAdapter1> hpAdapter;
for (UINT hp = 0;
SUCCEEDED(factory6->EnumAdapterByGpuPreference(
hp, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
IID_PPV_ARGS(&hpAdapter)));
++hp)
{
DXGI_ADAPTER_DESC1 hpDesc{};
hpAdapter->GetDesc1(&hpDesc);
if (hpDesc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) {
hpAdapter.Reset();
continue;
}
char hpName[256]{};
size_t hpConverted = 0;
wcstombs_s(&hpConverted, hpName, sizeof(hpName), hpDesc.Description, _TRUNCATE);
for (auto& g : gpus) {
// A DX12 linked adapter is expanded into one selectable
// row per physical node. Mark every row that belongs to
// the high-performance adapter, not only node 0.
if (g.name == hpName) g.isDiscrete = true;
}
hpAdapter.Reset();
break; // only the first non-software high-perf adapter is discrete
}
}
} else {
// Single hardware GPU: DXGI preference API can't distinguish, and
// old GPUs may lack Vulkan. Fall back to a name-based heuristic.
for (auto& g : gpus) {
if (!g.isSoftware)
g.isDiscrete = !NameLooksIntegrated(g.name);
}
}
}
#endif // _WIN32
#ifdef HAVE_METAL
{
auto metalDevices = gpu_bench::ProbeMetalDevices();
for (auto& md : metalDevices) {
auto it = std::find_if(gpus.begin(), gpus.end(), [&](const GpuInfo& g) {
return g.name.find(md.name) != std::string::npos
|| md.name.find(g.name) != std::string::npos;
});
if (it != gpus.end()) {
it->supportsMetal = true;
if (it->vramMB == 0 && md.vramBytes > 0)
it->vramMB = static_cast<std::uint32_t>(md.vramBytes / (1024 * 1024));
} else {
GpuInfo info;
info.name = md.name;
info.supportsMetal = true;
info.vramMB = static_cast<std::uint32_t>(md.vramBytes / (1024 * 1024));
info.isDiscrete = !md.hasUnifiedMemory && !md.isLowPower;
info.isSoftware = false;
gpus.push_back(info);
}
}
}
#endif
// --- Vulkan probe (if compiled in) ---
#ifdef HAVE_VULKAN
if (VulkanLoaderAvailable()
#ifdef GPU_BENCH_MOLTENVK
&& allowTranslatedApis
#endif
) {
#ifdef _WIN32
// Delay the explicit preload until after DXGI/D3D probing. Loading
// RenderDoc any earlier would unnecessarily change those probes by
// installing its D3D hooks; this is the last safe point before the
// Vulkan implicit layer can initialise its crash handler.
PrepareGuiWorkerRenderDocForVulkanProbe(guiWorkerRenderDocDll);
#endif
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.apiVersion = VK_API_VERSION_1_1;
VkInstanceCreateInfo ci{};
ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
ci.pApplicationInfo = &appInfo;
VkInstance inst = VK_NULL_HANDLE;
if (vkCreateInstance(&ci, nullptr, &inst) == VK_SUCCESS) {
std::uint32_t count = 0;
vkEnumeratePhysicalDevices(inst, &count, nullptr);
std::vector<VkPhysicalDevice> devs(count);
vkEnumeratePhysicalDevices(inst, &count, devs.data());
for (std::uint32_t di = 0; di < devs.size(); ++di) {
const auto& dev = devs[di];
VkPhysicalDeviceProperties props{};
vkGetPhysicalDeviceProperties(dev, &props);
bool vkIsSoftware = (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU);
bool vkIsDiscrete = (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU);
// Match Vulkan device to an existing DXGI entry by name.
// Prefer an unmatched entry first so that duplicate GPUs each get their own match.
bool matched = false;
auto nameMatches = [&](const GpuInfo& gpu) {
return GpuNamesReferToSameAdapter(gpu.name, props.deviceName);
};
// First pass: match an entry that hasn't been marked yet.
for (auto& gpu : gpus) {
if (!gpu.supportsVulkan && nameMatches(gpu)) {
gpu.supportsVulkan = true;
gpu.vkPhysDevIndex = static_cast<std::int32_t>(di);
if (vkIsSoftware) gpu.isSoftware = true;
if (vkIsDiscrete) gpu.isDiscrete = true;
matched = true;
break;
}
}
// Second pass: all matching entries already marked — this is an
// additional GPU with the same name (e.g. dual identical cards).
// Create a new entry right after the first match so ordering is logical.
if (!matched) {
for (std::size_t gi = 0; gi < gpus.size(); ++gi) {
if (nameMatches(gpus[gi])) {
GpuInfo info;
info.name = gpus[gi].name; // copy DXGI name so disambiguation matches
info.supportsVulkan = true;
info.isSoftware = vkIsSoftware;
info.isDiscrete = vkIsDiscrete;
info.vramMB = gpus[gi].vramMB;
// This is an extra Vulkan physical device, not an
// extra DXGI adapter. A linked-adapter driver can
// expose one DXGI adapter with multiple D3D12 nodes
// while Vulkan exposes each physical GPU separately.
// Copying the first match's DXGI index/LUID and D3D
// capabilities makes run-all execute the same D3D
// adapter twice and merely label the second result
// as another GPU. Leave this entry Vulkan-only;
// DX12 reaches its other node through explicit
// linked-adapter AFR/SFR instead.
info.vkPhysDevIndex = static_cast<std::int32_t>(di);
gpus.insert(gpus.begin() + static_cast<std::ptrdiff_t>(gi) + 1, info);
matched = true;
break;
}
}
}
// Partial match: try matching by a substring of the name.
if (!matched) {
std::string vkName(props.deviceName);
for (auto& gpu : gpus) {
if (!gpu.isSoftware && !gpu.supportsVulkan) {
if (vkName.size() > 6 && gpu.name.size() > 6) {
std::string shortVk = vkName.substr(0, vkName.size() / 2);
if (gpu.name.find(shortVk) != std::string::npos) {
gpu.supportsVulkan = true;
gpu.vkPhysDevIndex = static_cast<std::int32_t>(di);
if (vkIsDiscrete) gpu.isDiscrete = true;
matched = true;
break;
}
}
}
}
}
if (!matched) {
GpuInfo info;
info.name = props.deviceName;
info.supportsVulkan = true;
info.isSoftware = vkIsSoftware;
info.isDiscrete = vkIsDiscrete;
info.supportsDX11 = false;
info.supportsDX12 = false;
info.vkPhysDevIndex = static_cast<std::int32_t>(di);
gpus.push_back(info);
}
}
vkDestroyInstance(inst, nullptr);
}
}
#endif
// --- OpenGL probe: macOS graphics 4.1, desktop compute 4.3+ ---
#ifdef HAVE_OPENGL
{
if (glfwInit() == GLFW_FALSE)
return gpus; // GLFW not available — skip OpenGL probe
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
#ifdef __APPLE__
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#else
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#endif
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#endif
GLFWwindow* probe = glfwCreateWindow(1, 1, "", nullptr, nullptr);
if (probe) {
glfwMakeContextCurrent(probe);
// Read GL_RENDERER for software detection and fallback GPU entry.
using GetStringFn = const unsigned char* (*)(unsigned int);
auto glGetStringFn = reinterpret_cast<GetStringFn>(
glfwGetProcAddress("glGetString"));
std::string glRenderer;
if (glGetStringFn) {
const char* r = reinterpret_cast<const char*>(
glGetStringFn(0x1F01)); // GL_RENDERER
if (r) glRenderer = r;
}
using GetIntegerFn = void (*)(unsigned int, int*);
auto getInteger = reinterpret_cast<GetIntegerFn>(glfwGetProcAddress("glGetIntegerv"));
int glMajor = 0, glMinor = 0;
if (getInteger) {
getInteger(0x821B, &glMajor); // GL_MAJOR_VERSION
getInteger(0x821C, &glMinor); // GL_MINOR_VERSION
}
const bool glCompute = glMajor > 4 || (glMajor == 4 && glMinor >= 3);
bool isSoftwareGL =
glRenderer.find("llvmpipe") != std::string::npos ||
glRenderer.find("softpipe") != std::string::npos ||
glRenderer.find("swrast") != std::string::npos ||
glRenderer.find("lavapipe") != std::string::npos ||
glRenderer.find("Software") != std::string::npos;
// A GLFW context identifies only the OS-assigned OpenGL adapter;
// Windows has no standard per-context adapter selector. Do not mark
// every enumerated GPU as GL-capable or run-all will repeat the same
// default adapter and mislabel those results. Match one renderer
// entry; the fallback below creates a truthful GL-only row when the
// Vulkan/DXGI name cannot be correlated.
bool matchedOpenGlGpu = false;
if (!glRenderer.empty()) {
for (auto& gpu : gpus) {
if (gpu.isSoftware != isSoftwareGL) continue;
if (GpuNamesReferToSameAdapter(glRenderer, gpu.name)) {
gpu.supportsOpenGL = true;
gpu.supportsOpenGLCompute = glCompute;
matchedOpenGlGpu = true;
break;
}
}
}
if (!matchedOpenGlGpu && glRenderer.empty()) {
for (auto& gpu : gpus) {
if (gpu.isSoftware == isSoftwareGL) {
gpu.supportsOpenGL = true;
gpu.supportsOpenGLCompute = glCompute;
matchedOpenGlGpu = true;
break;
}
}
}
// On Linux without DXGI, gpus may be empty if no Vulkan SDK
// is installed. Create a GPU entry from GL_RENDERER so the
// application has at least one usable device.
if (!glRenderer.empty()) {
bool alreadyListed = matchedOpenGlGpu;
for (const auto& gpu : gpus) {
if (GpuNamesReferToSameAdapter(glRenderer, gpu.name)) {
alreadyListed = true;
break;
}
}
if (!alreadyListed) {
GpuInfo info;
info.name = glRenderer;
info.supportsOpenGL = true;
info.supportsOpenGLCompute = glCompute;
info.isSoftware = isSoftwareGL;
info.supportsDX11 = false;
info.supportsDX12 = false;
gpus.push_back(info);
}
}
glfwMakeContextCurrent(nullptr);
glfwDestroyWindow(probe);
}
glfwTerminate();
}
#endif
// Remove ghost DXGI adapters: some drivers expose the same physical GPU
// through multiple DXGI adapters with different LUIDs. After all API
// probing, if entries share the same name AND VRAM size but only some
// have Vulkan support, the non-Vulkan ones are ghost adapters — remove
// them. In a real dual-GPU setup both instances would be Vulkan-capable.
for (std::size_t i = 0; i < gpus.size(); ) {
bool hasVulkanSibling = false;
for (std::size_t j = 0; j < gpus.size(); ++j) {
if (j != i && gpus[j].name == gpus[i].name &&
gpus[j].vramMB == gpus[i].vramMB && gpus[j].supportsVulkan) {
hasVulkanSibling = true;
break;
}
}
const bool linkedDx12Node = gpus[i].supportsDX12 &&
gpus[i].dx12NodeCount > 1;
if (hasVulkanSibling && !gpus[i].supportsVulkan && !linkedDx12Node) {
gpus.erase(gpus.begin() + static_cast<std::ptrdiff_t>(i));
} else {
++i;
}
}
// Disambiguate GPUs with identical names by appending #1, #2, etc.
for (std::size_t i = 0; i < gpus.size(); ++i) {
const std::string original = gpus[i].name;
int count = 0;
for (std::size_t j = 0; j < gpus.size(); ++j)
if (gpus[j].name == original) ++count;
if (count > 1) {
int idx = 1;
for (std::size_t j = 0; j < gpus.size(); ++j) {
if (gpus[j].name == original) {
gpus[j].name += " #" + std::to_string(idx++);
}
}