Repository navigation
Expand file tree
/
Copy pathDraw.cpp
More file actions
2178 lines (2100 loc) · 139 KB
/
Copy pathDraw.cpp
File metadata and controls
2178 lines (2100 loc) · 139 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 "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetTransfer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/GpuColorTransfer.hpp"
#include "prx/libSceAgcDriver/Graphics/include/VertexInput.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp"
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
#include "prx/libSceAgcDriver/Execution/include/CaptureTrace.hpp"
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/GuestAllocations.hpp"
#include "Optimization/include/Optimization/ShaderStageInputInfo.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <functional>
#include <optional>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <utility>
namespace AgcDriver::Graphics {
namespace {
std::uint32_t GuestFormatFor(VkFormat format, std::uint32_t elementBytes) {
if (const auto guest = FindGuestColorTargetFormat(format, elementBytes)) return *guest;
throw std::runtime_error("AGC graphics: no guest texture format matches the color buffer format " + std::to_string(static_cast<int>(format)));
}
// The color buffer as a single-mip 2D surface descriptor (tile mode SW_64KB_R_X).
GuestTextureResource SurfaceForTarget(const ColorTarget& color) {
Require(color.tileMode != ColorTileMode::Linear, "linear color targets are not resident");
const bool chain = color.mipCount > 1;
GuestTextureResource surface{};
surface.baseAddress = chain ? color.surfaceAddress : color.address;
surface.width = chain ? color.surfaceExtent.width : color.extent.width;
surface.height = chain ? color.surfaceExtent.height : color.extent.height;
surface.depthOrLastArray = color.depth - 1u;
surface.baseArray = 0;
surface.mipCount = color.mipCount;
surface.baseLevel = 0;
surface.lastLevel = color.mipCount - 1;
surface.tileMode = ColorTextureTileMode(color.tileMode);
surface.dimension = color.depth > 1 ? TextureDimension::k3D : TextureDimension::k2D;
surface.format = GuestFormatFor(color.format, color.elementBytes);
surface.dstSelX = 4;
surface.dstSelY = 5;
surface.dstSelZ = 6;
surface.dstSelW = 7;
surface.dccAddress = color.dccAddress;
surface.dccAlphaOnMsb = color.dccAlphaOnMsb;
surface.dccPipeAligned = color.dccPipeAligned;
return surface;
}
}
namespace {
std::size_t colorKeyCount(const ColorTarget& color, std::size_t bytes) {
if (color.mipCount != 1 || color.depth != 1 || !color.dccPipeAligned) return DccKeyBytes(bytes);
return DccKeyCount(ColorTextureTileMode(color.tileMode), color.elementBytes, color.extent.width, color.extent.height, bytes);
}
std::array<std::byte, 16> clearTexel(const ColorTarget& color, DccKeys keys) {
std::array<std::byte, 16> texel{};
const auto elementBytes = static_cast<std::size_t>(color.elementBytes);
Require(elementBytes != 0 && elementBytes <= texel.size(), "unexpected color element size");
if (keys == DccKeys::ClearRegister) {
Require(elementBytes <= sizeof(color.clearWords), "the DCC register clear of a texel over 64 bits is not modeled");
std::memcpy(texel.data(), color.clearWords.data(), elementBytes);
} else {
Require(FillDccClear(color.format, keys, color.dccAlphaOnMsb, std::span(texel.data(), elementBytes)), "the target's format has no encoding of its DCC clear code");
}
return texel;
}
bool clearToTexel(StorageTexture& image, const std::array<std::byte, 16>& texel, std::uint32_t elementBytes, const char*& refusal) {
std::array<std::byte, 16> repeated{};
for (std::size_t offset = 0; offset + elementBytes <= repeated.size(); offset += elementBytes) std::memcpy(repeated.data() + offset, texel.data(), elementBytes);
std::array<std::uint32_t, 4> pattern{};
std::memcpy(pattern.data(), repeated.data(), repeated.size());
return image.FillClear(std::span<const std::uint32_t, 4>(pattern), StorageTexture::WholeImage, refusal);
}
void writeTexels(const ColorTarget& color, const std::array<std::byte, 16>& texel) {
const auto elementBytes = static_cast<std::size_t>(color.elementBytes);
std::vector<std::byte> texels(color.bytes);
for (std::size_t offset = 0; offset + elementBytes <= texels.size(); offset += elementBytes) std::memcpy(texels.data() + offset, texel.data(), elementBytes);
GuestMemory::Write(color.address, texels);
}
void storeClearTexels(const Context& context, const ColorTarget& color, const std::array<std::byte, 16>& texel) {
StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization");
const auto keys = ReadDccKeys(color.dccAddress, color.bytes);
if (!IsDccClear(keys)) return;
writeTexels(color, keys == DccKeys::ClearRegister ? texel : clearTexel(color, keys));
MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes));
}
void materializeRegisterClear(const Context& context, const ColorTarget& color, StorageTexture& resident) {
if (color.dccAddress == 0 || resident.Descriptor().dccAddress != color.dccAddress) return;
if (CurrentDccKeys(color.dccAddress, color.bytes) != DccKeys::ClearRegister) return;
const auto texel = clearTexel(color, DccKeys::ClearRegister);
const char* refusal = nullptr;
bool cleared = clearToTexel(resident, texel, color.elementBytes, refusal);
const auto keyBytes = static_cast<std::size_t>(color.bytes / 256);
if (!cleared && keyBytes != 0) {
if (auto* recorder = Recorder::Active(); recorder != nullptr && recorder->PendingWriteOverlaps(color.dccAddress, keyBytes)) {
Recorder::CountSync(2);
recorder->SyncThrough(color.dccAddress, keyBytes);
if (CurrentDccKeys(color.dccAddress, color.bytes) != DccKeys::ClearRegister) return;
cleared = clearToTexel(resident, texel, color.elementBytes, refusal);
}
}
if (cleared) {
MarkDccUncompressed(context, color.dccAddress, color.bytes, colorKeyCount(color, color.bytes));
return;
}
storeClearTexels(context, color, texel);
resident.Refresh();
}
bool materializeCmaskClear(const Context& context, const ColorTarget& color, StorageTexture* resident) {
if (color.cmaskAddress == 0) return false;
const auto metadataBytes = static_cast<std::uint64_t>(color.cmaskBytes) * 256u;
const auto state = CurrentDccKeys(color.cmaskAddress, metadataBytes);
if (state == DccKeys::Uncompressed) return false;
Require(color.dccAddress == 0, std::string("CMASK of a DCC color target that is not all expanded is not modeled (") + DccKeysName(state) + ")");
Require(state == DccKeys::Clear0000, std::string("CMASK whose tiles are not all fast-cleared or all expanded is not modeled (") + DccKeysName(state) + ")");
const auto texel = clearTexel(color, DccKeys::ClearRegister);
const char* refusal = nullptr;
if (resident == nullptr || !clearToTexel(*resident, texel, color.elementBytes, refusal)) {
StorageTexture::FlushPending(color.address, color.bytes, nullptr, "fast-clear materialization");
writeTexels(color, texel);
if (resident != nullptr) resident->Refresh();
}
MarkDccUncompressed(context, color.cmaskAddress, metadataBytes);
return true;
}
void imageBarrier(const Context& context, VkCommandBuffer commands, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) {
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
barrier.srcAccessMask = sourceAccess;
barrier.dstAccessMask = destinationAccess;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier);
}
void memoryBarrier(const Context& context, VkCommandBuffer commands, VkPipelineStageFlags sourceStage, VkPipelineStageFlags destinationStage, VkAccessFlags sourceAccess, VkAccessFlags destinationAccess) {
const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, sourceAccess, destinationAccess};
context.Resolved(&DeviceFunctions::cmdPipelineBarrier, "vkCmdPipelineBarrier")(commands, sourceStage, destinationStage, 0, 1, &barrier, 0, nullptr, 0, nullptr);
}
// The color surface as one untailed SW_64KB_R_X mip for the GPU detiler, with tightly packed linear rows.
TileMipLayout ColorTargetMip(const ColorTarget& color, const ColorTargetLayout& layout) {
TileMipLayout mip{};
mip.width = color.extent.width;
mip.height = color.extent.height;
mip.blocksPerRow = layout.BlocksPerRow();
mip.pitchBytes = color.extent.width * color.elementBytes;
mip.tiledSize = layout.Bytes();
mip.linearSize = layout.LinearBytes();
return mip;
}
// APS5_PROFILE_DRAW: per-draw phase timers in microseconds (a recorded draw's phases are far below
// the millisecond the old print rounded to), totalled over 10 s in the [draws] line.
enum DrawPhase : std::size_t { PhaseValidate, PhaseVertex, PhaseSetup, PhaseReadTarget, PhasePrepare, PhaseLookup, PhaseResources, PhasePipeline, PhaseRecord, PhaseKeep, PhaseSync, PhaseWriteBack, PhaseDescribe, PhaseCount };
constexpr std::array<const char*, PhaseCount> DrawPhaseNames{"validate", "vertex", "setup", "readTarget", "prepare", "lookup", "resources", "pipeline", "record", "keep", "sync", "writeBack", "describe"};
// Why a draw did not go into the recorder without a wait (counted in the [draws] line): its targets
// are not all resident, no recorder is active, a switch (APS5_SYNC_DRAWS, APS5_DUMP_TARGETS,
// APS5_SYNC_COMPLETION_DRAWS) forced it, or its completion work writes copied guest buffers or
// releases an address-based build's lease, which the CPU must not outrun (see `recorded` in Draw).
enum SyncReason : std::size_t { SyncNone, SyncNotResident, SyncNoRecorder, SyncDisabled, SyncCopiedWrites, SyncLease, SyncCount };
constexpr std::array<const char*, SyncCount> SyncReasonNames{"none", "non-resident target", "no recorder", "disabled", "copied writes", "lease"};
constexpr std::size_t IndirectPathCount = static_cast<std::size_t>(IndirectDrawPath::Count);
constexpr std::array<const char*, IndirectPathCount> IndirectDrawPathNames{"gpu-side", "patched SGPR not folded", "fetch offset unknown", "non-vertex path", "GE_INDX_OFFSET", "draw index", "vertex range too large", "feature gap", "pending image results", "pending label or copied write", "not imported", "disabled"};
// What became of one draw, for the totals.
struct DrawOutcome {
// In the recorder; `waited` when the recorder was synced right after (copied writes or a lease).
bool recorded = false;
bool waited = false;
bool completion = false;
// A recorded draw began a render pass of its own, or continued the previous draw's.
bool passBegun = false;
bool passContinued = false;
SyncReason reason = SyncNone;
// Shader validation memo (see CachedFragmentOutputs).
bool validateMemoized = false;
bool validateHit = false;
// A build that acquired the allocation registry lease (BDA), whose cost sits outside the
// build's own sub-phases.
bool addressBased = false;
// Resident target lookups, and those that took a millisecond or more. Whether a slow one
// re-uploaded the image or just walked its pages under contention is not visible from here
// (StorageTexture::Version advances on every MarkDirty as well as on an upload, and Generation
// is stamped afresh by every write-watch walk): the [texture] line's "reused" and "direct
// uploads" counters and APS5_TRACE_UPLOAD name the actual uploads.
std::uint64_t targetLookups = 0;
std::uint64_t slowLookups = 0;
double slowLookupUs = 0;
// The lookups by whether the draw's scissor covers the whole target (an area-scoped proof
// would change nothing for those), the pages their write-watch collects walked and their time.
std::uint64_t fullScissorLookups = 0;
std::uint64_t partialLookups = 0;
std::uint64_t pagesWalked = 0;
double lookupUs = 0;
// How the draw's resources came about (DrawKind), for the per-kind averages.
std::size_t kind = 0;
// The flush hook's fence waits made inside this draw (index and vertex reads, the target
// lookups' flushes, the build's texture lookups): nested in the draw's GpuMutex hold, so they
// are the part of the hold that is waiting rather than working. The draw's own syncs (a
// recorded-then-waited draw's recorder Sync, a synchronous draw's SubmitAndWait) are kept apart
// in ownSyncUs: those wait by design and would otherwise count as nested hook waits.
double hookWaitUs = 0;
double ownSyncUs = 0;
};
// The resources of a draw: a recipe hit (reserved for the draw recipe step), a resource-cache
// template hit, a build, or an address-based (BDA) build.
enum DrawKind : std::size_t { KindRecipeHit, KindTemplateHit, KindBuild, KindBda, KindCount };
constexpr std::array<const char*, KindCount> DrawKindNames{"recipe hit", "template hit", "build", "BDA"};
struct DrawProfile {
std::mutex mutex;
std::array<double, KindCount> kindUs{};
std::array<std::uint64_t, KindCount> kindCounts{};
std::uint64_t fullScissorLookups = 0;
std::uint64_t partialLookups = 0;
std::uint64_t pagesWalked = 0;
double lookupUs = 0;
std::array<double, PhaseCount> totalsUs{};
// The longest single draw's time per phase, and the longest draw: the [lock] line's 'draw'
// hold max (tens of ms against an average well under a millisecond) needs a phase name.
std::array<double, PhaseCount> maxUs{};
double maxDrawUs = 0;
double hookWaitUs = 0;
double maxHookWaitUs = 0;
double ownSyncUs = 0;
// The resources build's sub-phases (ShaderResources::Timing) of draws only; dispatches report
// theirs in the [resources] line. `other` is the rest of the build (prepareAddressBindings:
// the registry lease and snapshots of an address-based build, the BDA table, the layout
// lookup), and how much of it address-based builds account for.
double bindingsUs = 0;
double uploadUs = 0;
double descriptorsUs = 0;
double otherUs = 0;
double addressOtherUs = 0;
std::uint64_t addressBuilds = 0;
std::uint64_t draws = 0;
std::uint64_t recorded = 0;
std::uint64_t waited = 0;
// Recorded draws whose write-back (BDA fault check) runs as a completion action instead of
// making the draw synchronous (see APS5_SYNC_COMPLETION_DRAWS).
std::uint64_t completion = 0;
// Render passes recorded draws began, and draws that continued the previous draw's pass.
std::uint64_t passesBegun = 0;
std::uint64_t passesContinued = 0;
std::array<std::uint64_t, SyncCount> reasons{};
// The CPU inside Graphics::Draw, split by outcome: a synchronous draw costs ten times a recorded
// one, so one average would only show the synchronous population.
double recordedUs = 0;
double waitedUs = 0;
double synchronousUs = 0;
std::uint64_t targetLookups = 0;
std::uint64_t slowLookups = 0;
double slowLookupUs = 0;
// Resource cache outcomes: hits, misses (built and inserted when reusable), entries that failed
// Revalidate, and draws that could not use the cache (synchronous, no variant id, or disabled).
// Which key words the misses differ in is the cache's own "[rescache] miss churn" line
// (ResourceCache::noteMiss compares each miss with the last key of the same variants).
std::uint64_t cacheHits = 0;
std::uint64_t cacheMisses = 0;
std::uint64_t cacheInvalidated = 0;
std::uint64_t uncacheable = 0;
// Shader validation memo (see CachedFragmentOutputs).
std::uint64_t validateHits = 0;
std::uint64_t validateMisses = 0;
// Draw recipe outcomes (DrawWithRecipe): hits, and misses by DrawRecipeMiss.
std::uint64_t recipeHits = 0;
std::array<std::uint64_t, static_cast<std::size_t>(DrawRecipeMiss::Count)> recipeMisses{};
// Indirect draws by path (IndirectDrawPath), the GPU-side ones whose records were rewritten
// with a constant, and the time of the CPU record reads (their syncs).
std::array<std::uint64_t, IndirectPathCount> indirect{};
std::uint64_t indirectRewritten = 0;
double indirectReadUs = 0;
// Draw packets that drew nothing, by DrawSkip, and their time.
std::array<std::uint64_t, static_cast<std::size_t>(DrawSkip::Count)> skips{};
std::array<double, static_cast<std::size_t>(DrawSkip::Count)> skipUs{};
std::chrono::steady_clock::time_point lastReport = std::chrono::steady_clock::now();
};
constexpr std::array<const char*, static_cast<std::size_t>(DrawSkip::Count)> DrawSkipNames{"nothing to draw", "prechecked", "thrown"};
DrawProfile& Profile() {
static DrawProfile profile;
return profile;
}
// Adds one draw's phases to the totals and prints the [draws] and [rescache] lines every 10 s.
void reportDraw(const std::array<double, PhaseCount>& us, const ShaderResources::BuildTiming* built, const DrawOutcome& outcome) {
auto& profile = Profile();
std::lock_guard lock(profile.mutex);
double drawUs = 0;
for (std::size_t i = 0; i < PhaseCount; ++i) {
profile.totalsUs[i] += us[i];
profile.maxUs[i] = std::max(profile.maxUs[i], us[i]);
drawUs += us[i];
}
profile.maxDrawUs = std::max(profile.maxDrawUs, drawUs);
profile.hookWaitUs += outcome.hookWaitUs;
profile.maxHookWaitUs = std::max(profile.maxHookWaitUs, outcome.hookWaitUs);
profile.ownSyncUs += outcome.ownSyncUs;
if (built != nullptr) {
profile.bindingsUs += built->bindingsMs * 1000.0;
profile.uploadUs += built->uploadMs * 1000.0;
profile.descriptorsUs += built->descriptorsMs * 1000.0;
const auto other = std::max(0.0, us[PhaseResources] - (built->bindingsMs + built->uploadMs + built->descriptorsMs) * 1000.0);
profile.otherUs += other;
if (outcome.addressBased) {
profile.addressOtherUs += other;
++profile.addressBuilds;
}
}
++profile.draws;
if (outcome.recorded) ++(outcome.waited ? profile.waited : profile.recorded);
if (outcome.completion) ++profile.completion;
if (outcome.passBegun) ++profile.passesBegun;
if (outcome.passContinued) ++profile.passesContinued;
++profile.reasons[outcome.reason];
(outcome.recorded ? (outcome.waited ? profile.waitedUs : profile.recordedUs) : profile.synchronousUs) += drawUs;
profile.targetLookups += outcome.targetLookups;
profile.slowLookups += outcome.slowLookups;
profile.slowLookupUs += outcome.slowLookupUs;
profile.fullScissorLookups += outcome.fullScissorLookups;
profile.partialLookups += outcome.partialLookups;
profile.pagesWalked += outcome.pagesWalked;
profile.lookupUs += outcome.lookupUs;
if (outcome.kind < KindCount) {
++profile.kindCounts[outcome.kind];
profile.kindUs[outcome.kind] += drawUs;
}
if (outcome.validateMemoized) ++(outcome.validateHit ? profile.validateHits : profile.validateMisses);
const auto now = std::chrono::steady_clock::now();
if (now - profile.lastReport < std::chrono::seconds(10)) return;
profile.lastReport = now;
const auto synchronous = profile.draws - profile.recorded - profile.waited;
const auto average = [](double total, std::uint64_t count) { return count != 0 ? total / static_cast<double>(count) : 0.0; };
char line[2048];
int n = std::snprintf(line, sizeof(line), "[draws] %llu draws over 10 s (%llu recorded avg %.0f us, of them %llu with completion; %llu recorded then waited avg %.0f us; %llu synchronous avg %.0f us; render passes %llu begun, %llu draws continued one; waited or synchronous because:", static_cast<unsigned long long>(profile.draws), static_cast<unsigned long long>(profile.recorded), average(profile.recordedUs, profile.recorded), static_cast<unsigned long long>(profile.completion), static_cast<unsigned long long>(profile.waited), average(profile.waitedUs, profile.waited), static_cast<unsigned long long>(synchronous), average(profile.synchronousUs, synchronous), static_cast<unsigned long long>(profile.passesBegun), static_cast<unsigned long long>(profile.passesContinued));
const auto room = [&] { return n > 0 && static_cast<std::size_t>(n) < sizeof(line); };
for (std::size_t i = SyncNone + 1; i < SyncCount && room(); ++i) {
if (profile.reasons[i] != 0) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu", SyncReasonNames[i], static_cast<unsigned long long>(profile.reasons[i]));
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "):");
for (std::size_t i = 0; i < PhaseCount && room(); ++i) {
if (profile.totalsUs[i] <= 0) continue;
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s=%.1fms", DrawPhaseNames[i], profile.totalsUs[i] / 1000.0);
if (i == PhaseResources && room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " (bindings %.1f, upload %.1f, descriptors %.1f, other %.1f of which %.1f in %llu address-based builds)", profile.bindingsUs / 1000.0, profile.uploadUs / 1000.0, profile.descriptorsUs / 1000.0, profile.otherUs / 1000.0, profile.addressOtherUs / 1000.0, static_cast<unsigned long long>(profile.addressBuilds));
if (i == PhaseReadTarget && room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " (%llu resident lookups, %llu of them >= 1 ms = %.1f; target lookups: full-scissor %llu / partial %llu / pages walked %llu / %.0f us)", static_cast<unsigned long long>(profile.targetLookups), static_cast<unsigned long long>(profile.slowLookups), profile.slowLookupUs / 1000.0, static_cast<unsigned long long>(profile.fullScissorLookups), static_cast<unsigned long long>(profile.partialLookups), static_cast<unsigned long long>(profile.pagesWalked), profile.lookupUs);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; per kind (avg us, count):");
for (std::size_t kind = 0; kind < KindCount && room(); ++kind) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %.0f (%llu)", DrawKindNames[kind], average(profile.kindUs[kind], profile.kindCounts[kind]), static_cast<unsigned long long>(profile.kindCounts[kind]));
}
// The longest draw and the longest single phase of any draw (which phase a long 'draw' hold
// was), plus the hook waits nested inside the draws.
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; longest draw %.1f ms, longest phase of any draw:", profile.maxDrawUs / 1000.0);
for (std::size_t i = 0; i < PhaseCount && room(); ++i) {
if (profile.maxUs[i] < 500.0) continue;
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %.1f", DrawPhaseNames[i], profile.maxUs[i] / 1000.0);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; hook waits inside draws %.1f ms (max %.1f; the draws' own syncs, %.1f ms, not counted)", profile.hookWaitUs / 1000.0, profile.maxHookWaitUs / 1000.0, profile.ownSyncUs / 1000.0);
std::uint64_t indirectCpu = 0;
for (std::size_t i = 1; i < IndirectPathCount; ++i) indirectCpu += profile.indirect[i];
if ((profile.indirect[0] != 0 || indirectCpu != 0) && room()) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; indirect: gpu-side %llu (%llu rewritten), cpu-side %llu (", static_cast<unsigned long long>(profile.indirect[0]), static_cast<unsigned long long>(profile.indirectRewritten), static_cast<unsigned long long>(indirectCpu));
for (std::size_t i = 1; i < IndirectPathCount && room(); ++i) {
if (profile.indirect[i] != 0) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu", IndirectDrawPathNames[i], static_cast<unsigned long long>(profile.indirect[i]));
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "), argument reads %.1f ms", profile.indirectReadUs / 1000.0);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; skipped packets:");
for (std::size_t i = 0; i < profile.skips.size() && room(); ++i) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu in %.1f ms", DrawSkipNames[i], static_cast<unsigned long long>(profile.skips[i]), profile.skipUs[i] / 1000.0);
}
if (room()) n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), "; recipe hits %llu, misses by reason:", static_cast<unsigned long long>(profile.recipeHits));
for (std::size_t i = 1; i < profile.recipeMisses.size() && room(); ++i) {
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s %llu", DrawRecipeMissName(static_cast<DrawRecipeMiss>(i)), static_cast<unsigned long long>(profile.recipeMisses[i]));
}
std::fprintf(stderr, "%s\n", line);
std::fprintf(stderr, "[rescache] draws: %llu hits, %llu misses, %llu invalidated, %llu uncacheable; validation memo %llu hits / %llu misses (which key words the misses differ in: the miss churn line)\n", static_cast<unsigned long long>(profile.cacheHits), static_cast<unsigned long long>(profile.cacheMisses), static_cast<unsigned long long>(profile.cacheInvalidated), static_cast<unsigned long long>(profile.uncacheable), static_cast<unsigned long long>(profile.validateHits), static_cast<unsigned long long>(profile.validateMisses));
profile.totalsUs.fill(0);
profile.maxUs.fill(0);
profile.maxDrawUs = profile.hookWaitUs = profile.maxHookWaitUs = profile.ownSyncUs = 0;
profile.bindingsUs = profile.uploadUs = profile.descriptorsUs = profile.otherUs = profile.addressOtherUs = 0;
profile.addressBuilds = 0;
profile.draws = profile.recorded = profile.waited = profile.completion = 0;
profile.passesBegun = profile.passesContinued = 0;
profile.reasons.fill(0);
profile.recordedUs = profile.waitedUs = profile.synchronousUs = 0;
profile.targetLookups = profile.slowLookups = 0;
profile.slowLookupUs = 0;
profile.fullScissorLookups = profile.partialLookups = profile.pagesWalked = 0;
profile.lookupUs = 0;
profile.kindUs.fill(0);
profile.kindCounts.fill(0);
profile.cacheHits = profile.cacheMisses = profile.cacheInvalidated = profile.uncacheable = 0;
profile.validateHits = profile.validateMisses = 0;
profile.recipeHits = 0;
profile.recipeMisses.fill(0);
profile.indirect.fill(0);
profile.indirectRewritten = 0;
profile.indirectReadUs = 0;
profile.skips.fill(0);
profile.skipUs.fill(0);
}
void countCache(std::uint64_t DrawProfile::*counter) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!profile) return;
auto& stats = Profile();
std::lock_guard lock(stats.mutex);
++(stats.*counter);
}
// ValidateShaders decodes every SPIR-V instruction of every stage on every draw. Its outcome depends
// only on the stages' compiled variants (a variant id names identical SPIR-V and binding layout),
// their push constant placement and vertex attribute shapes, and the state fields it checks, so the
// fragment output set is remembered by exactly those. Nothing here is keyed by pointer: the results
// a draw hands in live in a per-draw vector. A stage without a variant id is validated as before,
// except the rect-list control and evaluation stages, which are generated from the vertex and
// fragment results the key already names (the pipeline key treats them the same way). `memoized`
// says whether the memo applied, `hit` whether it answered. APS5_NO_VALIDATE_CACHE=1 validates
// every draw.
bool ValidationKey(const Context& context, std::span<const CompiledShader> shaders, const State& state, std::vector<std::uint64_t>& key) {
using Stage = ShaderRecompiler::ShaderStage;
static const bool disabled = std::getenv("APS5_NO_VALIDATE_CACHE") != nullptr;
const auto add = [&](auto value) { key.push_back(static_cast<std::uint64_t>(value)); };
bool keyed = !disabled;
if (keyed) {
key.reserve(40 + shaders.size() * 12);
add(shaders.size());
for (const auto& shader : shaders) {
Require(shader.program != nullptr, "missing compiled shader");
const auto& program = *shader.program;
const bool generated = state.rectList && (shader.stage == Stage::TessellationControl || shader.stage == Stage::TessellationEvaluation);
if (!generated && program.PipelineVariantId() == 0) {
keyed = false;
break;
}
add(shader.stage);
add(generated ? std::uint64_t{0} : program.PipelineVariantId());
add(shader.pushConstantOffset);
add(program.pushConstants.size());
add(program.bdaAbiVersion);
add(program.vertexAttributes.size());
for (const auto& attribute : program.vertexAttributes) {
add(attribute.location);
add(attribute.components);
add(attribute.fetchIndex);
add(attribute.formatComponents);
// The data format bits of the V# decide the attribute's signature.
add((attribute.resource.fields[3] >> 12u) & 0x7fu);
}
}
}
if (keyed) {
add(state.stages.path);
add(state.rectList);
add(state.topology);
add(state.cullMode);
add(state.blends.size());
add(context.subgroup.subgroupSize);
add(context.subgroup.supportedStages);
add(context.subgroup.supportedOperations);
add(context.fragmentShaderBarycentric);
add(state.stages.mesh.has_value());
if (state.stages.mesh) {
const auto& mesh = *state.stages.mesh;
add(mesh.inputPrimitive);
add(mesh.primitivesPerGroup);
add(mesh.verticesPerGroup);
add(mesh.maxVertices);
add(mesh.maxPrimitives);
add(mesh.threadsPerGroup);
add(mesh.ldsSizeDwords);
add(mesh.provokingVertex);
}
add(state.stages.tessellation.has_value());
if (state.stages.tessellation) {
const auto& tessellation = *state.stages.tessellation;
add(tessellation.inputControlPoints);
add(tessellation.outputControlPoints);
add(tessellation.domain);
add(tessellation.partitioning);
add(tessellation.outputTopology);
}
}
return keyed;
}
std::mutex& validationMutex() {
static std::mutex mutex;
return mutex;
}
std::map<std::vector<std::uint64_t>, std::string>& validationFailures() {
static std::map<std::vector<std::uint64_t>, std::string> failures;
return failures;
}
std::set<std::uint32_t> CachedFragmentOutputs(const Context& context, std::span<const CompiledShader> shaders, const State& state, bool& memoized, bool& hit) {
memoized = false;
hit = false;
std::vector<std::uint64_t> key;
const bool keyed = ValidationKey(context, shaders, state, key);
static std::map<std::vector<std::uint64_t>, std::set<std::uint32_t>> memo;
if (keyed) {
memoized = true;
std::lock_guard lock(validationMutex());
if (const auto found = memo.find(key); found != memo.end()) {
hit = true;
return found->second;
}
}
std::set<std::uint32_t> outputs;
try {
outputs = ValidateShaders(shaders, state, context.subgroup, context.fragmentShaderBarycentric, context.descriptorIndexing, context.imageInt64Atomics, context.geometryShader, context.sampleRateShading);
} catch (const std::exception& error) {
if (keyed) {
std::lock_guard lock(validationMutex());
auto& failures = validationFailures();
if (failures.size() >= 1024) failures.clear();
failures.emplace(std::move(key), error.what());
}
throw;
}
if (keyed) {
std::lock_guard lock(validationMutex());
// A handful of configurations recur; a runaway key space is dropped wholesale.
if (memo.size() >= 1024) memo.clear();
memo.emplace(std::move(key), outputs);
}
return outputs;
}
// The resource cache key of a recorded draw: a marker no compute key starts with (those begin with
// the stage), the device handle (the cache is process-wide and the driver replaces the headless
// device with the windowed one while workers may still use the old one: an entry's descriptor set
// and pooled buffers belong to the device that built it) and every stage's content key
// (ResourceCache::noteMiss walks this layout to attribute misses, so it changes together with it).
// With `ranges`, also the render target and the index buffer the build's alias checks compared the
// guest buffers against; without it the checks are repeated for a hit (CheckBufferAliases), since
// neither range is part of the descriptor set (the target is attached, the index buffer copied per
// draw), so a target or index ring that moves per frame does not miss on every draw. That guards a
// workload with such rings; in the profiled menu stage every draw was DRAW_INDEX_AUTO (index range
// 0) onto one fixed target, so its misses come from the stages' descriptor words themselves.
bool MovableBuffers() {
static const bool enabled = std::getenv("APS5_NO_MOVED_BUFFER_TEMPLATES") == nullptr;
return enabled;
}
ResourceCache::Key DrawResourceKey(const Context& context, std::span<const CompiledShader> shaders, const ColorTarget& target, std::uint64_t indexAddress, std::uint64_t indexBytes, bool ranges) {
ResourceCache::Key key{0xffffffffu};
const auto append64 = [&](std::uint64_t value) {
key.push_back(static_cast<std::uint32_t>(value));
key.push_back(static_cast<std::uint32_t>(value >> 32u));
};
append64(reinterpret_cast<std::uint64_t>(context.device));
key.push_back(static_cast<std::uint32_t>(shaders.size()));
for (const auto& shader : shaders) {
const auto part = ShaderResources::ContentKey(shader, true, MovableBuffers());
key.push_back(static_cast<std::uint32_t>(part.size()));
key.insert(key.end(), part.begin(), part.end());
}
if (ranges) {
append64(target.address);
append64(target.bytes);
append64(indexAddress);
append64(indexBytes);
}
return key;
}
// The alias checks the build makes for every guest buffer descriptor (ShaderResources::
// addGuestBuffer), repeated for a cached build whose own checks compared the buffers against
// another draw's render target and index buffer. The same conditions and messages, so a draw that
// would have failed its build fails its hit.
void CheckBufferAliases(std::span<const CompiledShader> shaders, const ColorTarget& target, std::uint64_t indexAddress, std::uint64_t indexBytes) {
const auto overlap = [](std::uint64_t first, std::uint64_t firstSize, std::uint64_t second, std::uint64_t secondSize) { return first < second + secondSize && second < first + firstSize; };
for (const auto& shader : shaders) {
for (const auto& binding : shader.program->bindings) {
if (binding.role != ShaderRecompiler::DescriptorRole::GuestBuffers) continue;
const auto& words = binding.guestDescriptor;
for (std::size_t offset = 0; offset + 4 <= words.size(); offset += 4) {
const ShaderRecompiler::ShaderBufferResource descriptor{{words[offset], words[offset + 1], words[offset + 2], words[offset + 3]}};
const auto address = descriptor.Base48();
const auto size = descriptor.GetSize();
if (size == 0 || address == 0) continue;
const auto element = offset / 4;
const bool written = element >= binding.bufferWritten.size() || binding.bufferWritten[element];
Require(!overlap(address, size, target.address, target.bytes), "shader buffer aliases the render target");
Require(!written || !overlap(address, size, indexAddress, indexBytes), "writable shader buffer aliases the index buffer");
}
}
}
}
}
std::array<std::uint32_t, 4> MeshIndexBufferDescriptor(const Pm4::DrawParameters& draw) {
constexpr std::uint32_t RawWord3 = 0x31016facu;
if (!draw.indexed) return {0u, 0u, 0u, RawWord3};
const auto address = draw.indexAddress;
const auto bytes = (static_cast<std::uint64_t>(draw.indexCount) * draw.indexSize + 3u) & ~std::uint64_t{3};
Require(address != 0 && bytes != 0 && bytes <= 0xffffffffu && (address >> 48u) == 0, "invalid mesh index buffer range");
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u) & 0xffffu, static_cast<std::uint32_t>(bytes), RawWord3};
}
MeshArgumentRules MeshArgumentRulesFor(const Context& context, const ShaderRecompiler::MeshConfiguration& mesh, std::uint32_t indexCount) {
const auto inputSize = mesh.inputPrimitive == 1 ? 1u : mesh.inputPrimitive == 2 ? 2u : 3u;
const auto step = mesh.inputPrimitive == 5 || mesh.inputPrimitive == 6 ? 1u : inputSize;
Require(mesh.primitivesPerGroup != 0, "mesh draw contains no complete primitive");
return {indexCount, inputSize, step, mesh.primitivesPerGroup, context.meshLimits.maxMeshWorkGroupCount[0], context.meshLimits.maxMeshWorkGroupCount[1], context.meshLimits.maxMeshWorkGroupTotalCount};
}
MeshArguments ResolveMeshArguments(const Pm4::DrawArguments& record, const MeshArgumentRules& rules) {
const auto first = record.firstVertexOrIndex;
const auto effective = first < rules.indexCount ? std::min(record.count, rules.indexCount - first) : 0u;
std::uint32_t groups = 0;
if (effective >= rules.inputSize && record.instances != 0) {
groups = (effective - rules.inputSize) / rules.step / rules.primitivesPerGroup + 1u;
if (groups > rules.maxGroups || record.instances > rules.maxInstances || groups > rules.maxTotal / record.instances) groups = 0;
}
return {groups, groups != 0 ? record.instances : 0u, groups != 0 ? 1u : 0u, effective, first};
}
std::shared_ptr<std::vector<std::shared_ptr<ShaderResources>>> DrawCopiedWriters() {
// Never destroyed: a completion action of a batch still in flight at static teardown may erase from it.
static auto* const writers = new std::shared_ptr<std::vector<std::shared_ptr<ShaderResources>>>(std::make_shared<std::vector<std::shared_ptr<ShaderResources>>>());
return *writers;
}
const char* IndirectDrawPathName(IndirectDrawPath path) {
return IndirectDrawPathNames[static_cast<std::size_t>(path)];
}
void CountIndirectDraw(IndirectDrawPath path, double readMs, bool rewritten) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!profile) return;
auto& stats = Profile();
std::lock_guard lock(stats.mutex);
++stats.indirect[static_cast<std::size_t>(path)];
if (rewritten) ++stats.indirectRewritten;
stats.indirectReadUs += readMs * 1000.0;
}
void CountDrawSkip(DrawSkip kind, double us) {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
if (!profile) return;
auto& stats = Profile();
std::lock_guard lock(stats.mutex);
++stats.skips[static_cast<std::size_t>(kind)];
stats.skipUs[static_cast<std::size_t>(kind)] += us;
}
bool DrawRecipes() {
static const bool noDrawRecipe = std::getenv("APS5_NO_DRAW_RECIPE") != nullptr;
return !noDrawRecipe;
}
const char* DrawRecipeMissName(DrawRecipeMiss miss) {
constexpr std::array<const char*, static_cast<std::size_t>(DrawRecipeMiss::Count)> names{"none", "not recordable", "target gone", "template gone", "objects gone", "proof"};
return names[static_cast<std::size_t>(miss)];
}
namespace {
// APS5_PROFILE_DRAW: the per-phase timers of one draw (DrawPhase), shared by Draw's parts and
// DrawWithRecipe.
struct DrawTimer {
bool profile;
std::chrono::steady_clock::time_point phaseStart;
std::array<double, PhaseCount> us{};
explicit DrawTimer(bool profile) : profile(profile), phaseStart(std::chrono::steady_clock::now()) {}
void phase(DrawPhase which) {
if (!profile) return;
const auto now = std::chrono::steady_clock::now();
us[which] += std::chrono::duration<double, std::micro>(now - phaseStart).count();
phaseStart = now;
}
};
// One line per draw with the phases that took time (APS5_TRACE_DRAWS), and the 10 s totals.
// `waitedBefore` is the thread's GPU waits at the draw's start and `ownWaitedMs` the draw's own
// syncs (see DrawOutcome::hookWaitUs).
void reportDrawEnd(const State& state, const DrawTimer& timer, const ShaderResources::BuildTiming* built, DrawOutcome& outcome, double waitedBefore, double ownWaitedMs, const char* suffix) {
if (!timer.profile) return;
static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr;
outcome.hookWaitUs = std::max(0.0, Recorder::ThreadWaitedMs() - waitedBefore - ownWaitedMs) * 1000.0;
outcome.ownSyncUs = ownWaitedMs * 1000.0;
if (traceDraws) {
char line[512];
int n = std::snprintf(line, sizeof(line), "[draw] %ux%u %zu targets%s:", state.renderExtent.width, state.renderExtent.height, state.colors.size(), suffix);
for (std::size_t i = 0; i < PhaseCount && n > 0 && static_cast<std::size_t>(n) < sizeof(line); ++i) {
if (timer.us[i] <= 0) continue;
n += std::snprintf(line + n, sizeof(line) - static_cast<std::size_t>(n), " %s=%.0fus", DrawPhaseNames[i], timer.us[i]);
}
std::fprintf(stderr, "%s\n", line);
}
reportDraw(timer.us, built, outcome);
}
}
DrawInputCopy CopyDrawInput(const Context& context, Recorder* recorder, std::uint64_t address, std::size_t bytes, std::size_t alignment, Recorder::SnapshotUse use) {
Require(use != Recorder::SnapshotUse::Storage, "a draw input is a vertex or index buffer");
DrawInputCopy copy;
if (recorder != nullptr && bytes != 0) {
GuestMemory::FlushGpuWrites(address, bytes);
copy.registryGeneration = GuestAllocations::GuestAllocationsGeneration_nid_postfix();
copy.generation = GuestMemory::CollectWrites(address, bytes);
if (copy.generation != 0) copy.buffer = recorder->ReusableDrawSnapshot(address, bytes, use, ©.derived);
if (copy.buffer != nullptr) {
copy.reused = true;
return copy;
}
}
copy.buffer = std::make_shared<Buffer>(context, bytes, use == Recorder::SnapshotUse::Vertex ? VK_BUFFER_USAGE_VERTEX_BUFFER_BIT : VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
GuestMemory::Read(address, copy.buffer->Bytes(), alignment);
return copy;
}
void KeepDrawInput(Recorder* recorder, std::uint64_t address, const DrawInputCopy& copy, Recorder::SnapshotUse use, std::uint32_t derived) {
if (recorder == nullptr || copy.reused || copy.generation == 0 || copy.buffer == nullptr) return;
recorder->KeepDrawSnapshot(address, copy.buffer->Bytes().size(), copy.generation, copy.registryGeneration, copy.buffer, use, derived);
}
namespace {
// The draw's inputs before its resources (prepareDrawInputs): the validated parameters, the index
// buffer copy with its highest index, the vertex buffer copies and their layout, the fragment
// outputs and the pipeline stages.
struct DrawInputs {
// An empty auto draw: nothing to record.
bool nothing = false;
std::uint64_t indexBytes = 0;
std::shared_ptr<Buffer> indices;
std::uint32_t maxIndex = 0;
VertexInputLayout vertexInput;
std::vector<std::shared_ptr<Buffer>> vertexBuffers;
std::vector<VkBuffer> vertexHandles;
std::vector<VkDeviceSize> vertexOffsets;
std::set<std::uint32_t> fragmentOutputs;
VkPipelineStageFlags shaderStages = 0;
std::uint32_t meshGroups = 0;
};
// Draw's validation, index and vertex phases. With `recipe` the fragment outputs, the pipeline
// stages and the vertex input layout are the recipe's (derived from the same compiled stages)
// instead of computed.
DrawInputs prepareDrawInputs(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, DrawOutcome& outcome, DrawTimer& timer, const DrawRecipe* recipe) {
DrawInputs inputs;
APS5_LOG_OUT_DEBUG("Draw indices=%u instances=%u indexSize=%u flags=%u indexAddress=0x%llx", draw.indexCount, draw.instanceCount, draw.indexSize, draw.flags, static_cast<unsigned long long>(draw.indexAddress));
APS5_LOG_OUT_DEBUG("State colorTarget=%u render=%ux%u colorAddress=0x%llx colorBytes=%llu colorExtent=%ux%u", state.hasColorTarget ? 1u : 0u, state.renderExtent.width, state.renderExtent.height, static_cast<unsigned long long>(state.color.address), static_cast<unsigned long long>(state.color.bytes), state.color.extent.width, state.color.extent.height);
APS5_LOG_OUT_DEBUG("Viewport x=%f y=%f w=%f h=%f minDepth=%f maxDepth=%f", state.viewport.x, state.viewport.y, state.viewport.width, state.viewport.height, state.viewport.minDepth, state.viewport.maxDepth);
APS5_LOG_OUT_DEBUG("Scissor x=%d y=%d w=%u h=%u topology=%u cullMode=0x%x frontFace=%u", state.scissor.offset.x, state.scissor.offset.y, state.scissor.extent.width, state.scissor.extent.height, static_cast<unsigned>(state.topology), static_cast<unsigned>(state.cullMode), static_cast<unsigned>(state.frontFace));
// An indirect draw: the counts live in guest memory records (Pm4::DrawParameters::IndirectDraw),
// read by the GPU from the host import or, when the GPU could not see their current bytes, by
// the CPU (Draw's `records`). The driver resolved every non-vertex-path draw before this.
const auto* args = draw.indirect ? &*draw.indirect : nullptr;
Require(draw.indexed ? draw.flags == 0 : (draw.flags & ~0x20u) == 0, "draw modifiers are unsupported");
if (draw.indexed) {
Require(draw.indexSize == 2 || draw.indexSize == 4, "only uint16 and uint32 index buffers are supported");
} else {
Require(draw.indexAddress == 0 && draw.indexSize == 0, "auto draw must not reference an index buffer");
if (args == nullptr) {
if (draw.indexCount == 0 || draw.instanceCount == 0) {
inputs.nothing = true;
return inputs;
}
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - (draw.indexCount - 1u), "auto draw vertex range overflow");
Require(draw.firstInstance <= std::numeric_limits<std::uint32_t>::max() - (draw.instanceCount - 1u), "auto draw instance range overflow");
}
}
if (args == nullptr) Require(draw.indexCount != 0 && draw.instanceCount != 0, "zero-count indexed draws are unsupported");
else Require((!state.stages.mesh || draw.indexed) && !state.stages.tessellation && !state.rectList, "indirect draw on a non-vertex path must be resolved by the driver");
inputs.indexBytes = static_cast<std::uint64_t>(draw.indexCount) * draw.indexSize;
const auto indexBytes = inputs.indexBytes;
APS5_LOG_OUT_DEBUG("Index buffer bytes=%llu", static_cast<unsigned long long>(indexBytes));
Require(indexBytes <= std::numeric_limits<std::size_t>::max(), "index buffer size overflow");
if (draw.indexed) GuestMemory::CheckRange(reinterpret_cast<const void*>(draw.indexAddress), static_cast<std::size_t>(indexBytes), draw.indexSize);
APS5_LOG_CHARS_OUT_DEBUG("Index buffer range OK");
Require(!draw.indexed || !state.hasColorTarget || draw.indexAddress + indexBytes <= state.color.address || state.color.address + state.color.bytes <= draw.indexAddress, "index buffer aliases the render target");
if (state.rectList) Require(draw.indexCount % 3 == 0, "incomplete rect-list primitive");
APS5_LOG_CHARS_OUT_DEBUG("ValidateShaders");
if (recipe != nullptr) {
inputs.fragmentOutputs = recipe->fragmentOutputs;
inputs.shaderStages = recipe->shaderStages;
} else {
inputs.fragmentOutputs = CachedFragmentOutputs(context, shaders, state, outcome.validateMemoized, outcome.validateHit);
inputs.shaderStages = PipelineStages(shaders);
}
APS5_LOG_CHARS_OUT_DEBUG("ValidateShaders OK");
APS5_LOG_OUT_DEBUG("PipelineStages=0x%x", static_cast<unsigned>(inputs.shaderStages));
if (state.stages.mesh) {
APS5_LOG_CHARS_OUT_DEBUG("Mesh path");
Require(context.meshShader, "device does not support mesh shaders");
const auto& mesh = *state.stages.mesh;
const auto inputSize = mesh.inputPrimitive == 1 ? 1u : mesh.inputPrimitive == 2 ? 2u : 3u;
Require(draw.indexCount >= inputSize && mesh.primitivesPerGroup != 0, "mesh draw contains no complete primitive");
if (args == nullptr) {
const auto step = mesh.inputPrimitive == 5 || mesh.inputPrimitive == 6 ? 1u : inputSize;
const auto primitives = (draw.indexCount - inputSize) / step + 1u;
inputs.meshGroups = (primitives - 1u) / mesh.primitivesPerGroup + 1u;
APS5_LOG_OUT_DEBUG("Mesh primitives=%u groups=%u", primitives, inputs.meshGroups);
Require(inputs.meshGroups <= context.meshLimits.maxMeshWorkGroupCount[0] && draw.instanceCount <= context.meshLimits.maxMeshWorkGroupCount[1] && static_cast<std::uint64_t>(inputs.meshGroups) * draw.instanceCount <= context.meshLimits.maxMeshWorkGroupTotalCount, "mesh draw exceeds workgroup count limits");
}
}
if (state.stages.tessellation) Require(draw.indexCount % state.stages.tessellation->inputControlPoints == 0, "incomplete tessellation patch");
// Viewport and scissor are dynamic pipeline state, so their limits are checked here per draw.
ValidateViewport(context, state.viewport);
ValidateDepthBounds(context, state);
timer.phase(PhaseValidate);
inputs.maxIndex = draw.indexed ? 0u : draw.firstVertex + draw.indexCount - 1u;
if (draw.indexed) {
const auto use = draw.indexSize == 2 ? Recorder::SnapshotUse::Index16 : Recorder::SnapshotUse::Index32;
auto copy = CopyDrawInput(context, context.recorder, draw.indexAddress, static_cast<std::size_t>(indexBytes), draw.indexSize, use);
std::uint32_t highest = copy.derived;
if (!copy.reused) {
highest = 0;
const auto bytes = copy.buffer->Bytes();
for (std::size_t offset = 0; offset < indexBytes; offset += draw.indexSize) {
std::uint32_t index = 0;
if (draw.indexSize == 2) {
std::uint16_t value = 0;
std::memcpy(&value, bytes.data() + offset, sizeof(value));
index = value;
} else {
std::memcpy(&index, bytes.data() + offset, sizeof(index));
}
highest = std::max(highest, index);
}
KeepDrawInput(context.recorder, draw.indexAddress, copy, use, highest);
}
Require(highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit");
Require(!state.stages.mesh || state.stages.mesh->inputPrimitive != 5 || !state.primitiveRestart || highest != (draw.indexSize == 2 ? 0xffffu : 0xffffffffu), "primitive restart in a triangle fan geometry draw is unsupported");
inputs.maxIndex = highest;
inputs.indices = std::move(copy.buffer);
}
APS5_LOG_CHARS_OUT_DEBUG("Index validation OK");
const auto& attributes = shaders.front().program->vertexAttributes;
// Validates the vertex descriptors; the layout also keys and builds the pipeline.
if (recipe != nullptr) inputs.vertexInput = recipe->vertexInput;
else inputs.vertexInput = BuildVertexInputLayout(context, attributes);
inputs.vertexOffsets.assign(attributes.size(), 0);
// An indexed draw's vertex offset moves every fetch: the copy must reach the last one.
if (draw.indexed) {
Require(draw.firstVertex <= std::numeric_limits<std::uint32_t>::max() - inputs.maxIndex, "indexed draw vertex range overflow");
inputs.maxIndex += draw.firstVertex;
}
std::vector<VertexFetch> fetches;
fetches.reserve(attributes.size());
for (const auto& attribute : attributes) {
// An indirect draw's counts are unknown here: the descriptor's whole range is copied.
const auto bytes = args != nullptr ? VertexBufferExtent(attribute) : VertexBufferReadSize(attribute, inputs.maxIndex, draw.instanceCount, draw.firstInstance);
const auto& fields = attribute.resource.fields;
const auto address = fields[0] | (static_cast<std::uint64_t>(fields[1] & 0xffffu) << 32u);
Require(!state.hasColorTarget || address + bytes <= state.color.address || state.color.address + state.color.bytes <= address, "vertex buffer aliases the render target");
fetches.push_back({address, address + bytes, (fields[1] >> 16u) & 0x3fffu, attribute.fetchIndex, DecodeVertexFormat(attribute).alignment});
}
const auto plan = PlanVertexCopies(fetches);
for (const auto& [begin, end] : plan.copies) {
const auto bytes = static_cast<std::size_t>(end - begin);
GuestMemory::CheckRange(reinterpret_cast<const void*>(begin), bytes, 1);
auto copy = CopyDrawInput(context, context.recorder, begin, bytes, 1, Recorder::SnapshotUse::Vertex);
KeepDrawInput(context.recorder, begin, copy, Recorder::SnapshotUse::Vertex, 0);
inputs.vertexBuffers.push_back(std::move(copy.buffer));
}
for (std::size_t i = 0; i < attributes.size(); ++i) {
inputs.vertexHandles.push_back(inputs.vertexBuffers[plan.copyOf[i]]->Handle());
inputs.vertexOffsets[i] = plan.offsets[i];
}
timer.phase(PhaseVertex);
return inputs;
}
// The resident-target proof of one attachment (StorageTexture::Refresh: FlushPending, CollectWrites
// over the target's pages, the DCC key scan of TextureClearKeys, then UnchangedSince), with the
// [draws] target-lookup accounting. `lookup` makes (or finds) the image; DrawWithRecipe refreshes
// the stored object instead.
std::shared_ptr<StorageTexture> refreshResidentTarget(const Context& context, const State& state, const ColorTarget& color, DrawOutcome& outcome, bool profile, const std::function<std::shared_ptr<StorageTexture>()>& lookup) {
const auto lookupStart = std::chrono::steady_clock::now();
const auto walkedBefore = profile ? GuestMemory::ThreadCollectedBytes() : 0;
std::shared_ptr<StorageTexture> resident;
try {
resident = lookup();
if (resident != nullptr) materializeRegisterClear(context, color, *resident);
} catch (const std::exception& error) {
static std::mutex reportMutex;
static std::set<std::uint64_t> reported;
std::lock_guard lock(reportMutex);
if (reported.insert(color.address).second) std::fprintf(stderr, "[gpu] color target 0x%llx stays non-resident: %s\n", static_cast<unsigned long long>(color.address), error.what());
}
if (resident != nullptr) materializeCmaskClear(context, color, resident.get());
if (profile) {
const auto lookupUs = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - lookupStart).count();
++outcome.targetLookups;
if (lookupUs >= 1000.0) {
++outcome.slowLookups;
outcome.slowLookupUs += lookupUs;
}
outcome.lookupUs += lookupUs;
outcome.pagesWalked += (GuestMemory::ThreadCollectedBytes() - walkedBefore) / 4096;
const bool fullScissor = state.scissor.offset.x <= 0 && state.scissor.offset.y <= 0 && state.scissor.extent.width >= color.extent.width && state.scissor.extent.height >= color.extent.height;
++(fullScissor ? outcome.fullScissorLookups : outcome.partialLookups);
}
return resident;
}
// A draw's resources (resolveDrawResources): the resource-cache template a recordable draw's
// stages repeat, or a fresh build.
struct ResolvedResources {
std::shared_ptr<ShaderResources> resources;
std::vector<ShaderResources::MovedBuffer> moved;
ResourceCache::Key contentKey;
bool cacheable = false;
const ShaderResources::BuildTiming* built = nullptr;
};
ResolvedResources resolveDrawResources(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::uint64_t indexBytes, bool recordable, DrawOutcome& outcome, DrawTimer& timer) {
ResolvedResources resolved;
APS5_LOG_CHARS_OUT_DEBUG("Creating ShaderResources");
// A recordable draw whose stages' compiled content repeats an earlier one binds that build's
// descriptor set when it is still valid (see ResourceCache; the dispatch path does the same).
// Only recordable draws take part: a synchronous draw writes its resources back, which a shared
// object must never do. Revalidate proves a hit by texture identity, which needs the texture
// caches. Push constants still come from this draw's stages. APS5_NO_DRAW_RESOURCE_CACHE=1
// builds every draw's resources as before.
static const bool noDrawResourceCache = std::getenv("APS5_NO_DRAW_RESOURCE_CACHE") != nullptr;
static const bool noTextureCache = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
// The render target and index ranges stay out of the key (see DrawResourceKey); a hit repeats
// the alias checks instead. Debug aid: APS5_NO_DRAW_KEY_TRIM=1 keys them as before.
static const bool trimKey = std::getenv("APS5_NO_DRAW_KEY_TRIM") == nullptr;
resolved.cacheable = recordable && !noDrawResourceCache && !noTextureCache && std::all_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.program != nullptr && shader.program->PipelineVariantId() != 0; });
if (resolved.cacheable) {
resolved.contentKey = DrawResourceKey(context, shaders, state.color, draw.indexAddress, indexBytes, !trimKey);
if (auto cached = SharedResourceCache().Find(resolved.contentKey)) {
const bool valid = cached->Revalidate(shaders);
auto* recorder = Recorder::Active();
std::optional<std::vector<ShaderResources::MovedBuffer>> moved;
if (valid && recorder != nullptr) moved = cached->MovedReadOnlyBuffers(shaders, *recorder);
if (moved.has_value()) {
if (trimKey) CheckBufferAliases(shaders, state.color, draw.indexAddress, indexBytes);
resolved.resources = std::move(cached);
resolved.moved = std::move(*moved);
outcome.kind = KindTemplateHit;
countCache(&DrawProfile::cacheHits);
} else if (valid) {
countCache(&DrawProfile::cacheMisses);
} else {
SharedResourceCache().Remove(resolved.contentKey);
countCache(&DrawProfile::cacheInvalidated);
}
}
} else {
countCache(&DrawProfile::uncacheable);
}
timer.phase(PhaseLookup);
if (resolved.resources == nullptr) {
resolved.resources = std::make_shared<ShaderResources>(context, shaders, state.color, draw.indexAddress, static_cast<std::size_t>(indexBytes), snapshots);
resolved.built = &resolved.resources->Timing();
outcome.addressBased = resolved.resources->HoldsLease();
outcome.kind = outcome.addressBased ? KindBda : KindBuild;
if (resolved.cacheable) countCache(&DrawProfile::cacheMisses);
}
timer.phase(PhaseResources);
APS5_LOG_CHARS_OUT_DEBUG("ShaderResources created");