forked from KhronosGroup/Vulkan-ValidationLayers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsynchronization_validation.cpp
5850 lines (5213 loc) · 318 KB
/
synchronization_validation.cpp
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
/* Copyright (c) 2019-2021 The Khronos Group Inc.
* Copyright (c) 2019-2021 Valve Corporation
* Copyright (c) 2019-2021 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: John Zulauf <[email protected]>
* Author: Locke Lin <[email protected]>
* Author: Jeremy Gebben <[email protected]>
*/
#include <limits>
#include <vector>
#include <memory>
#include <bitset>
#include "synchronization_validation.h"
#include "sync_utils.h"
static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; }
const static std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
AccessAddressType::kLinear, AccessAddressType::kIdealized};
static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
}
static const char *string_SyncHazardVUID(SyncHazard hazard) {
switch (hazard) {
case SyncHazard::NONE:
return "SYNC-HAZARD-NONE";
break;
case SyncHazard::READ_AFTER_WRITE:
return "SYNC-HAZARD-READ_AFTER_WRITE";
break;
case SyncHazard::WRITE_AFTER_READ:
return "SYNC-HAZARD-WRITE_AFTER_READ";
break;
case SyncHazard::WRITE_AFTER_WRITE:
return "SYNC-HAZARD-WRITE_AFTER_WRITE";
break;
case SyncHazard::READ_RACING_WRITE:
return "SYNC-HAZARD-READ-RACING-WRITE";
break;
case SyncHazard::WRITE_RACING_WRITE:
return "SYNC-HAZARD-WRITE-RACING-WRITE";
break;
case SyncHazard::WRITE_RACING_READ:
return "SYNC-HAZARD-WRITE-RACING-READ";
break;
default:
assert(0);
}
return "SYNC-HAZARD-INVALID";
}
static bool IsHazardVsRead(SyncHazard hazard) {
switch (hazard) {
case SyncHazard::NONE:
return false;
break;
case SyncHazard::READ_AFTER_WRITE:
return false;
break;
case SyncHazard::WRITE_AFTER_READ:
return true;
break;
case SyncHazard::WRITE_AFTER_WRITE:
return false;
break;
case SyncHazard::READ_RACING_WRITE:
return false;
break;
case SyncHazard::WRITE_RACING_WRITE:
return false;
break;
case SyncHazard::WRITE_RACING_READ:
return true;
break;
default:
assert(0);
}
return false;
}
static const char *string_SyncHazard(SyncHazard hazard) {
switch (hazard) {
case SyncHazard::NONE:
return "NONR";
break;
case SyncHazard::READ_AFTER_WRITE:
return "READ_AFTER_WRITE";
break;
case SyncHazard::WRITE_AFTER_READ:
return "WRITE_AFTER_READ";
break;
case SyncHazard::WRITE_AFTER_WRITE:
return "WRITE_AFTER_WRITE";
break;
case SyncHazard::READ_RACING_WRITE:
return "READ_RACING_WRITE";
break;
case SyncHazard::WRITE_RACING_WRITE:
return "WRITE_RACING_WRITE";
break;
case SyncHazard::WRITE_RACING_READ:
return "WRITE_RACING_READ";
break;
default:
assert(0);
}
return "INVALID HAZARD";
}
static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
// Return the info for the first bit found
const SyncStageAccessInfoType *info = nullptr;
for (size_t i = 0; i < flags.size(); i++) {
if (flags.test(i)) {
info = &syncStageAccessInfoByStageAccessIndex[i];
break;
}
}
return info;
}
static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
std::string out_str;
if (flags.none()) {
out_str = "0";
} else {
for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
const auto &info = syncStageAccessInfoByStageAccessIndex[i];
if ((flags & info.stage_access_bit).any()) {
if (!out_str.empty()) {
out_str.append(sep);
}
out_str.append(info.name);
}
}
if (out_str.length() == 0) {
out_str.append("Unhandled SyncStageAccess");
}
}
return out_str;
}
static std::string string_UsageTag(const ResourceUsageTag &tag) {
std::stringstream out;
out << "command: " << CommandTypeString(tag.command);
out << ", seq_no: " << tag.seq_num;
if (tag.sub_command != 0) {
out << ", subcmd: " << tag.sub_command;
}
return out.str();
}
std::string CommandBufferAccessContext::FormatUsage(const HazardResult &hazard) const {
const auto &tag = hazard.tag;
assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
std::stringstream out;
const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name;
if (IsHazardVsRead(hazard.hazard)) {
const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
out << ", read_barriers: " << string_VkPipelineStageFlags2KHR(barriers);
} else {
SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
}
// PHASE2 TODO -- add comand buffer and reset from secondary if applicable
out << ", " << string_UsageTag(tag) << ", reset_no: " << reset_count_;
return out.str();
}
// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
// also reflects this special case for read hazard detection (using access instead of exec scope)
static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
static const SyncStageAccessFlags kColorAttachmentAccessScope =
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR;
static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
{{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
{kColorAttachmentExecScope, kColorAttachmentAccessScope},
{kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
{kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
// Sometimes we have an internal access conflict, and we using the kCurrentCommandTag to set and detect in temporary/proxy contexts
static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, ResourceUsageTag::kMaxCount,
ResourceUsageTag::kMaxCount, CMD_NONE);
static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) {
return bindable.binding.offset + bindable.binding.mem_state->fake_base_address;
}
inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
if (size == VK_WHOLE_SIZE) {
return (whole_size - offset);
}
return size;
}
static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
return GetRealWholeSize(offset, size, buf_state.createInfo.size);
}
template <typename T>
static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
}
static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
}
static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
}
// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
//
// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
//
// Usage:
// Constructor() -- initializes the generator to point to the begin of the space declared.
// * -- the current range of the generator empty signfies end
// ++ -- advance to the next non-empty range (or end)
// A wrapper for a single range with the same semantics as the actual generators below
template <typename KeyType>
class SingleRangeGenerator {
public:
SingleRangeGenerator(const KeyType &range) : current_(range) {}
const KeyType &operator*() const { return current_; }
const KeyType *operator->() const { return ¤t_; }
SingleRangeGenerator &operator++() {
current_ = KeyType(); // just one real range
return *this;
}
bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
private:
SingleRangeGenerator() = default;
const KeyType range_;
KeyType current_;
};
// Generate the ranges that are the intersection of range and the entries in the FilterMap
template <typename FilterMap, typename KeyType = typename FilterMap::key_type>
class FilteredRangeGenerator {
public:
// Default constructed is safe to dereference for "empty" test, but for no other operation.
FilteredRangeGenerator() : range_(), filter_(nullptr), filter_pos_(), current_() {
// Default construction for KeyType *must* be empty range
assert(current_.empty());
}
FilteredRangeGenerator(const FilterMap &filter, const KeyType &range)
: range_(range), filter_(&filter), filter_pos_(), current_() {
SeekBegin();
}
FilteredRangeGenerator(const FilteredRangeGenerator &from) = default;
const KeyType &operator*() const { return current_; }
const KeyType *operator->() const { return ¤t_; }
FilteredRangeGenerator &operator++() {
++filter_pos_;
UpdateCurrent();
return *this;
}
bool operator==(const FilteredRangeGenerator &other) const { return current_ == other.current_; }
private:
void UpdateCurrent() {
if (filter_pos_ != filter_->cend()) {
current_ = range_ & filter_pos_->first;
} else {
current_ = KeyType();
}
}
void SeekBegin() {
filter_pos_ = filter_->lower_bound(range_);
UpdateCurrent();
}
const KeyType range_;
const FilterMap *filter_;
typename FilterMap::const_iterator filter_pos_;
KeyType current_;
};
using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
using EventSimpleRangeGenerator = FilteredRangeGenerator<SyncEventState::ScopeMap>;
// Templated to allow for different Range generators or map sources...
// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
template <typename FilterMap, typename RangeGen, typename KeyType = typename FilterMap::key_type>
class FilteredGeneratorGenerator {
public:
// Default constructed is safe to dereference for "empty" test, but for no other operation.
FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
// Default construction for KeyType *must* be empty range
assert(current_.empty());
}
FilteredGeneratorGenerator(const FilterMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
SeekBegin();
}
FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
const KeyType &operator*() const { return current_; }
const KeyType *operator->() const { return ¤t_; }
FilteredGeneratorGenerator &operator++() {
KeyType gen_range = GenRange();
KeyType filter_range = FilterRange();
current_ = KeyType();
while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
if (gen_range.end > filter_range.end) {
// if the generated range is beyond the filter_range, advance the filter range
filter_range = AdvanceFilter();
} else {
gen_range = AdvanceGen();
}
current_ = gen_range & filter_range;
}
return *this;
}
bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
private:
KeyType AdvanceFilter() {
++filter_pos_;
auto filter_range = FilterRange();
if (filter_range.valid()) {
FastForwardGen(filter_range);
}
return filter_range;
}
KeyType AdvanceGen() {
++gen_;
auto gen_range = GenRange();
if (gen_range.valid()) {
FastForwardFilter(gen_range);
}
return gen_range;
}
KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
KeyType GenRange() const { return *gen_; }
KeyType FastForwardFilter(const KeyType &range) {
auto filter_range = FilterRange();
int retry_count = 0;
const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
while (!filter_range.empty() && (filter_range.end <= range.begin)) {
if (retry_count < kRetryLimit) {
++filter_pos_;
filter_range = FilterRange();
retry_count++;
} else {
// Okay we've tried walking, do a seek.
filter_pos_ = filter_->lower_bound(range);
break;
}
}
return FilterRange();
}
// TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
// faster.
KeyType FastForwardGen(const KeyType &range) {
auto gen_range = GenRange();
while (!gen_range.empty() && (gen_range.end <= range.begin)) {
++gen_;
gen_range = GenRange();
}
return gen_range;
}
void SeekBegin() {
auto gen_range = GenRange();
if (gen_range.empty()) {
current_ = KeyType();
filter_pos_ = filter_->cend();
} else {
filter_pos_ = filter_->lower_bound(gen_range);
current_ = gen_range & FilterRange();
}
}
const FilterMap *filter_;
RangeGen gen_;
typename FilterMap::const_iterator filter_pos_;
KeyType current_;
};
using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
VkDeviceSize stride) {
VkDeviceSize range_start = offset + first_index * stride;
VkDeviceSize range_size = 0;
if (count == UINT32_MAX) {
range_size = buf_whole_size - range_start;
} else {
range_size = count * stride;
}
return MakeRange(range_start, range_size);
}
SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
VkShaderStageFlagBits stage_flag) {
if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
}
auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
if (stage_access == syncStageAccessMaskByShaderStage.end()) {
assert(0);
}
if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
return stage_access->second.uniform_read;
}
// If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
// Because if write hazard happens, read hazard might or might not happen.
// But if write hazard doesn't happen, read hazard is impossible to happen.
if (descriptor_data.is_writable) {
return stage_access->second.storage_write;
}
// TODO: sampled_read
return stage_access->second.storage_read;
}
bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
? true
: false;
}
bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
? true
: false;
}
// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
template <typename Action>
static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
Action &action) {
// At this point the "apply over range" logic only supports a single memory binding
if (!SimpleBinding(image_state)) return;
auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
const auto base_address = ResourceBaseAddress(image_state);
subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
image_state.createInfo.extent, base_address);
for (; range_gen->non_empty(); ++range_gen) {
action(*range_gen);
}
}
// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
// Used by both validation and record operations
//
// The signature for Action() reflect the needs of both uses.
template <typename Action>
void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) {
VkExtent3D extent = CastTo3D(render_area.extent);
VkOffset3D offset = CastTo3D(render_area.offset);
const auto &rp_ci = rp_state.createInfo;
const auto *attachment_ci = rp_ci.pAttachments;
const auto &subpass_ci = rp_ci.pSubpasses[subpass];
// Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
const auto *color_attachments = subpass_ci.pColorAttachments;
const auto *color_resolve = subpass_ci.pResolveAttachments;
if (color_resolve && color_attachments) {
for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
const auto &color_attach = color_attachments[i].attachment;
const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kColorAttachment, offset, extent, 0);
action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment, offset, extent, 0);
}
}
}
// Depth stencil resolve only if the extension is present
const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
(ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
(subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
const auto src_ci = attachment_ci[src_at];
// The formats are required to match so we can pick either
const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
VkImageAspectFlags aspect_mask = 0u;
// Figure out which aspects are actually touched during resolve operations
const char *aspect_string = nullptr;
if (resolve_depth && resolve_stencil) {
// Validate all aspects together
aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
aspect_string = "depth/stencil";
} else if (resolve_depth) {
// Validate depth only
aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
aspect_string = "depth";
} else if (resolve_stencil) {
// Validate all stencil only
aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT;
aspect_string = "stencil";
}
if (aspect_mask) {
action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at],
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster, offset, extent, aspect_mask);
action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at],
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, offset, extent, aspect_mask);
}
}
}
// Action for validating resolve operations
class ValidateResolveAction {
public:
ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
const CommandExecutionContext &ex_context, const char *func_name)
: render_pass_(render_pass),
subpass_(subpass),
context_(context),
ex_context_(ex_context),
func_name_(func_name),
skip_(false) {}
void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
HazardResult hazard;
hazard = context_.DetectHazard(view, current_usage, ordering_rule, offset, extent, aspect_mask);
if (hazard.hazard) {
skip_ |=
ex_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
"%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
" to resolve attachment %" PRIu32 ". Access info %s.",
func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
attachment_name, src_at, dst_at, ex_context_.FormatUsage(hazard).c_str());
}
}
// Providing a mechanism for the constructing caller to get the result of the validation
bool GetSkip() const { return skip_; }
private:
VkRenderPass render_pass_;
const uint32_t subpass_;
const AccessContext &context_;
const CommandExecutionContext &ex_context_;
const char *func_name_;
bool skip_;
};
// Update action for resolve operations
class UpdateStateResolveAction {
public:
UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {}
void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
// Ignores validation only arguments...
context_.UpdateAccessState(view, current_usage, ordering_rule, offset, extent, aspect_mask, tag_);
}
private:
AccessContext &context_;
const ResourceUsageTag &tag_;
};
void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) {
access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_));
usage_index = usage_index_;
hazard = hazard_;
prior_access = prior_;
tag = tag_;
}
AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
const std::vector<SubpassDependencyGraphNode> &dependencies,
const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
Reset();
const auto &subpass_dep = dependencies[subpass];
prev_.reserve(subpass_dep.prev.size());
prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
for (const auto &prev_dep : subpass_dep.prev) {
const auto prev_pass = prev_dep.first->pass;
const auto &prev_barriers = prev_dep.second;
assert(prev_dep.second.size());
prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
prev_by_subpass_[prev_pass] = &prev_.back();
}
async_.reserve(subpass_dep.async.size());
for (const auto async_subpass : subpass_dep.async) {
async_.emplace_back(&contexts[async_subpass]);
}
if (subpass_dep.barrier_from_external.size()) {
src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external);
}
if (subpass_dep.barrier_to_external.size()) {
dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
}
}
template <typename Detector>
HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
const ResourceAccessRange &range) const {
ResourceAccessRangeMap descent_map;
ResolvePreviousAccess(type, range, &descent_map, nullptr);
HazardResult hazard;
for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
hazard = detector.Detect(prev);
}
return hazard;
}
template <typename Action>
void AccessContext::ForAll(Action &&action) {
for (const auto address_type : kAddressTypes) {
auto &accesses = GetAccessStateMap(address_type);
for (const auto &access : accesses) {
action(address_type, access);
}
}
}
// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
// the DAG of the contexts (for example subpasses)
template <typename Detector>
HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
DetectOptions options) const {
HazardResult hazard;
if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
// Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
// so we'll check these first
for (const auto &async_context : async_) {
hazard = async_context->DetectAsyncHazard(type, detector, range);
if (hazard.hazard) return hazard;
}
}
const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
const auto &accesses = GetAccessStateMap(type);
const auto from = accesses.lower_bound(range);
const auto to = accesses.upper_bound(range);
ResourceAccessRange gap = {range.begin, range.begin};
for (auto pos = from; pos != to; ++pos) {
// Cover any leading gap, or gap between entries
if (detect_prev) {
// TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
// Cover any leading gap, or gap between entries
gap.end = pos->first.begin; // We know this begin is < range.end
if (gap.non_empty()) {
// Recur on all gaps
hazard = DetectPreviousHazard(type, detector, gap);
if (hazard.hazard) return hazard;
}
// Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
gap.begin = pos->first.end;
}
hazard = detector.Detect(pos);
if (hazard.hazard) return hazard;
}
if (detect_prev) {
// Detect in the trailing empty as needed
gap.end = range.end;
if (gap.non_empty()) {
hazard = DetectPreviousHazard(type, detector, gap);
}
}
return hazard;
}
// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
template <typename Detector>
HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
const ResourceAccessRange &range) const {
auto &accesses = GetAccessStateMap(type);
const auto from = accesses.lower_bound(range);
const auto to = accesses.upper_bound(range);
HazardResult hazard;
for (auto pos = from; pos != to && !hazard.hazard; ++pos) {
hazard = detector.DetectAsync(pos, start_tag_);
}
return hazard;
}
struct ApplySubpassTransitionBarriersAction {
explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
void operator()(ResourceAccessState *access) const {
assert(access);
access->ApplyBarriers(barriers, true);
}
const std::vector<SyncBarrier> &barriers;
};
struct ApplyTrackbackBarriersAction {
explicit ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
void operator()(ResourceAccessState *access) const {
assert(access);
assert(!access->HasPendingState());
access->ApplyBarriers(barriers, false);
access->ApplyPendingBarriers(kCurrentCommandTag);
}
const std::vector<SyncBarrier> &barriers;
};
// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
// *different* map from dest.
// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
// range [first, last)
template <typename BarrierAction>
static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
BarrierAction &barrier_action) {
auto at = entry;
for (auto pos = first; pos != last; ++pos) {
// Every member of the input iterator range must fit within the remaining portion of entry
assert(at->first.includes(pos->first));
assert(at != dest->end());
// Trim up at to the same size as the entry to resolve
at = sparse_container::split(at, *dest, pos->first);
auto access = pos->second; // intentional copy
barrier_action(&access);
at->second.Resolve(access);
++at; // Go to the remaining unused section of entry
}
}
static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
SyncBarrier merged = {};
for (const auto &barrier : barriers) {
merged.Merge(barrier);
}
return merged;
}
template <typename BarrierAction>
void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
bool recur_to_infill) const {
if (!range.non_empty()) return;
ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
while (current->range.non_empty() && range.includes(current->range.begin)) {
const auto current_range = current->range & range;
if (current->pos_B->valid) {
const auto &src_pos = current->pos_B->lower_bound;
auto access = src_pos->second; // intentional copy
barrier_action(&access);
if (current->pos_A->valid) {
const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
trimmed->second.Resolve(access);
current.invalidate_A(trimmed);
} else {
auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
}
} else {
// we have to descend to fill this gap
if (recur_to_infill) {
if (current->pos_A->valid) {
// Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation
ResourceAccessRangeMap gap_map;
ResolvePreviousAccess(type, current_range, &gap_map, infill_state);
ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action);
} else {
// There isn't anything in dest in current)range, so we can accumulate directly into it.
ResolvePreviousAccess(type, current_range, resolve_map, infill_state);
// Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current
for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) {
barrier_action(&pos->second);
}
}
// Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
// iterator of the outer while.
// Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
// not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
// we stepped on the dest map
const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
current.invalidate_A(); // Changes current->range
current.seek(seek_to);
} else if (!current->pos_A->valid && infill_state) {
// If we didn't find anything in the current range, and we aren't reccuring... we infill if required
auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
}
}
++current;
}
// Infill if range goes passed both the current and resolve map prior contents
if (recur_to_infill && (current->range.end < range.end)) {
ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
ResourceAccessRangeMap gap_map;
const auto the_end = resolve_map->end();
ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state);
for (auto &access : gap_map) {
barrier_action(&access.second);
resolve_map->insert(the_end, access);
}
}
}
void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
if ((prev_.size() == 0) && (src_external_.context == nullptr)) {
if (range.non_empty() && infill_state) {
descent_map->insert(std::make_pair(range, *infill_state));
}
} else {
// Look for something to fill the gap further along.
for (const auto &prev_dep : prev_) {
const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers);
prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
}
if (src_external_.context) {
const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers);
src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
}
}
}
// Non-lazy import of all accesses, WaitEvents needs this.
void AccessContext::ResolvePreviousAccesses() {
ResourceAccessState default_state;
for (const auto address_type : kAddressTypes) {
ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
}
}
AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
}
static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
: SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE;
return stage_access;
}
static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
: SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE;
return stage_access;
}
// Caller must manage returned pointer
static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
uint32_t subpass, const VkRect2D &render_area,
std::vector<const IMAGE_VIEW_STATE *> attachment_views) {
auto *proxy = new AccessContext(context);
proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
return proxy;
}
template <typename BarrierAction>
class ResolveAccessRangeFunctor {
public:
ResolveAccessRangeFunctor(const AccessContext &context, AccessAddressType address_type, ResourceAccessRangeMap *descent_map,
const ResourceAccessState *infill_state, BarrierAction &barrier_action)
: context_(context),
address_type_(address_type),
descent_map_(descent_map),
infill_state_(infill_state),
barrier_action_(barrier_action) {}
ResolveAccessRangeFunctor() = delete;
void operator()(const ResourceAccessRange &range) const {
context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_);
}
private:
const AccessContext &context_;
const AccessAddressType address_type_;
ResourceAccessRangeMap *const descent_map_;
const ResourceAccessState *infill_state_;
BarrierAction &barrier_action_;
};
template <typename BarrierAction>
void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range,
BarrierAction &barrier_action, AccessAddressType address_type,
ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action);
ApplyOverImageRange(image_state, subresource_range, action);
}
// Layout transitions are handled as if the were occuring in the beginning of the next subpass
bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &ex_context, const RENDER_PASS_STATE &rp_state,
const VkRect2D &render_area, uint32_t subpass,
const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
const char *func_name) const {
bool skip = false;
// As validation methods are const and precede the record/update phase, for any tranistions from the immediately
// previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
// those affects have not been recorded yet.
//
// Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
// to apply and only copy then, if this proves a hot spot.
std::unique_ptr<AccessContext> proxy_for_prev;
TrackBack proxy_track_back;
const auto &transitions = rp_state.subpass_transitions[subpass];
for (const auto &transition : transitions) {
const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
if (prev_needs_proxy) {
if (!proxy_for_prev) {
proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass,
render_area, attachment_views));
proxy_track_back = *track_back;
proxy_track_back.context = proxy_for_prev.get();
}
track_back = &proxy_track_back;
}
auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
if (hazard.hazard) {
skip |= ex_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
"%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
" image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
string_VkImageLayout(transition.old_layout),
string_VkImageLayout(transition.new_layout),
ex_context.FormatUsage(hazard).c_str());
}
}
return skip;
}
bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &ex_context, const RENDER_PASS_STATE &rp_state,
const VkRect2D &render_area, uint32_t subpass,
const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
const char *func_name) const {
bool skip = false;
const auto *attachment_ci = rp_state.createInfo.pAttachments;
VkExtent3D extent = CastTo3D(render_area.extent);
VkOffset3D offset = CastTo3D(render_area.offset);
for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {