Repository navigation
Expand file tree
/
Copy pathResourceTracker.cpp
More file actions
1865 lines (1773 loc) · 83.2 KB
/
Copy pathResourceTracker.cpp
File metadata and controls
1865 lines (1773 loc) · 83.2 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/ResourceTracker.hpp"
#include "Optimization/SrtWalker.hpp"
#include "Optimization/ResourceMaterializer.hpp"
#include "SpirvBackend/SpirvBufferFormat.hpp"
#include "IntermediateRepresentation/IrBuilder.hpp"
#include "Optimization/SrtWalker/SrtInstructionPredicates.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <map>
#include <span>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
namespace ShaderRecompiler {
namespace {
constexpr std::uint32_t samplerBorderClampMask = (1u << 2u) | (1u << 5u) | (1u << 8u);
constexpr std::uint32_t samplerDword3ReservedMask = 0x3ffff000u;
[[noreturn]] void fail(const std::string& message) {
throw std::runtime_error(message);
}
// Debug aid: APS5_TRACE_BDA=1 names the accesses that make a program address-based (see Collect).
bool bdaTraceEnabled() {
static const bool enabled = std::getenv("APS5_TRACE_BDA") != nullptr;
return enabled;
}
constexpr unsigned bdaTraceLimit = 8;
std::string formatHex32(std::uint32_t value) {
static constexpr char digits[] = "0123456789abcdef";
std::string hex(8u, '0');
for (std::uint32_t index = 0; index < 8u; index++) {
hex[7u - index] = digits[(value >> (index * 4u)) & 0xfu];
}
return hex;
}
std::string describeValueChain(const IrValue* value, std::uint32_t depth) {
value = value->Resolve();
if (value->HasImmediate()) {
return "Immediate";
}
std::string text = std::string(IrOpcodeName(value->Opcode()));
if (value->Opcode() == IrOpcode::LoadAddressU32 || value->Opcode() == IrOpcode::ReadConstBuffer) {
text += "@pc=0x" + formatHex32(value->Flags<MemoryFlags>().pc);
}
if (depth == 0u || value->ArgumentCount() == 0u) {
return text;
}
text += "(";
for (std::uint32_t index = 0; index < value->ArgumentCount(); index++) {
if (index != 0u) {
text += ", ";
}
text += describeValueChain(value->Argument(index), depth - 1u);
}
text += ")";
return text;
}
std::uint32_t possibleU32Bits(const IrValue* value) {
value = value->Resolve();
if (value->HasImmediate()) {
return value->Type() == IrType::U32 ? value->ImmediateU32() : std::numeric_limits<std::uint32_t>::max();
}
switch (value->Opcode()) {
case IrOpcode::BitwiseAnd32:
return possibleU32Bits(value->Argument(0)) & possibleU32Bits(value->Argument(1));
case IrOpcode::BitwiseOr32:
return possibleU32Bits(value->Argument(0)) | possibleU32Bits(value->Argument(1));
case IrOpcode::ShiftLeftLogical32: {
const IrValue* shift = value->Argument(1)->Resolve();
return shift->HasImmediate() && shift->Type() == IrType::U32 ? possibleU32Bits(value->Argument(0)) << (shift->ImmediateU32() & 31u) : std::numeric_limits<std::uint32_t>::max();
}
default:
return std::numeric_limits<std::uint32_t>::max();
}
}
std::uint32_t byteExtent(const MemoryInfo& memory) {
const auto bytes = std::max((memory.dataBits + 7u) / 8u, 1u);
const auto count = std::max(memory.dataDwords, 1u);
const auto end = static_cast<std::uint64_t>(memory.offset) + static_cast<std::uint64_t>(bytes) * count;
return end > std::numeric_limits<std::uint32_t>::max() ? std::numeric_limits<std::uint32_t>::max() : static_cast<std::uint32_t>(end);
}
class Tracker {
public:
explicit Tracker(IrProgram& program) : m_program(program), m_info(program.Resources().info), m_builder(program) {
m_info.buffers.clear();
m_info.images.clear();
m_info.samplers.clear();
m_info.sampledPairs.clear();
m_info.usesDma = false;
m_info.bdaWrites = false;
}
void Run() {
if (m_program.Resources().resourceTrackingComplete) {
fail("resources already tracked");
}
if (!m_program.Resources().srtPlanComplete) {
fail("SRT plan is not ready");
}
SplitDescriptorPhis();
PlanTableColumns();
std::unordered_map<const IrBlock*, std::uint32_t> blockIndices;
for (const IrBlock* block : m_program.BlockOrder()) {
blockIndices.emplace(block, static_cast<std::uint32_t>(blockIndices.size()));
}
m_blockSources.assign(blockIndices.size(), {});
m_blockImages.assign(blockIndices.size(), {});
for (auto& block : m_program.Blocks()) {
const auto found = blockIndices.find(block.get());
m_currentBlock = found == blockIndices.end() ? std::numeric_limits<std::uint32_t>::max() : found->second;
for (IrValue* inst : block->Instructions()) {
Collect(*inst);
}
}
m_currentBlock = std::numeric_limits<std::uint32_t>::max();
PlanResourceControlFlow();
if (m_bdaTraces > bdaTraceLimit) std::fprintf(stderr, "[bda] %u more address accesses in this program not shown\n", m_bdaTraces - bdaTraceLimit);
CheckTableStores();
AssignTables();
LinkImageAliases();
for (const auto& patch : m_handlePatches) {
patch.handle->SetFlags<std::uint32_t>(patch.resource);
}
for (const auto& patch : m_memoryPatches) {
auto& memory = m_program.Resources().memoryInfo[patch.index];
memory.resource = patch.resource;
if (patch.hasSampler) {
memory.sampler = patch.sampler;
}
}
std::vector<const IrValue*> referenced;
for (const auto& plan : m_tableColumns) {
const auto& column = *m_sources[plan.source].tableColumn;
IrValue* offset = column.selected ? &m_builder.Constant(column.addend) : plan.offset;
for (std::uint32_t argument = 0; argument < plan.handle->ArgumentCount(); argument++) {
plan.handle->ReplaceArgument(argument, offset);
}
KeepSourceAlive(*plan.handle, m_sources[column.heapSource], referenced);
if (column.selected) {
KeepSourceAlive(*plan.handle, m_sources[column.selection], referenced);
}
if (plan.keyDomain.has_value()) {
KeepSourceAlive(*plan.handle, m_sources[plan.keyDomain->source], referenced);
}
}
for (const auto index : m_tablePlanningMemory) {
m_program.Resources().memoryInfo[index].planningOnly = true;
}
std::erase_if(m_program.Metadata().dynamicReads, [&](IrValue* value) {
const IrValue* inst = value->Resolve();
return std::ranges::find(m_tablePlanningReads, inst) != m_tablePlanningReads.end();
});
m_program.Resources().descriptorSources = std::move(m_sources);
m_program.Resources().info = std::move(m_info);
m_program.Resources().resourceTrackingComplete = true;
}
private:
struct HandlePatch {
IrValue* handle = nullptr;
std::uint32_t resource = 0;
};
struct MemoryPatch {
std::uint32_t index = 0;
std::uint32_t resource = 0;
std::uint32_t sampler = 0;
bool hasSampler = false;
};
struct TableColumnPlan {
IrValue* handle = nullptr;
std::uint32_t source = 0;
IrValue* offset = nullptr;
std::vector<std::uint32_t> memory;
std::vector<const IrValue*> reads;
std::optional<KeyDomain> keyDomain;
};
void MakeSource(const IrValue& handle, std::uint32_t width, bool sampler, bool sampleAdjust, DescriptorSource& descriptor) {
if (handle.ArgumentCount() != width) {
fail(std::string(IrOpcodeName(handle.Opcode())) + " has " + std::to_string(handle.ArgumentCount()) + " descriptor dwords, expected " + std::to_string(width));
}
descriptor.dwordCount = width;
for (std::uint32_t i = 0; i < width; i++) {
descriptor.dwords[i] = handle.Argument(i)->Resolve();
}
if (sampleAdjust) {
descriptor.dwords[3] = canonicalizeSampleAdjustDword3(descriptor.dwords[3]);
}
const IrValue* dword0 = descriptor.dwords[0]->Resolve();
if (sampler && dword0->HasImmediate() && dword0->Type() == IrType::U32 && (dword0->ImmediateU32() & samplerBorderClampMask) == 0u) {
descriptor.dwords[3] = &m_builder.Constant(0u);
}
}
IrValue* canonicalizeSampleAdjustDword3(IrValue* value) {
for (;;) {
value = value->Resolve();
if ((possibleU32Bits(value) & ~samplerDword3ReservedMask) == 0u) {
return &m_builder.Constant(0u);
}
if (value->Opcode() != IrOpcode::BitwiseOr32) {
return value;
}
IrValue* left = value->Argument(0)->Resolve();
IrValue* right = value->Argument(1)->Resolve();
const bool leftReserved = (possibleU32Bits(left) & ~samplerDword3ReservedMask) == 0u;
const bool rightReserved = (possibleU32Bits(right) & ~samplerDword3ReservedMask) == 0u;
if (leftReserved) {
value = right;
} else if (rightReserved) {
value = left;
} else {
return value;
}
}
}
bool ValidateSource(const DescriptorSource& descriptor, std::uint32_t& badDword) const {
constexpr SrtWalker walker;
for (std::uint32_t i = 0; i < descriptor.dwordCount; i++) {
badDword = i;
if (descriptor.dwords[i]->Resolve()->Type() != IrType::U32) {
return false;
}
if (!walker.ValidateRuntimeValue(m_program.Resources(), descriptor.dwords[i])) {
return false;
}
}
return true;
}
std::uint32_t InternSource(const DescriptorSource& descriptor) {
for (std::uint32_t candidate = 0; candidate < m_sources.size(); candidate++) {
const auto& current = m_sources[candidate];
if (current.dwordCount != descriptor.dwordCount || current.tableColumn != descriptor.tableColumn) {
continue;
}
bool same = true;
for (std::uint32_t i = 0; i < descriptor.dwordCount; i++) {
same = same && EquivalentValue(m_program.Resources(), current.dwords[i], descriptor.dwords[i]);
}
if (same) {
NoteBlockSource(candidate);
return candidate;
}
}
m_sources.push_back(descriptor);
NoteBlockSource(static_cast<std::uint32_t>(m_sources.size() - 1));
return static_cast<std::uint32_t>(m_sources.size() - 1);
}
void NoteBlockImage(std::uint32_t image) {
if (m_currentBlock >= m_blockImages.size()) {
return;
}
auto& images = m_blockImages[m_currentBlock];
if (std::ranges::find(images, image) == images.end()) {
images.push_back(image);
}
}
void NoteBlockSource(std::uint32_t source) {
if (m_currentBlock >= m_blockSources.size()) {
return;
}
auto& sources = m_blockSources[m_currentBlock];
if (std::ranges::find(sources, source) == sources.end()) {
sources.push_back(source);
}
}
void PlanResourceControlFlow() {
const auto& order = m_program.BlockOrder();
const auto& info = m_program.Metadata().blockInfo;
if (order.empty() || order.size() != info.size()) {
return;
}
std::unordered_map<const IrBlock*, std::uint32_t> indexOf;
std::unordered_map<std::uint32_t, std::uint32_t> idToIndex;
for (std::uint32_t index = 0; index < order.size(); index++) {
indexOf.emplace(order[index], index);
idToIndex.emplace(info[index].id, index);
}
std::vector<ResourceBlock> controlFlow(order.size());
for (std::uint32_t index = 0; index < order.size(); index++) {
auto& block = controlFlow[index];
const auto& terminator = info[index].terminator;
const auto target = [&](std::uint32_t id) { return idToIndex.find(id); };
const auto trueEdge = target(terminator.trueBlock);
const auto falseEdge = target(terminator.falseBlock);
if (terminator.kind == TerminatorKind::ConditionalBranch && !terminator.loopHeader && info[index].condition != nullptr && trueEdge != idToIndex.end() && falseEdge != idToIndex.end()) {
block.condition = info[index].condition;
block.successors = {trueEdge->second, falseEdge->second};
} else if (terminator.kind != TerminatorKind::Return) {
for (const IrBlock* successor : order[index]->Successors()) {
const auto found = indexOf.find(successor);
if (found == indexOf.end()) {
return;
}
block.successors.push_back(found->second);
}
}
block.sources = m_blockSources[index];
block.images = m_blockImages[index];
}
std::vector<std::uint8_t> unconditional(order.size());
for (std::uint32_t index = 0; index < order.size() && unconditional[index] == 0u;) {
unconditional[index] = 1u;
if (controlFlow[index].successors.size() != 1u) {
break;
}
index = controlFlow[index].successors.front();
}
std::vector<std::uint8_t> reached(m_sources.size());
std::vector<std::uint8_t> reachedImages(m_info.images.size());
for (std::uint32_t index = 0; index < order.size(); index++) {
if (unconditional[index] == 0u) {
continue;
}
for (const auto source : controlFlow[index].sources) {
reached[source] = 1u;
}
for (const auto image : controlFlow[index].images) {
reachedImages[image] = 1u;
}
}
bool guarded = false;
for (const auto& block : controlFlow) {
for (const auto source : block.sources) {
guarded = guarded || reached[source] == 0u;
}
for (const auto image : block.images) {
guarded = guarded || reachedImages[image] == 0u;
}
}
if (guarded) {
m_program.Resources().controlFlow = std::move(controlFlow);
}
}
static bool immediateU32(IrValue* value, std::uint32_t& result) {
value = value->Resolve();
if (!value->HasImmediate() || value->Type() != IrType::U32) {
return false;
}
result = value->ImmediateU32();
return true;
}
const MemoryInfo* ScalarReadMemory(const IrValue& read, std::uint32_t& index) const {
if (read.Opcode() != IrOpcode::ReadConstBuffer || read.ArgumentCount() != 2u) {
return nullptr;
}
index = read.Flags<MemoryFlags>().index;
if (index >= m_program.Resources().memoryInfo.size()) {
return nullptr;
}
const auto& memory = m_program.Resources().memoryInfo[index];
return memory.kind == ResourceKind::ScalarBuffer && memory.dataBits == 32u && memory.dataDwords == 1u ? &memory : nullptr;
}
const MemoryInfo* ScalarAddressMemory(const IrValue& read, std::uint32_t& index) const {
if (read.Opcode() != IrOpcode::LoadAddressU32 || read.ArgumentCount() != 4u) {
return nullptr;
}
index = read.Flags<MemoryFlags>().index;
if (index >= m_program.Resources().memoryInfo.size()) {
return nullptr;
}
const auto& memory = m_program.Resources().memoryInfo[index];
std::uint32_t high = 0;
const IrValue* active = read.Argument(3)->Resolve();
const bool always = active->HasImmediate() && active->Type() == IrType::U1 && active->ImmediateBool();
return memory.kind == ResourceKind::ScalarAddress && !memory.addressIsFull && memory.dataBits == 32u && memory.dataDwords == 1u && immediateU32(read.Argument(2), high) && high == 0u && always ? &memory : nullptr;
}
static bool AccessesMemory(IrOpcode op) {
return BufferAccessOf(op) != BufferAccess::None || AddressOpcodeInfoOf(op).access != AddressAccess::None || ImageOpcodeInfoOf(op).access != ImageAccess::None;
}
void IndexMemoryUsers() {
for (const auto& block : m_program.Blocks()) {
for (const IrValue* inst : block->Instructions()) {
if (AccessesMemory(inst->Opcode())) {
m_memoryUsers[inst->Flags<MemoryFlags>().index].push_back(inst);
}
}
}
m_memoryUsersIndexed = true;
}
bool MemoryIndexBelongsTo(std::uint32_t index, const IrValue& owner) const {
if (m_memoryUsersIndexed) {
const auto users = m_memoryUsers.find(index);
return users == m_memoryUsers.end() || std::ranges::all_of(users->second, [&](const IrValue* user) { return user == &owner; });
}
for (const auto& block : m_program.Blocks()) {
for (const IrValue* inst : block->Instructions()) {
if (!AccessesMemory(inst->Opcode()) || inst == &owner) {
continue;
}
if (inst->Flags<MemoryFlags>().index == index) {
return false;
}
}
}
return true;
}
bool MakeRuntimeSource(const IrValue& handle, IrOpcode expected, std::uint32_t width, std::uint32_t& source, DescriptorSource& descriptor) {
if (handle.Opcode() != expected) {
return false;
}
MakeSource(handle, width, false, false, descriptor);
std::uint32_t badDword = 0;
if (!ValidateSource(descriptor, badDword)) {
return false;
}
source = InternSource(descriptor);
return true;
}
static bool MatchScale(IrValue* value, IrValue*& key, std::uint32_t& stride) {
value = value->Resolve();
if (value->ArgumentCount() != 2u) {
return false;
}
std::uint32_t immediate = 0;
if (value->Opcode() == IrOpcode::ShiftLeftLogical32) {
if (!immediateU32(value->Argument(1), immediate) || immediate >= 32u) {
return false;
}
key = value->Argument(0)->Resolve();
stride = 1u << immediate;
return true;
}
if (value->Opcode() != IrOpcode::IMul32) {
return false;
}
if (immediateU32(value->Argument(1), immediate)) {
key = value->Argument(0)->Resolve();
} else if (immediateU32(value->Argument(0), immediate)) {
key = value->Argument(1)->Resolve();
} else {
return false;
}
stride = immediate;
return true;
}
static bool MatchAffineOffset(IrValue* value, IrValue*& key, std::uint32_t& stride, std::uint32_t& addend) {
value = value->Resolve();
addend = 0;
bool matched = MatchScale(value, key, stride);
if (!matched && value->Opcode() == IrOpcode::IAdd32 && value->ArgumentCount() == 2u) {
if (immediateU32(value->Argument(0), addend)) {
matched = MatchScale(value->Argument(1), key, stride);
} else if (immediateU32(value->Argument(1), addend)) {
matched = MatchScale(value->Argument(0), key, stride);
}
}
return matched && stride >= 4u && stride % 4u == 0u && key->Type() == IrType::U32;
}
static bool MatchMaskedOffset(IrValue* value, IrValue*& key, std::uint32_t& stride) {
value = value->Resolve();
if (value->Opcode() != IrOpcode::BitwiseAnd32 || value->ArgumentCount() != 2u) {
return false;
}
std::uint32_t mask = 0;
IrValue* scaled = nullptr;
if (immediateU32(value->Argument(1), mask)) {
scaled = value->Argument(0);
} else if (immediateU32(value->Argument(0), mask)) {
scaled = value->Argument(1);
} else {
return false;
}
return MatchScale(scaled, key, stride) && std::has_single_bit(stride) && stride >= 4u && (mask & ~(stride - 1u)) != 0u && key->Type() == IrType::U32;
}
static bool ReadsThroughDescriptor(const IrValue* value) {
std::vector<const IrValue*> pending{value};
std::vector<const IrValue*> seen;
while (!pending.empty()) {
const IrValue* current = pending.back()->Resolve();
pending.pop_back();
if (std::find(seen.begin(), seen.end(), current) != seen.end()) continue;
seen.push_back(current);
if (current->Opcode() == IrOpcode::ReadConstBuffer || current->Opcode() == IrOpcode::LoadAddressU32) return true;
for (std::size_t index = 0; index < current->ArgumentCount(); index++) pending.push_back(current->Argument(index));
}
return false;
}
std::optional<KeyDomain> MatchKeyDomain(IrValue* key) {
key = key->Resolve();
DescriptorSource direct;
direct.dwordCount = 1u;
direct.dwords[0] = key;
std::uint32_t badDword = 0;
if (ValidateSource(direct, badDword) && !ReadsThroughDescriptor(key)) {
KeyDomain domain{InternSource(direct), 0u, 4u};
domain.value = true;
return domain;
}
std::uint32_t memoryIndex = 0;
const MemoryInfo* memory = ScalarReadMemory(*key, memoryIndex);
if (memory == nullptr) {
return std::nullopt;
}
DescriptorSource source;
std::uint32_t sourceIndex = 0;
if (!MakeRuntimeSource(*key->Argument(0)->Resolve(), IrOpcode::GetBufferResource, 4u, sourceIndex, source)) {
return std::nullopt;
}
IrValue* selector = nullptr;
std::uint32_t stride = 0;
std::uint32_t addend = 0;
if (MatchAffineOffset(key->Argument(1), selector, stride, addend)) {
return KeyDomain{sourceIndex, memory->offset + addend, stride};
}
const auto bits = possibleU32Bits(key->Argument(1));
const auto zeros = bits == 0u ? 31u : std::min<std::uint32_t>(static_cast<std::uint32_t>(std::countr_zero(bits)), 31u);
return KeyDomain{sourceIndex, memory->offset, std::max(4u, 1u << zeros)};
}
static IrValue* SplitImmediateAddend(IrValue* value, std::uint32_t& addend) {
value = value->Resolve();
addend = 0;
while (value->Opcode() == IrOpcode::IAdd32 && value->ArgumentCount() == 2u) {
std::uint32_t immediate = 0;
IrValue* rest = nullptr;
if (immediateU32(value->Argument(0), immediate)) rest = value->Argument(1)->Resolve();
else if (immediateU32(value->Argument(1), immediate)) rest = value->Argument(0)->Resolve();
else break;
addend += immediate;
value = rest;
}
return value;
}
bool TryMakeTableColumn(IrValue& handle, bool sampler, bool r128, TableColumnPlan& plan) {
const auto expected = sampler ? IrOpcode::GetSamplerResource : IrOpcode::GetImageResource;
const std::uint32_t width = sampler ? 4u : 8u;
if (handle.Opcode() != expected || handle.ArgumentCount() != width) {
return false;
}
std::uint32_t words = width;
if (!sampler && r128) {
bool zeroTail = true;
for (std::uint32_t dword = 4u; dword < 8u; dword++) {
std::uint32_t immediate = 0;
zeroTail = zeroTail && immediateU32(handle.Argument(dword), immediate) && immediate == 0u;
}
if (zeroTail) {
words = 4u;
}
}
IrValue* heapHandle = nullptr;
IrValue* offset = nullptr;
IrValue* base = nullptr;
std::uint32_t baseAddend = 0;
std::uint32_t carry = 0;
bool folded = false;
std::uint32_t first = 0;
bool address = false;
for (std::uint32_t dword = 0; dword < words; dword++) {
IrValue* read = handle.Argument(dword)->Resolve();
std::uint32_t memoryIndex = 0;
const MemoryInfo* memory = ScalarReadMemory(*read, memoryIndex);
const bool addressRead = memory == nullptr && (memory = ScalarAddressMemory(*read, memoryIndex)) != nullptr;
if (memory == nullptr || !MemoryIndexBelongsTo(memoryIndex, *read)) {
return false;
}
std::uint32_t readAddend = 0;
IrValue* readBase = SplitImmediateAddend(read->Argument(1), readAddend);
if (dword == 0u) {
first = memory->offset;
address = addressRead;
base = readBase;
baseAddend = readAddend;
} else if (addressRead != address || memory->offset + readAddend != first + baseAddend + dword * static_cast<std::uint32_t>(sizeof(std::uint32_t))) {
return false;
} else if (readAddend != baseAddend) {
if (readAddend < baseAddend || static_cast<std::uint64_t>(memory->offset) + (readAddend - baseAddend) > 0x7fffffffu) {
return false;
}
folded = true;
carry = std::max(carry, readAddend - baseAddend);
}
IrValue* currentHandle = read->Argument(0)->Resolve();
if (heapHandle != nullptr && currentHandle != heapHandle && !EquivalentValue(m_program.Resources(), heapHandle, currentHandle)) {
return false;
}
if (heapHandle == nullptr) heapHandle = currentHandle;
if (dword == 0u) {
offset = read->Argument(1)->Resolve();
} else if (!EquivalentValue(m_program.Resources(), base, readBase)) {
return false;
}
plan.memory.push_back(memoryIndex);
plan.reads.push_back(read);
}
if (address) {
DescriptorSource direct;
MakeSource(handle, width, false, false, direct);
std::uint32_t badDword = 0;
if (ValidateSource(direct, badDword)) {
return false;
}
}
IrValue* key = nullptr;
std::uint32_t stride = 0;
std::uint32_t addend = 0;
bool masked = false;
std::uint32_t descriptorOffset = 0;
if (address && immediateU32(offset, descriptorOffset)) {
return TryMakeIndirectColumn(handle, *heapHandle, sampler, words, descriptorOffset, first, plan);
}
if (!MatchAffineOffset(offset, key, stride, addend)) {
if (!MatchMaskedOffset(offset, key, stride)) {
return false;
}
masked = true;
}
DescriptorSource heapSource;
std::uint32_t heapIndex = 0;
if (!MakeRuntimeSource(*heapHandle, address ? IrOpcode::GetAddressResource : IrOpcode::GetBufferResource, address ? 2u : 4u, heapIndex, heapSource)) {
return false;
}
TableColumn column;
column.heapSource = heapIndex;
column.stride = stride;
column.addend = addend;
column.offset = first;
column.dwordCount = words;
column.maxKey = possibleU32Bits(key);
column.sampler = sampler;
column.address = address;
column.foldedAddend = folded ? baseAddend : 0u;
column.foldedCarry = folded ? carry : 0u;
if (!address && !sampler) {
DescriptorSource direct;
MakeSource(handle, width, false, false, direct);
DescriptorSource selection;
selection.dwordCount = 1u;
selection.dwords[0] = offset;
std::uint32_t badDword = 0;
if (ValidateSource(direct, badDword) && ValidateSource(selection, badDword)) {
column.selected = true;
column.selection = InternSource(selection);
}
}
const auto domain = masked ? std::optional<KeyDomain>{} : MatchKeyDomain(key);
DescriptorSource columnSource = heapSource;
columnSource.tableColumn = column;
plan.handle = &handle;
plan.source = InternSource(columnSource);
plan.keyDomain = domain;
auto& shared = *m_sources[plan.source].tableColumn;
shared.maxKey = std::max(shared.maxKey, column.maxKey);
if (!domain.has_value()) {
shared.unkeyed = true;
shared.keyDomains.clear();
} else if (!shared.unkeyed && std::find(shared.keyDomains.begin(), shared.keyDomains.end(), *domain) == shared.keyDomains.end()) {
shared.keyDomains.push_back(*domain);
}
plan.offset = offset;
return true;
}
bool TryMakeIndirectColumn(IrValue& handle, IrValue& pointer, bool sampler, std::uint32_t words, std::uint32_t descriptorOffset, std::uint32_t descriptorImmediate, TableColumnPlan& plan) {
if (pointer.Opcode() != IrOpcode::GetAddressResource || pointer.ArgumentCount() != 2u) {
return false;
}
IrValue* bufferHandle = nullptr;
IrValue* offset = nullptr;
std::uint32_t first = 0;
for (std::uint32_t dword = 0; dword < 2u; dword++) {
IrValue* read = pointer.Argument(dword)->Resolve();
std::uint32_t memoryIndex = 0;
const MemoryInfo* memory = ScalarReadMemory(*read, memoryIndex);
if (memory == nullptr || !MemoryIndexBelongsTo(memoryIndex, *read)) {
return false;
}
if (dword == 0u) {
first = memory->offset;
bufferHandle = read->Argument(0)->Resolve();
offset = read->Argument(1)->Resolve();
} else if (memory->offset != first + static_cast<std::uint32_t>(sizeof(std::uint32_t)) || read->Argument(0)->Resolve() != bufferHandle || !EquivalentValue(m_program.Resources(), offset, read->Argument(1))) {
return false;
}
}
IrValue* key = nullptr;
std::uint32_t stride = 0;
std::uint32_t addend = 0;
if (!MatchAffineOffset(offset, key, stride, addend)) {
return false;
}
DescriptorSource heapSource;
std::uint32_t heapIndex = 0;
if (!MakeRuntimeSource(*bufferHandle, IrOpcode::GetBufferResource, 4u, heapIndex, heapSource)) {
return false;
}
TableColumn column;
column.heapSource = heapIndex;
column.stride = stride;
column.addend = addend;
column.offset = first;
column.dwordCount = words;
column.maxKey = possibleU32Bits(key);
column.sampler = sampler;
column.indirect = true;
column.indirectOffset = descriptorOffset;
column.indirectImmediate = descriptorImmediate;
const auto domain = MatchKeyDomain(key);
DescriptorSource columnSource = heapSource;
columnSource.tableColumn = column;
plan.handle = &handle;
plan.source = InternSource(columnSource);
plan.keyDomain = domain;
auto& shared = *m_sources[plan.source].tableColumn;
shared.maxKey = std::max(shared.maxKey, column.maxKey);
if (!domain.has_value()) {
shared.unkeyed = true;
shared.keyDomains.clear();
} else if (!shared.unkeyed && std::find(shared.keyDomains.begin(), shared.keyDomains.end(), *domain) == shared.keyDomains.end()) {
shared.keyDomains.push_back(*domain);
}
plan.offset = offset;
return true;
}
const TableColumnPlan* FindTableColumn(const IrValue& handle) const {
const auto found = std::ranges::find_if(m_tableColumns, [&](const TableColumnPlan& plan) {
return plan.handle == &handle;
});
return found == m_tableColumns.end() ? nullptr : &*found;
}
bool PlanTableColumn(IrValue& handle, bool sampler, bool r128) {
if (FindTableColumn(handle) != nullptr) {
return true;
}
TableColumnPlan plan;
if (!TryMakeTableColumn(handle, sampler, r128, plan)) {
return false;
}
m_tableColumns.push_back(std::move(plan));
return true;
}
static constexpr std::uint32_t phiSearchDepth = 8u;
static bool SplittableImageRead(const IrValue& inst) {
switch (inst.Opcode()) {
case IrOpcode::ImageSampleRaw:
case IrOpcode::ImageGatherRaw:
case IrOpcode::ImageQueryLod:
case IrOpcode::ImageQueryDimensions:
case IrOpcode::ImageRead: return inst.Type() == IrType::U32x4;
default: return false;
}
}
void CollectDescriptorPhis(IrValue* value, std::vector<IrValue*>& phis, std::uint32_t depth) const {
value = value->Resolve();
if (value->HasImmediate()) {
return;
}
if (value->IsPhi()) {
if (ResolveInvariantPhi(m_program.Resources(), value) == nullptr && std::ranges::find(phis, value) == phis.end()) {
phis.push_back(value);
}
return;
}
if (depth != 0u && value->Opcode() == IrOpcode::ReadFirstLane && value->ArgumentCount() == 2u) {
CollectDescriptorPhis(value->Argument(0), phis, depth - 1u);
return;
}
if (depth == 0u || !Detail::IsRuntimeUniformOp(value->Opcode())) {
return;
}
for (std::size_t index = 0; index < value->ArgumentCount(); index++) {
CollectDescriptorPhis(value->Argument(index), phis, depth - 1u);
}
}
static IrValue* PhiIncoming(const IrValue& phi, const IrBlock* predecessor) {
for (std::size_t index = 0; index < phi.ArgumentCount(); index++) {
if (phi.PhiBlock(index) == predecessor) {
return phi.Argument(index);
}
}
return nullptr;
}
IrValue* EmitBefore(IrValue& position, IrOpcode op, IrType type, std::span<IrValue* const> arguments, std::uint64_t flags = 0) {
IrValue& value = m_program.CreateValue(op, type, flags);
for (IrValue* argument : arguments) {
value.AddArgument(argument);
}
position.Parent()->InsertInstructionBefore(&position, &value);
return &value;
}
IrValue* EmitCopy(const IrValue& original, std::span<IrValue* const> arguments, IrValue& position) {
return EmitBefore(position, original.Opcode(), original.Type(), arguments, original.Flags<std::uint64_t>());
}
IrValue* Rematerialize(IrValue* value, IrValue& position, bool emit, std::uint32_t depth) {
value = value->Resolve();
if (value->HasImmediate()) {
return value;
}
if (value->IsPhi()) {
IrValue* invariant = ResolveInvariantPhi(m_program.Resources(), value);
return invariant == nullptr || invariant->IsPhi() ? nullptr : Rematerialize(invariant, position, emit, depth);
}
if (depth == 0u) {
return nullptr;
}
const auto op = value->Opcode();
const bool register_ = op == IrOpcode::GetUserData;
const bool argumentless = (op == IrOpcode::GetShaderBase || op == IrOpcode::GetSrtResource) && value->ArgumentCount() == 0u;
const bool srtRead = op == IrOpcode::ReadConst && value->ArgumentCount() == 2u && value->Argument(0)->Resolve()->Opcode() == IrOpcode::GetSrtResource && value->Argument(1)->Resolve()->HasImmediate();
if (!register_ && !argumentless && !srtRead && !Detail::IsRuntimeUniformOp(op)) {
return nullptr;
}
std::vector<IrValue*> arguments;
for (std::size_t index = 0; index < value->ArgumentCount(); index++) {
IrValue* argument = register_ ? value->Argument(index) : Rematerialize(value->Argument(index), position, emit, depth - 1u);
if (argument == nullptr) {
return nullptr;
}
arguments.push_back(argument);
}
return emit ? EmitCopy(*value, arguments, position) : value;
}
IrValue* SubstituteEdge(IrValue* value, const IrBlock* predecessor, IrValue& position, bool emit, std::uint32_t depth) {
value = value->Resolve();
std::vector<IrValue*> phis;
CollectDescriptorPhis(value, phis, depth);
if (phis.empty()) {
return value;
}
if (value->IsPhi()) {
IrValue* incoming = PhiIncoming(*value, predecessor);
return incoming == nullptr ? nullptr : Rematerialize(incoming, position, emit, phiSearchDepth);
}
std::vector<IrValue*> arguments;
for (std::size_t index = 0; index < value->ArgumentCount(); index++) {
IrValue* argument = SubstituteEdge(value->Argument(index), predecessor, position, emit, depth - 1u);
if (argument == nullptr) {
return nullptr;
}
arguments.push_back(argument);
}
return emit ? EmitCopy(*value, arguments, position) : value;
}
IrValue& EdgeSelector(IrBlock& block, const std::vector<bool>& edges) {
for (const auto& selector : m_edgeSelectors) {
if (selector.block == &block && selector.edges == edges) {
return *selector.value;
}
}
IrValue& phi = m_program.CreateValue(IrOpcode::Phi, IrType::Bool);
const auto& predecessors = block.Predecessors();
for (std::size_t index = 0; index < predecessors.size(); index++) {
phi.AddPhiOperand(predecessors[index], &m_builder.ConstantBool(edges[index]));
}
block.InsertInstructionBefore(nullptr, &phi);
m_edgeSelectors.push_back({&block, edges, &phi});
return phi;
}
void SplitDescriptorPhi(IrValue& inst) {
const auto info = ImageOpcodeInfoOf(inst.Opcode());
const std::uint32_t handleCount = info.needsSampler ? 2u : 1u;
if (inst.ArgumentCount() < handleCount || inst.Parent() == nullptr) {
return;
}
std::array<IrValue*, 2> handles {};
std::array<bool, 2> split {};
std::vector<IrValue*> phis;
for (std::uint32_t slot = 0; slot < handleCount; slot++) {
IrValue* handle = inst.Argument(slot)->Resolve();
const auto expected = slot == 0u ? IrOpcode::GetImageResource : IrOpcode::GetSamplerResource;
if (handle->Opcode() != expected || handle->ArgumentCount() != (slot == 0u ? 8u : 4u)) {
return;
}
handles[slot] = handle;
std::vector<IrValue*> handlePhis;
for (std::size_t dword = 0; dword < handle->ArgumentCount(); dword++) {
CollectDescriptorPhis(handle->Argument(dword), handlePhis, phiSearchDepth);
}
split[slot] = !handlePhis.empty();
for (IrValue* phi : handlePhis) {
if (std::ranges::find(phis, phi) == phis.end()) {
phis.push_back(phi);
}
}
}
if (phis.empty()) {
return;
}
if (!SplitDescriptorEdges(inst, handles, split, handleCount, phis)) {
SplitDescriptorWeb(inst, handles, split, handleCount);
}
}
bool SplitDescriptorEdges(IrValue& inst, const std::array<IrValue*, 2>& handles, const std::array<bool, 2>& split, std::uint32_t handleCount, const std::vector<IrValue*>& phis) {
IrBlock* block = phis.front()->Parent();
if (block == nullptr) {
return false;
}
const auto& predecessors = block->Predecessors();
if (predecessors.size() < 2u) {
return false;
}
for (const IrValue* phi : phis) {
if (phi->Parent() != block || phi->PhiBlockCount() != predecessors.size()) {
return false;
}
for (const IrBlock* predecessor : predecessors) {
if (PhiIncoming(*phi, predecessor) == nullptr) {
return false;
}
}
}
std::vector<std::uint32_t> edgeArm(predecessors.size());
std::vector<const IrBlock*> arms;
for (std::size_t edge = 0; edge < predecessors.size(); edge++) {
std::uint32_t arm = 0;
for (; arm < arms.size(); arm++) {
const bool same = std::ranges::all_of(phis, [&](const IrValue* phi) {
return EquivalentValue(m_program.Resources(), PhiIncoming(*phi, predecessors[edge]), PhiIncoming(*phi, arms[arm]));
});
if (same) {
break;
}
}
if (arm == arms.size()) {
arms.push_back(predecessors[edge]);
}
edgeArm[edge] = arm;
}
for (const IrBlock* arm : arms) {
for (std::uint32_t slot = 0; slot < handleCount; slot++) {
for (std::size_t dword = 0; split[slot] && dword < handles[slot]->ArgumentCount(); dword++) {
if (SubstituteEdge(handles[slot]->Argument(dword), arm, inst, false, phiSearchDepth) == nullptr) {
return false;
}
}
}
}
std::vector<IrValue*> conditions;
for (std::uint32_t arm = 0; arm + 1u < arms.size(); arm++) {
std::vector<bool> edges(edgeArm.size());
for (std::size_t edge = 0; edge < edgeArm.size(); edge++) {
edges[edge] = edgeArm[edge] == arm;
}
conditions.push_back(&EdgeSelector(*block, edges));
}
ReplaceWithArmCopies(inst, handles, split, handleCount, conditions, [&](std::uint32_t arm, std::uint32_t slot, std::size_t dword) {
return SubstituteEdge(handles[slot]->Argument(dword), arms[arm], inst, true, phiSearchDepth);
});
return true;
}
template <typename Dword>
void ReplaceWithArmCopies(IrValue& inst, const std::array<IrValue*, 2>& handles, const std::array<bool, 2>& split, std::uint32_t handleCount, std::span<IrValue* const> conditions, Dword&& dword) {
std::vector<IrValue*> copies;
const auto flags = inst.Flags<MemoryFlags>();
const auto memory = m_program.Resources().memoryInfo.at(flags.index);
for (std::uint32_t arm = 0; arm <= conditions.size(); arm++) {
std::vector<IrValue*> arguments(inst.Arguments().begin(), inst.Arguments().end());