Repository navigation
Expand file tree
/
Copy pathResourceMaterializer.cpp
More file actions
2686 lines (2530 loc) · 152 KB
/
Copy pathResourceMaterializer.cpp
File metadata and controls
2686 lines (2530 loc) · 152 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 "Optimization/ResourceMaterializer.hpp"
#include "Optimization/SrtWalker/SrtFlatSlotClasses.hpp"
#include "Optimization/SrtWalker/SrtEvaluator.hpp"
#include "Optimization/SrtWalker/SrtInstructionPredicates.hpp"
#include "Optimization/ShaderStageInputInfo.hpp"
#include "RdnaDecoder/RdnaDescriptorFormat.hpp"
#include "RdnaDecoder/RdnaImageOpDecoder.hpp"
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
#include "SpirvBackend/SpirvBufferFormat.hpp"
#include "ThreadOwned.hpp"
#include "ImageTableAbi.hpp"
#include "prx/libc/include/HostThreadLocal.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <unordered_map>
#include <unordered_set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace ShaderRecompiler {
namespace {
using ImageTableAbi::PoisonReason;
std::atomic<std::uint64_t> specializationNanoseconds{0};
std::atomic<std::uint64_t> evaluateNanoseconds{0};
std::atomic<std::uint64_t> materializeNanoseconds{0};
bool MaterializeProfiled() {
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
return profile;
}
struct DecodedImage {
IrTextureNumericClass numericClass = IrTextureNumericClass::Unsupported;
RdnaImageDimension dimension = RdnaImageDimension::Unknown;
std::uint32_t mipCount = 1;
IrBufferFormat conversionFormat = IrBufferFormat::Invalid;
std::uint32_t shaderSwizzle = ShaderImageIdentitySwizzle;
bool cube = false;
bool fmask = false;
bool depthBits = false;
bool depthUnorm16 = false;
IrBufferFormat packedFormat = IrBufferFormat::Invalid;
bool srgbDecode = false;
};
ShaderBufferResource decodeBufferDescriptor(const DescriptorValue& value) {
if (value.dwordCount != 4u) {
throw std::runtime_error("buffer descriptor has an invalid width");
}
ShaderBufferResource result;
for (std::uint32_t i = 0; i < 4u; i++) {
result.fields[i] = value.dwords[i];
}
return result;
}
bool nullImageDescriptor(const DescriptorValue& descriptor) {
return descriptor.dwords[0] == 0u && (descriptor.dwords[1] & 0xffu) == 0u;
}
ImageType rawImageType(const DescriptorValue& descriptor) {
return static_cast<ImageType>((descriptor.dwords[3] >> 28u) & 0xfu);
}
bool nullImageDescriptor(const ImageResource& image, const DescriptorValue& descriptor) {
if (nullImageDescriptor(descriptor)) return true;
return static_cast<std::uint32_t>(rawImageType(descriptor)) <= 1u && image.table == NoTable && image.read && !image.written && !image.atomic;
}
IrBufferFormat rawImageFormat(const DescriptorValue& descriptor) {
return static_cast<IrBufferFormat>((descriptor.dwords[1] >> 20u) & 0x1ffu);
}
std::uint32_t descriptorImageSwizzle(const DescriptorValue& descriptor) {
return descriptor.dwords[3] & 0xfffu;
}
bool descriptorIsCube(const DescriptorValue& descriptor) {
return rawImageType(descriptor) == ImageType::Cube;
}
bool descriptorIsShortCube(const DescriptorValue& descriptor) {
const auto depth = descriptor.dwords[4] & 0x1fffu;
const auto baseArray = (descriptor.dwords[4] >> 16u) & 0x1fffu;
return descriptorIsCube(descriptor) && descriptor.dwordCount == 8u && baseArray < depth && depth - baseArray < 5u;
}
RdnaImageDimension descriptorDimension(const DescriptorValue& descriptor, RdnaImageDimension requested) {
const bool wantArray = requested == RdnaImageDimension::Dim1DArray || requested == RdnaImageDimension::Dim2DArray || requested == RdnaImageDimension::Dim2DMsaaArray;
switch (rawImageType(descriptor)) {
case ImageType::Color1D:
return RdnaImageDimension::Dim1D;
case ImageType::Color1DArray:
return wantArray ? RdnaImageDimension::Dim1DArray : RdnaImageDimension::Dim1D;
case ImageType::Color3D:
return RdnaImageDimension::Dim3D;
case ImageType::Cube:
return RdnaImageDimension::Dim2DArray;
case ImageType::Color2DArray:
return wantArray || requested == RdnaImageDimension::Dim3D ? RdnaImageDimension::Dim2DArray : RdnaImageDimension::Dim2D;
case ImageType::Color2DMsaaArray:
return wantArray ? RdnaImageDimension::Dim2DMsaaArray : RdnaImageDimension::Dim2DMsaa;
case ImageType::Color2D:
return RdnaImageDimension::Dim2D;
case ImageType::Color2DMsaa:
return RdnaImageDimension::Dim2DMsaa;
default:
throw std::runtime_error("image descriptor has an unsupported type");
}
}
std::uint32_t imageCoordinates(RdnaImageDimension dimension) {
switch (dimension) {
case RdnaImageDimension::Dim1D: return 1u;
case RdnaImageDimension::Dim1DArray: case RdnaImageDimension::Dim2D: return 2u;
case RdnaImageDimension::Dim2DMsaaArray: return 4u;
default: return 3u;
}
}
bool multisamplePlaneRead(const ImageResource& image) {
return image.dimension == RdnaImageDimension::Dim2D && image.resourceClass == ImageResourceClass::Sampled && image.table == NoTable && !image.depthCompare && !image.r128 && image.cubeFaceCompatible;
}
bool undefinedImageWords(const DescriptorValue& descriptor) {
const auto type = static_cast<std::uint32_t>(rawImageType(descriptor));
return !nullImageDescriptor(descriptor) && type >= 2u && (type < static_cast<std::uint32_t>(ImageType::Color1D) || !IsDefinedImageFormat(rawImageFormat(descriptor)));
}
bool validImageDescriptor(const DescriptorValue& descriptor, bool r128) {
const auto type = rawImageType(descriptor);
const auto format = rawImageFormat(descriptor);
if (type < ImageType::Color1D || !IsDefinedImageFormat(format)) {
return false;
}
if (r128 && type != ImageType::Color1D && type != ImageType::Color2D && type != ImageType::Color2DMsaa) {
return false;
}
if (type == ImageType::Color2DMsaa || type == ImageType::Color2DMsaaArray) {
const auto baseLevel = (descriptor.dwords[3] >> 12u) & 0xfu;
const auto fragments = (descriptor.dwords[3] >> 16u) & 0xfu;
const auto maxMip = (descriptor.dwords[5] >> 4u) & 0xfu;
return baseLevel == 0u && fragments >= 1u && fragments <= 3u && (r128 || maxMip == fragments);
}
return true;
}
std::uint32_t storageMipCount(const ImageResource& base, const DescriptorValue& descriptor) {
if (base.mipMode != ImageMipMode::DynamicStorage || nullImageDescriptor(base, descriptor)) {
return 1u;
}
const auto mipBase = (descriptor.dwords[3] >> 12u) & 0xfu;
const auto mipLast = (descriptor.dwords[3] >> 16u) & 0xfu;
return mipBase <= mipLast ? mipLast - mipBase + 1u : 0u;
}
struct ImageDecode {
DecodedImage decoded;
std::optional<PoisonReason> reason;
std::string detail;
};
ImageDecode rejectImage(PoisonReason reason, std::string detail) {
ImageDecode result;
result.reason = reason;
result.detail = std::move(detail);
return result;
}
PoisonReason invalidImageReason(const DescriptorValue& descriptor) {
const auto type = rawImageType(descriptor);
if (type < ImageType::Color1D) {
return PoisonReason::NotImage;
}
if (!IsDefinedImageFormat(rawImageFormat(descriptor))) {
return PoisonReason::InvalidFormat;
}
if (type == ImageType::Color2DMsaa || type == ImageType::Color2DMsaaArray) {
return PoisonReason::Multisampled;
}
return PoisonReason::Dimension;
}
ImageDecode inspectImageDescriptor(const DescriptorValue& descriptor, const ImageResource& base, std::uint32_t srgbDecodeFormats) {
ImageDecode result;
auto& decoded = result.decoded;
decoded.mipCount = storageMipCount(base, descriptor);
if (decoded.mipCount == 0u) {
return rejectImage(PoisonReason::InvalidFormat, "storage image descriptor has an invalid mip range");
}
if (nullImageDescriptor(base, descriptor)) {
decoded.numericClass = base.atomic ? IrTextureNumericClass::Uint : IrTextureNumericClass::Float;
decoded.dimension = RdnaImageDimension::Dim2D;
decoded.cube = false;
return result;
}
if (base.resourceClass == ImageResourceClass::None || (base.atomic && base.resourceClass != ImageResourceClass::Storage)) {
throw std::runtime_error("image resource has an invalid class");
}
if (!validImageDescriptor(descriptor, base.r128)) {
return rejectImage(invalidImageReason(descriptor), "image descriptor is invalid");
}
const bool queryLayers = base.dimension == RdnaImageDimension::Dim1D && base.dimensionQueryOnly && rawImageType(descriptor) == ImageType::Color2DArray;
decoded.dimension = descriptorDimension(descriptor, queryLayers ? RdnaImageDimension::Dim2DArray : base.dimension);
if (base.depthCompare) {
if (decoded.dimension == RdnaImageDimension::Dim1D) {
decoded.dimension = RdnaImageDimension::Dim2D;
} else if (decoded.dimension == RdnaImageDimension::Dim1DArray) {
decoded.dimension = RdnaImageDimension::Dim2DArray;
}
}
if (GcnGuestShaders() && imageCoordinates(decoded.dimension) != imageCoordinates(base.dimension)) {
throw std::runtime_error("GCN image instruction on a descriptor of type " + std::to_string(static_cast<std::uint32_t>(rawImageType(descriptor))) + " needs a different address count than its inferred dimension; not implemented");
}
decoded.cube = descriptorIsCube(descriptor);
const auto format = rawImageFormat(descriptor);
if (decoded.dimension == RdnaImageDimension::Dim2DMsaa && rawImageType(descriptor) == ImageType::Color2DMsaa && multisamplePlaneRead(base) && !IsFmaskTextureFormat(format) && !IsDepthBitsTexture(descriptor.dwords[1], descriptor.dwords[3])) decoded.dimension = RdnaImageDimension::Dim2D;
if (base.atomic64 && format != IrBufferFormat::Format32_32UInt && format != IrBufferFormat::Format32_32SInt && format != IrBufferFormat::Format32_32Float) {
return rejectImage(PoisonReason::InvalidFormat, "64-bit atomic image descriptor uses an unsupported format " + std::to_string(static_cast<std::uint32_t>(format)));
}
if (base.atomic && !base.atomic64 && format != IrBufferFormat::Format32UInt && format != IrBufferFormat::Format32SInt && format != IrBufferFormat::Format32Float) {
return rejectImage(PoisonReason::InvalidFormat, "atomic image descriptor uses an unsupported format " + std::to_string(static_cast<std::uint32_t>(format)));
}
const bool storage = base.resourceClass == ImageResourceClass::Storage;
const bool table = base.table != NoTable;
if (decoded.cube && (storage || !base.sampledOnly) && descriptorIsShortCube(descriptor)) {
return rejectImage(PoisonReason::Dimension, "a cube descriptor with fewer than six slices is implemented only for sampling; loads, stores and dimension queries through it stop at its last slice");
}
decoded.fmask = IsFmaskTextureFormat(format);
if (decoded.fmask && !base.fmaskCompatible) return rejectImage(PoisonReason::Fmask, "FMASK requires a direct 32-bit image load");
if (decoded.fmask && (storage || base.depthCompare || table)) {
return rejectImage(PoisonReason::Fmask, "FMASK requires a direct sampled image load");
}
if (decoded.fmask && !FmaskLayoutOf(format).has_value()) return rejectImage(PoisonReason::Fmask, "FMASK format is not implemented");
if (decoded.fmask && ((descriptor.dwords[6] & (1u << 20u)) != 0u || ((descriptor.dwords[6] & (1u << 21u)) != 0u && (descriptor.dwords[6] >> 24u) == 0u && descriptor.dwords[7] == 0u))) return rejectImage(PoisonReason::Fmask, "FMASK CMASK compression is not implemented without readable metadata");
if (decoded.fmask && (descriptor.dwords[6] & (1u << 21u)) != 0u && format != IrBufferFormat::Fmask32_S8_F8) return rejectImage(PoisonReason::Fmask, "FMASK CMASK compression is implemented only for 8-sample, 8-fragment FMASK");
if (decoded.fmask && (base.packed || base.byElements != 0u)) return rejectImage(PoisonReason::Fmask, "packed FMASK image reads are not implemented");
for (std::uint32_t component = 0; decoded.fmask && component < 4u; ++component) {
const auto selector = (descriptorImageSwizzle(descriptor) >> (component * 3u)) & 7u;
if (selector != 0u && selector != 1u && selector != 4u) return rejectImage(PoisonReason::Fmask, "FMASK destination channel selector is not implemented");
}
if (base.packed) {
if (table || (!storage && descriptorImageSwizzle(descriptor) != ShaderImageIdentitySwizzle)) {
return rejectImage(PoisonReason::InvalidFormat, "packed image access requires a direct image, with identity swizzle when sampled");
}
decoded.packedFormat = format;
}
if (base.byElements != 0u) {
const bool eightBit = format == IrBufferFormat::Format8UNorm || format == IrBufferFormat::Format8SNorm || format == IrBufferFormat::Format8UInt || format == IrBufferFormat::Format8SInt;
const bool sixteenBit = format == IrBufferFormat::Format16UNorm || format == IrBufferFormat::Format16SNorm || format == IrBufferFormat::Format16UInt || format == IrBufferFormat::Format16SInt || format == IrBufferFormat::Format16Float;
const bool eightBitPair = format == IrBufferFormat::Format8_8UNorm || format == IrBufferFormat::Format8_8SNorm || format == IrBufferFormat::Format8_8UInt || format == IrBufferFormat::Format8_8SInt;
const bool packedEight = format == IrBufferFormat::Format8UNorm || format == IrBufferFormat::Format8UInt || format == IrBufferFormat::Format8SInt;
const bool packedSixteen = format == IrBufferFormat::Format16UNorm || format == IrBufferFormat::Format16UInt || format == IrBufferFormat::Format16SInt || format == IrBufferFormat::Format8_8UNorm || format == IrBufferFormat::Format8_8UInt || format == IrBufferFormat::Format8_8SInt;
const bool measured = base.packed ? packedEight || (base.byElements == 2u && packedSixteen)
: base.byElements == 4u ? base.byComponents == 1u && eightBit : base.byElements == 2u && (base.byComponents == 1u ? eightBit || sixteenBit : base.byComponents == 2u && eightBitPair);
if (!measured || descriptorImageSwizzle(descriptor) != ShaderImageIdentitySwizzle || rawImageType(descriptor) != ImageType::Color2D || table) {
return rejectImage(PoisonReason::InvalidFormat, base.packed ? "MIMG PCK2/PCK4 requires a direct, identity-swizzled 2D UNORM, UINT or SINT image whose elements fill one dword: R8, R16 or RG8 for PCK2, R8 for PCK4"
: "MIMG BY2/BY4 requires a direct, identity-swizzled 2D image whose elements fill one dword: R8, R16 or RG8 for BY2, R8 for BY4");
}
}
const bool nativeRepacked = (format == IrBufferFormat::Format10_11_11Float || format == IrBufferFormat::Format11_11_10Float) && !storage && !base.packed;
const auto remappedFormat = storage ? RemapStorageTextureFormat(format) : RemapTextureFormat(format);
decoded.conversionFormat = remappedFormat != format && !nativeRepacked ? format : IrBufferFormat::Invalid;
if (format == IrBufferFormat::Format11_11_10UNorm || ((format == IrBufferFormat::Format10_11_11Float || format == IrBufferFormat::Format11_11_10Float) && !nativeRepacked)) {
const bool floating = format == IrBufferFormat::Format10_11_11Float || format == IrBufferFormat::Format11_11_10Float;
if (!base.srgbDecodeCompatible) {
if (floating) return rejectImage(PoisonReason::Conversion, "samples or gathers a converted float image, or queries its LOD, which is not implemented");
if (storage || base.depthCompare || (base.emulatedCompare & EmulatedCompare::ConvertedSampleUnsupported) != 0u) return rejectImage(PoisonReason::Conversion, "sampling, gathering or querying LOD of a converted unorm image is not implemented");
if (base.table != NoTable) return rejectImage(PoisonReason::Conversion, "samples a converted unorm image selected through an image table, which is not implemented");
if (decoded.cube || (decoded.dimension != RdnaImageDimension::Dim2D && decoded.dimension != RdnaImageDimension::Dim2DArray)) return rejectImage(PoisonReason::Conversion, "samples a converted unorm image that is not a 2D or 2D array view, which is not implemented");
if ((base.emulatedCompare & EmulatedCompare::ConvertedSampleRequiresSingleLevel) != 0u && ((descriptor.dwords[3] >> 12u) & 0xfu) != ((descriptor.dwords[3] >> 16u) & 0xfu)) return rejectImage(PoisonReason::Conversion, "samples a converted unorm image with several mip levels at a LOD that is not 0, which is not implemented");
}
if (!base.depthBitsCompatible) return rejectImage(PoisonReason::Conversion, floating ? "reads or writes a converted float image with 16-bit data, which is not implemented" : "reads or writes a converted unorm image with 16-bit data, which is not implemented");
for (std::uint32_t component = 0; component < 4u; ++component) {
if (((descriptorImageSwizzle(descriptor) >> (component * 3u)) & 7u) == 7u) return rejectImage(PoisonReason::Conversion, "selects a channel the converted image format does not have");
}
}
if (decoded.fmask && format != IrBufferFormat::Fmask32_S8_F8) decoded.conversionFormat = FmaskExpansion;
decoded.srgbDecode = !storage && !base.depthCompare && (srgbDecodeFormats & SrgbDecodeBit(format)) != 0u;
if (decoded.srgbDecode && !base.srgbDecodeCompatible) {
return rejectImage(PoisonReason::SrgbUnsupported, "samples or gathers an sRGB image the device cannot sample, which is not implemented");
}
if (storage || decoded.conversionFormat != IrBufferFormat::Invalid) {
decoded.shaderSwizzle = descriptorImageSwizzle(descriptor);
}
const bool wideSint = format == IrBufferFormat::Format32SInt || format == IrBufferFormat::Format32_32SInt || format == IrBufferFormat::Format32_32_32_32SInt;
const bool narrowSint = format == IrBufferFormat::Format16SInt || format == IrBufferFormat::Format8_8SInt || format == IrBufferFormat::Format16_16SInt || format == IrBufferFormat::Format8_8_8_8SInt || format == IrBufferFormat::Format16_16_16_16SInt;
const bool rawSintStorage = storage && (wideSint || (narrowSint && !base.packed)) && base.written && !base.read && !base.atomic;
const bool rawFloat16Storage = storage && base.written && !base.read && !base.atomic &&
(remappedFormat == IrBufferFormat::Format16Float || remappedFormat == IrBufferFormat::Format16_16Float || remappedFormat == IrBufferFormat::Format16_16_16_16Float);
decoded.numericClass = base.atomic || decoded.fmask ? IrTextureNumericClass::Uint : nativeRepacked ? IrTextureNumericClass::Float : SampledTextureNumericClass(remappedFormat);
if (!storage && !base.depthCompare && IsDepthBitsTexture(descriptor.dwords[1], descriptor.dwords[3])) {
decoded.depthBits = true;
if (!base.depthBitsCompatible) return rejectImage(PoisonReason::DepthBits16, "runtime image reads depth bits as unsupported 16-bit results");
decoded.depthUnorm16 = DepthBitsTextureWidth(descriptor.dwords[1], descriptor.dwords[3]) == 16u;
decoded.numericClass = IrTextureNumericClass::Float;
decoded.shaderSwizzle = descriptorImageSwizzle(descriptor);
}
if (storage) {
if ((!rawSintStorage && decoded.numericClass == IrTextureNumericClass::Sint) || decoded.numericClass == IrTextureNumericClass::Unsupported) {
return rejectImage(PoisonReason::NumericClass, "storage image descriptor uses an unsupported format");
}
if (rawSintStorage) {
decoded.numericClass = IrTextureNumericClass::Uint;
}
if (rawFloat16Storage) {
decoded.numericClass = IrTextureNumericClass::Uint;
}
if ((rawSintStorage || rawFloat16Storage || (base.atomic && format == IrBufferFormat::Format32SInt)) && !base.packed) {
decoded.conversionFormat = format;
}
} else if (decoded.numericClass == IrTextureNumericClass::Unsupported || (base.depthCompare && decoded.numericClass != IrTextureNumericClass::Float)) {
char words[96];
std::snprintf(words, sizeof(words), " (T# %08x %08x %08x %08x %08x %08x %08x %08x)", descriptor.dwords[0], descriptor.dwords[1], descriptor.dwords[2], descriptor.dwords[3], descriptor.dwords[4], descriptor.dwords[5], descriptor.dwords[6], descriptor.dwords[7]);
return rejectImage(PoisonReason::NumericClass, std::string("sampled image descriptor uses an unsupported format") + words);
}
return result;
}
DecodedImage decodeImageDescriptor(const DescriptorValue& descriptor, const ImageResource& base, std::uint32_t srgbDecodeFormats) {
auto result = inspectImageDescriptor(descriptor, base, srgbDecodeFormats);
if (result.reason.has_value()) {
throw std::runtime_error(result.detail);
}
return result.decoded;
}
bool requiresPointSampler(const ImageResource& mode) {
return mode.numericClass == IrTextureNumericClass::Uint || mode.numericClass == IrTextureNumericClass::Sint || mode.conversionFormat != IrBufferFormat::Invalid || mode.depthBits;
}
bool reducesBetweenTexels(std::uint32_t word0, std::uint32_t filter) {
return ((word0 >> 29u) & 3u) != 0u && (((filter >> 20u) & 0xfu) != 0u || ((filter >> 26u) & 3u) == 2u);
}
std::string hexText(std::uint64_t value) {
char text[24];
std::snprintf(text, sizeof(text), "%llx", static_cast<unsigned long long>(value));
return text;
}
std::uint32_t TableKeyScanLimit() {
static const std::uint32_t limit = [] {
const char* text = std::getenv("APS5_IMAGE_TABLE_KEY_SCAN");
return text != nullptr ? static_cast<std::uint32_t>(std::strtoul(text, nullptr, 0)) : 256u;
}();
return limit;
}
bool TableStrict() {
static const bool strict = [] {
const char* text = std::getenv("APS5_IMAGE_TABLE_STRICT");
return text != nullptr && std::strcmp(text, "0") != 0;
}();
return strict;
}
bool TableTraced() {
static const bool traced = std::getenv("APS5_TRACE_IMAGE_TABLE") != nullptr;
return traced;
}
constexpr std::size_t PoisonReasonCount = static_cast<std::size_t>(PoisonReason::Count);
enum class NarrowSkip : std::size_t { Value, NotBuffer, KeyScan, Pending, Unmapped, Count };
constexpr std::array<const char*, static_cast<std::size_t>(NarrowSkip::Count)> NarrowSkipNames{"value", "not-buffer", "key-scan", "pending-write", "unmapped"};
struct TableCounters {
std::atomic<std::uint64_t> snapshots{0};
std::atomic<std::uint64_t> tables{0};
std::atomic<std::uint64_t> keys{0};
std::array<std::atomic<std::uint64_t>, PoisonReasonCount> poison{};
std::atomic<std::uint64_t> narrowed{0};
std::atomic<std::uint64_t> narrowSkipped{0};
std::array<std::atomic<std::uint64_t>, static_cast<std::size_t>(NarrowSkip::Count)> narrowSkips{};
std::atomic<std::uint64_t> narrowPositions{0};
std::atomic<std::uint64_t> selected{0};
std::atomic<std::uint64_t> reusedUnwritten{0};
std::atomic<std::uint64_t> reusedCompared{0};
std::atomic<std::uint64_t> nanoseconds{0};
std::atomic<long long> lastReport{0};
};
TableCounters& tableCounters() {
static TableCounters counters;
return counters;
}
struct TableReuseTotals {
std::atomic<std::uint64_t> unwritten{0};
std::atomic<std::uint64_t> compared{0};
std::atomic<std::uint64_t> wordsRead{0};
std::atomic<std::uint64_t> shared{0};
std::atomic<std::uint64_t> columns{0};
std::atomic<std::uint64_t> resolutions{0};
std::atomic<std::uint64_t> resolutionsShared{0};
};
TableReuseTotals& tableReuseTotals() {
static TableReuseTotals totals;
return totals;
}
void reportTables() {
if (!MaterializeProfiled()) return;
auto& counters = tableCounters();
const auto now = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
auto last = counters.lastReport.load(std::memory_order_relaxed);
if (last == 0) {
counters.lastReport.compare_exchange_strong(last, now, std::memory_order_relaxed);
return;
}
if (now - last < 10'000'000'000ll || !counters.lastReport.compare_exchange_strong(last, now, std::memory_order_relaxed)) return;
const auto snapshots = counters.snapshots.exchange(0, std::memory_order_relaxed);
if (snapshots == 0) return;
std::string poison;
for (std::size_t reason = 0; reason < PoisonReasonCount; reason++) {
const auto count = counters.poison[reason].exchange(0, std::memory_order_relaxed);
if (count == 0) continue;
poison += " " + std::string(ImageTableAbi::PoisonReasonName(static_cast<PoisonReason>(reason))) + "=" + std::to_string(count);
}
std::string skips;
for (std::size_t reason = 0; reason < counters.narrowSkips.size(); reason++) {
const auto count = counters.narrowSkips[reason].exchange(0, std::memory_order_relaxed);
if (count == 0) continue;
skips += " " + std::string(NarrowSkipNames[reason]) + "=" + std::to_string(count);
if (reason == static_cast<std::size_t>(NarrowSkip::KeyScan)) skips += " (up to " + std::to_string(counters.narrowPositions.exchange(0, std::memory_order_relaxed)) + " positions, APS5_IMAGE_TABLE_KEY_SCAN " + std::to_string(TableKeyScanLimit()) + ")";
}
std::fprintf(stderr, "[image-table] (10 s): %llu snapshots, %llu tables, %llu keys, %llu selected records, structural poison:%s, narrowing %llu applied / %llu skipped%s%s, reused %llu unwritten / %llu compared, %.1f ms\n",
static_cast<unsigned long long>(snapshots), static_cast<unsigned long long>(counters.tables.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(counters.keys.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(counters.selected.exchange(0, std::memory_order_relaxed)), poison.empty() ? " none" : poison.c_str(),
static_cast<unsigned long long>(counters.narrowed.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(counters.narrowSkipped.exchange(0, std::memory_order_relaxed)), skips.empty() ? "" : ":", skips.c_str(), static_cast<unsigned long long>(counters.reusedUnwritten.exchange(0, std::memory_order_relaxed)), static_cast<unsigned long long>(counters.reusedCompared.exchange(0, std::memory_order_relaxed)), static_cast<double>(counters.nanoseconds.exchange(0, std::memory_order_relaxed)) / 1e6);
}
enum class RecordState : std::uint8_t { OutsideDomain, Read, Unmapped, Carried };
struct ColumnContents {
SharedValues<std::uint32_t> codes;
SharedValues<DescriptorValue> words;
SharedValues<std::pair<std::uint64_t, std::uint64_t>> readRanges;
std::uint32_t poisoned = 0;
std::uint32_t unmapped = 0;
std::uint32_t carried = 0;
};
struct ColumnRecords {
std::uint64_t base = 0;
std::uint64_t size = 0;
std::uint32_t records = 0;
std::uint32_t keys = 0;
std::uint32_t fault = 0;
bool narrowed = false;
bool outside = false;
bool sealed = false;
std::vector<RecordState> states;
std::vector<std::uint32_t> words;
std::vector<DescriptorValue> distinct;
std::vector<std::pair<std::uint64_t, std::uint64_t>> readRanges;
ColumnContents contents;
};
struct TableTrace {
std::uint64_t base = 0;
std::uint64_t size = 0;
std::uint32_t records = 0;
std::uint32_t keys = 0;
std::uint32_t poison = 0;
bool narrowed = false;
bool operator==(const TableTrace& other) const = default;
};
void traceTable(const IrResourcePlan& plan, std::uint32_t table, const TableColumn& column, const TableTrace& trace) {
static std::mutex mutex;
static std::map<std::pair<std::uint64_t, std::uint32_t>, TableTrace> seen;
std::lock_guard lock(mutex);
auto& last = seen[{plan.shaderHash, table}];
if (last == trace) return;
last = trace;
std::fprintf(stderr, "[image-table] shader 0x%llx table %u (%s): base 0x%llx size 0x%llx stride 0x%x addend 0x%x offset 0x%x dwords %u, %u records, %u keys%s, %u structural poison\n", static_cast<unsigned long long>(plan.shaderHash), table, column.sampler ? "sampler" : "image", static_cast<unsigned long long>(trace.base), static_cast<unsigned long long>(trace.size), column.stride, column.addend, column.offset, column.dwordCount, trace.records, trace.keys, trace.narrowed ? " (narrowed)" : "", trace.poison);
}
bool TableSnapshotReuse() {
static const bool enabled = std::getenv("APS5_NO_TABLE_SNAPSHOT_REUSE") == nullptr;
return enabled;
}
struct ColumnKey {
std::uint64_t base = 0;
std::uint64_t size = 0;
std::uint32_t records = 0;
std::uint32_t keys = 0;
std::uint32_t stride = 0;
std::uint32_t addend = 0;
std::uint32_t offset = 0;
std::uint32_t dwordCount = 0;
std::uint32_t maxKey = 0;
std::uint32_t foldedAddend = 0;
std::uint32_t foldedCarry = 0;
bool address = false;
bool sampler = false;
bool operator==(const ColumnKey& other) const = default;
};
struct ColumnMemo {
ColumnKey key;
std::shared_ptr<const SrtGuestWords> read;
ColumnContents contents;
std::uint64_t low = 0;
std::uint64_t high = 0;
std::size_t Footprint() const {
return read->words.size() + read->runs.size() * 3u + contents.codes.size() + contents.words.size() * 9u + contents.readRanges.size() * 4u;
}
};
constexpr std::size_t ColumnMemoEntries = 16;
constexpr std::size_t ColumnMemoWords = std::size_t{1} << 22u;
std::vector<ColumnMemo>& ColumnMemos() {
thread_local std::vector<ColumnMemo>* slot = nullptr;
return ThreadOwned(slot);
}
template <typename TSlot>
struct SlotScratch {
std::vector<TSlot> slots;
std::uint32_t stamp = 0;
bool leased = false;
};
template <typename TSlot, typename TTag>
SlotScratch<TSlot>& threadScratch() {
return HostThreadLocal<SlotScratch<TSlot>, TTag>();
}
constexpr std::size_t KeptScratchBytes = std::size_t{2} << 20u;
template <typename TSlot>
class SlotLease {
public:
explicit SlotLease(SlotScratch<TSlot>& shared) : scratch(shared.leased ? own : shared) {
scratch.leased = true;
Clear();
}
SlotLease(const SlotLease&) = delete;
SlotLease& operator=(const SlotLease&) = delete;
~SlotLease() {
if (scratch.slots.size() * sizeof(TSlot) > KeptScratchBytes) std::vector<TSlot>().swap(scratch.slots);
scratch.leased = false;
}
void Clear() {
if (++scratch.stamp != 0u) return;
std::fill(scratch.slots.begin(), scratch.slots.end(), TSlot{});
scratch.stamp = 1u;
}
std::vector<TSlot>& Slots() {
return scratch.slots;
}
const std::vector<TSlot>& Slots() const {
return scratch.slots;
}
std::uint32_t Stamp() const {
return scratch.stamp;
}
private:
SlotScratch<TSlot> own;
SlotScratch<TSlot>& scratch;
};
struct DenseSlot {
std::uint32_t stamp = 0;
std::uint32_t value = 0;
};
class DenseScratchMap {
public:
DenseScratchMap(SlotScratch<DenseSlot>& shared, std::size_t count) : lease(shared), keys(count) {
if (lease.Slots().size() < keys) lease.Slots().resize(keys);
}
void Clear() {
lease.Clear();
}
std::optional<std::uint32_t> Find(std::size_t key) const {
if (key >= keys) throw std::out_of_range("dense scratch map key is out of range");
const auto& slot = lease.Slots()[key];
return slot.stamp == lease.Stamp() ? std::optional<std::uint32_t>(slot.value) : std::nullopt;
}
void Set(std::size_t key, std::uint32_t value) {
if (key >= keys) throw std::out_of_range("dense scratch map key is out of range");
lease.Slots()[key] = {lease.Stamp(), value};
}
private:
SlotLease<DenseSlot> lease;
std::size_t keys;
};
struct HashSlot {
std::uint64_t hash = 0;
std::uint32_t stamp = 0;
std::uint32_t value = 0;
};
std::uint64_t hashWords(std::span<const std::uint32_t> words, std::uint64_t seed) {
std::uint64_t hash = 0xcbf29ce484222325ull ^ seed;
for (const auto word : words) hash = (hash ^ word) * 0x100000001b3ull;
hash ^= hash >> 33u;
hash *= 0xff51afd7ed558ccdull;
return hash ^ (hash >> 33u);
}
class HashScratchIndex {
public:
explicit HashScratchIndex(SlotScratch<HashSlot>& shared) : lease(shared) {}
template <typename TEqual>
std::optional<std::uint32_t> Find(std::uint64_t hash, TEqual&& equal) const {
const auto& slots = lease.Slots();
if (slots.empty()) return std::nullopt;
const auto mask = slots.size() - 1u;
for (auto at = static_cast<std::size_t>(hash) & mask;; at = (at + 1u) & mask) {
const auto& slot = slots[at];
if (slot.stamp != lease.Stamp()) return std::nullopt;
if (slot.hash == hash && equal(slot.value)) return slot.value;
}
}
void Clear() {
lease.Clear();
entries = 0;
}
void Insert(std::uint64_t hash, std::uint32_t value) {
if ((entries + 1u) * 2u > lease.Slots().size()) grow();
place(lease.Slots(), hash, value);
entries++;
}
private:
static constexpr std::size_t MinimumSlots = 64;
void place(std::vector<HashSlot>& slots, std::uint64_t hash, std::uint32_t value) const {
const auto mask = slots.size() - 1u;
auto at = static_cast<std::size_t>(hash) & mask;
while (slots[at].stamp == lease.Stamp()) at = (at + 1u) & mask;
slots[at] = {hash, lease.Stamp(), value};
}
void grow() {
std::vector<HashSlot> grown(std::max(MinimumSlots, lease.Slots().size() * 2u));
for (const auto& slot : lease.Slots()) {
if (slot.stamp == lease.Stamp()) place(grown, slot.hash, slot.value);
}
lease.Slots().swap(grown);
}
SlotLease<HashSlot> lease;
std::size_t entries = 0;
};
struct WordsIndexTag {};
struct ElementIndexTag {};
struct SamplerIndexTag {};
struct PoisonIndexTag {};
struct TableRecordsTag {};
class TableSnapshotter {
public:
TableSnapshotter(const IrResourcePlan& plan, const SrtRuntime& runtime, SrtWalker& walker, const std::vector<std::uint8_t>& activeSources, ImageTableSnapshot& tables) : plan(plan), runtime(runtime), walker(walker), activeSources(activeSources), tables(tables) {}
void Run() {
tables = ImageTableSnapshot{};
std::uint32_t count = 0;
bool hasIndirect = false;
for (const auto& image : plan.info.images) {
if (image.table != NoTable) {
count = std::max(count, image.table + 1u);
if (image.source < plan.descriptorSources.size() && plan.descriptorSources[image.source].tableColumn.has_value() && plan.descriptorSources[image.source].tableColumn->indirect) hasIndirect = true;
}
}
for (const auto& sampler : plan.info.samplers) {
if (sampler.table != NoTable) {
count = std::max(count, sampler.table + 1u);
if (sampler.source < plan.descriptorSources.size() && plan.descriptorSources[sampler.source].tableColumn.has_value() && plan.descriptorSources[sampler.source].tableColumn->indirect) hasIndirect = true;
}
}
if (count == 0u) {
return;
}
if (runtime.readMemory == nullptr) {
throw std::runtime_error("image table snapshot requires runtime memory access");
}
const auto started = std::chrono::steady_clock::now();
const bool checkEpoch = (count > 1u || hasIndirect) && runtime.descriptorScope != nullptr;
bool completed = false;
for (std::uint32_t attempt = 0; attempt < 3u; ++attempt) {
if (attempt != 0u) {
columns.clear();
pages.clear();
wholePages.clear();
tables = {};
}
tables.shader = plan.shaderHash;
tables.tables.resize(count);
const SrtForceSyncScope forceSync(runtime, checkEpoch && attempt == 2u);
const auto invalidationsBefore = checkEpoch ? runtime.descriptorScope(runtime.userContext, 0u) : 0u;
for (const auto& image : plan.info.images) {
if (image.table != NoTable) Snapshot(image.source, image.table);
}
for (const auto& sampler : plan.info.samplers) {
if (sampler.table != NoTable) Snapshot(sampler.source, sampler.table);
}
if (!checkEpoch || runtime.descriptorScope(runtime.userContext, 0u) == invalidationsBefore) {
completed = true;
break;
}
}
if (!completed) throw std::runtime_error("image table: multi-table snapshot did not stabilize");
auto& counters = tableCounters();
counters.snapshots.fetch_add(1, std::memory_order_relaxed);
counters.tables.fetch_add(count, std::memory_order_relaxed);
counters.nanoseconds.fetch_add(static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - started).count()), std::memory_order_relaxed);
if (TableStrict()) {
for (std::uint32_t table = 0; table < tables.tables.size(); table++) {
const auto& column = tables.tables[table];
const auto poisoned = std::find_if(column.codes.begin(), column.codes.end(), [](std::uint32_t code) { return (code & ImageTableAbi::PoisonFlag) != 0u && (code & ~ImageTableAbi::PoisonFlag) != static_cast<std::uint32_t>(PoisonReason::OutsideDomain); });
if (column.fault != 0u || poisoned != column.codes.end()) {
const auto reason = static_cast<PoisonReason>((column.fault != 0u ? column.fault : *poisoned) & ~ImageTableAbi::PoisonFlag);
throw std::runtime_error("image table " + std::to_string(table) + " at 0x" + hexText(column.base) + " holds a record that cannot be read (" + std::string(ImageTableAbi::PoisonReasonName(reason)) + "), and APS5_IMAGE_TABLE_STRICT is set");
}
}
}
}
private:
static constexpr std::uint64_t PageBytes = 4096u;
mutable std::uint32_t indirectDwords = 0;
mutable std::uint32_t indirectDword = 0;
mutable std::uint32_t accessibleChecks = 0;
bool Accessible(std::uint64_t address, std::uint64_t bytes) const {
return runtime.accessible == nullptr || runtime.accessible(runtime.userContext, address, bytes);
}
bool PageAccessible(std::uint64_t address, std::uint64_t begin, std::uint64_t end) {
indirectDword = 0u;
accessibleChecks = 0u;
const auto page = address & ~(PageBytes - 1u);
if (const auto found = pages.find(page); found != pages.end()) return found->second;
const auto first = std::max(page, begin);
const auto last = std::min(page + PageBytes, end);
const bool accessible = first < last && Accessible(first, last - first);
pages.emplace(page, accessible);
return accessible;
}
bool AddressAccessible(std::uint64_t address) {
const auto page = address & ~(PageBytes - 1u);
const auto [found, inserted] = wholePages.try_emplace(page, false);
if (inserted) found->second = Accessible(page, PageBytes);
const bool accessible = found->second || Accessible(address, sizeof(std::uint32_t));
if (accessible) {
++accessibleChecks;
} else {
indirectDword = 0u;
accessibleChecks = 0u;
}
return accessible;
}
std::uint32_t Read(std::uint64_t address) const {
const bool scoped = runtime.descriptorScope != nullptr && indirectDwords > 1u && accessibleChecks == 1u;
if (scoped) {
static_cast<void>(runtime.descriptorScope(runtime.userContext, static_cast<std::size_t>(indirectDwords - indirectDword) * sizeof(std::uint32_t)));
indirectDword = (indirectDword + 1u) % indirectDwords;
} else {
indirectDword = 0u;
}
accessibleChecks = 0u;
std::uint32_t word = 0;
const bool ok = runtime.readMemory(runtime.userContext, address, &word);
if (scoped) static_cast<void>(runtime.descriptorScope(runtime.userContext, 0u));
if (!ok) {
throw std::runtime_error("image table: failed to read guest memory at 0x" + hexText(address));
}
return word;
}
ShaderBufferResource EvaluateBuffer(std::uint32_t source) const {
DescriptorValue value;
walker.EvaluateDescriptorSource(plan, source, runtime, value);
return decodeBufferDescriptor(value);
}
void Narrow(const TableColumn& column, ColumnRecords& records) {
const auto skip = [&](NarrowSkip reason) {
auto& counters = tableCounters();
counters.narrowSkipped.fetch_add(1, std::memory_order_relaxed);
counters.narrowSkips[static_cast<std::size_t>(reason)].fetch_add(1, std::memory_order_relaxed);
};
std::vector<std::uint32_t> values{0u};
std::vector<std::pair<std::uint64_t, std::uint64_t>> scanned;
for (const auto& domain : column.keyDomains) {
if (domain.value) {
DescriptorValue key;
try {
walker.EvaluateDescriptorSource(plan, domain.source, runtime, key);
} catch (const std::exception&) {
skip(NarrowSkip::Value);
return;
}
values.push_back(key.dwords[0]);
continue;
}
const auto keyBuffer = EvaluateBuffer(domain.source);
if (keyBuffer.Type() != 0u) {
skip(NarrowSkip::NotBuffer);
return;
}
const auto base = keyBuffer.Base48();
const auto size = keyBuffer.GetSize();
const std::uint64_t first = domain.offset & ~3u;
const std::uint64_t positions = size >= first + 4u ? (size - first - 4u) / domain.stride + 1u : 0u;
if (positions > TableKeyScanLimit() || first > 0xffffffffull) {
auto& widest = tableCounters().narrowPositions;
auto seen = widest.load(std::memory_order_relaxed);
while (seen < positions && !widest.compare_exchange_weak(seen, positions, std::memory_order_relaxed)) {}
skip(NarrowSkip::KeyScan);
return;
}
if (positions != 0u && runtime.pendingWrite != nullptr && runtime.pendingWrite(runtime.userContext, base + first, size - first)) {
skip(NarrowSkip::Pending);
return;
}
if (runtime.readWords != nullptr && positions != 0u && domain.stride % 4u == 0u && domain.stride <= 64u) {
const auto words = static_cast<std::size_t>(((positions - 1u) * domain.stride) / 4u + 1u);
for (std::uint64_t page = (base + first) & ~(PageBytes - 1u); page < base + first + words * 4u; page += PageBytes) {
if (!PageAccessible(std::max(page, base + first), base, base + size)) {
skip(NarrowSkip::Unmapped);
return;
}
}
if (keyWords.size() < words) keyWords.resize(words);
if (!runtime.readWords(runtime.userContext, base + first, keyWords.data(), words)) throw std::runtime_error("image table: failed to read guest memory at 0x" + hexText(base + first));
const auto step = static_cast<std::size_t>(domain.stride / 4u);
values.reserve(values.size() + positions);
for (std::size_t index = 0; index < words; index += step) values.push_back(keyWords[index]);
} else {
for (std::uint64_t index = 0; index < positions; index++) {
const auto address = base + first + index * domain.stride;
if (!PageAccessible(address, base, base + size)) {
skip(NarrowSkip::Unmapped);
return;
}
values.push_back(Read(address));
}
}
if (positions != 0u) scanned.emplace_back(base, size);
}
records.states.assign(records.keys, RecordState::OutsideDomain);
records.outside = false;
const std::uint32_t unwrapped = std::numeric_limits<std::uint32_t>::max() / column.stride;
for (const auto value : values) {
const std::uint32_t relative = value * column.stride;
const auto record = value <= unwrapped ? value : relative % column.stride == 0u ? relative / column.stride : records.keys;
if (record < records.keys) {
records.states[record] = RecordState::Read;
continue;
}
if (!records.outside && (column.address || ImageTableAbi::ScalarBufferDword(relative + column.addend, column.offset, records.size).has_value())) records.outside = true;
}
records.narrowed = true;
for (const auto& [base, size] : scanned) tables.ranges.emplace_back(base, size);
tableCounters().narrowed.fetch_add(1, std::memory_order_relaxed);
}
void Select(const TableColumn& column, ColumnRecords& records) {
const auto base = records.base;
const auto size = records.size;
DescriptorValue selection;
try {
walker.EvaluateDescriptorSource(plan, column.selection, runtime, selection);
} catch (const std::exception&) {
records.fault = ImageTableAbi::PoisonCode(static_cast<std::uint32_t>(PoisonReason::Unmapped));
return;
}
tableCounters().selected.fetch_add(1, std::memory_order_relaxed);
const auto offset = selection.dwords[0];
const auto entry = (column.addend + column.offset) & ~3u;
records.base = base + ((offset + column.offset) & ~3u) - entry;
records.size = entry + static_cast<std::uint64_t>(column.dwordCount) * sizeof(std::uint32_t);
records.records = 1u;
records.keys = 1u;
records.states.assign(1u, RecordState::Read);
records.words.assign(1u, 0u);
if (offset >= column.foldedAddend && offset > 0xffffffffu - column.foldedCarry) {
records.states.front() = RecordState::Carried;
return;
}
DescriptorValue value;
std::uint64_t low = std::numeric_limits<std::uint64_t>::max();
std::uint64_t high = 0;
bool completed = false;
for (std::uint32_t attempt = 0; attempt < 3u; ++attempt) {
value = {};
value.dwordCount = 8u;
low = std::numeric_limits<std::uint64_t>::max();
high = 0;
const SrtForceSyncScope forceSync(runtime, attempt == 2u);
const auto invalidationsBefore = runtime.descriptorScope != nullptr ? runtime.descriptorScope(runtime.userContext, 0u) : 0u;
for (std::uint32_t dword = 0; dword < column.dwordCount; dword++) {
const auto position = ImageTableAbi::ScalarBufferDword(offset, column.offset + dword * 4u, size);
if (!position.has_value()) {
value.availableDwordMask |= static_cast<std::uint8_t>(1u << dword);
continue;
}
const auto address = base + *position;
if (!PageAccessible(address, base, base + size)) {
records.states.front() = RecordState::Unmapped;
return;
}
if (runtime.descriptorScope != nullptr) static_cast<void>(runtime.descriptorScope(runtime.userContext, static_cast<std::size_t>(column.dwordCount - dword) * sizeof(std::uint32_t)));
value.dwords[dword] = Read(address);
if (runtime.descriptorScope != nullptr) static_cast<void>(runtime.descriptorScope(runtime.userContext, 0u));
value.availableDwordMask |= static_cast<std::uint8_t>(1u << dword);
low = std::min(low, address);
high = std::max(high, address + sizeof(std::uint32_t));
if (runtime.descriptorScope != nullptr && runtime.descriptorScope(runtime.userContext, 0u) != invalidationsBefore) break;
}
if (runtime.descriptorScope == nullptr || runtime.descriptorScope(runtime.userContext, 0u) == invalidationsBefore) {
completed = true;
break;
}
}
if (!completed) throw std::runtime_error("image table: selected descriptor snapshot did not stabilize");
records.words.front() = WordsIndex(records, value);
if (low < high) tables.ranges.emplace_back(low, high - low);
}
std::uint32_t WordsIndex(ColumnRecords& records, const DescriptorValue& value) {
const auto hash = hashWords(value.dwords, (static_cast<std::uint64_t>(value.dwordCount) << 8u) | value.availableDwordMask);
if (const auto found = wordsIndex.Find(hash, [&](std::uint32_t index) { return records.distinct[index] == value; })) return *found;
const auto index = static_cast<std::uint32_t>(records.distinct.size());
records.distinct.push_back(value);
wordsIndex.Insert(hash, index);
return index;
}
void Seal(ColumnRecords& records) {
auto& contents = records.contents;
std::vector<std::uint32_t> codes(records.keys, 0u);
for (std::uint32_t key = 0; key < records.keys; key++) {
switch (records.states[key]) {
case RecordState::Read:
codes[key] = records.words[key];
continue;
case RecordState::OutsideDomain:
codes[key] = ImageTableAbi::PoisonCode(static_cast<std::uint32_t>(PoisonReason::OutsideDomain));
break;
case RecordState::Unmapped:
codes[key] = ImageTableAbi::PoisonCode(static_cast<std::uint32_t>(PoisonReason::Unmapped));
contents.unmapped++;
break;
case RecordState::Carried:
codes[key] = ImageTableAbi::PoisonCode(static_cast<std::uint32_t>(PoisonReason::OffsetCarry));
contents.carried++;
break;
}
contents.poisoned++;
}
contents.codes = SharedValues<std::uint32_t>(std::move(codes));