forked from KhronosGroup/Vulkan-ValidationLayers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
synchronization_validation.cpp
6413 lines (5693 loc) · 345 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(); }
static bool SimpleBinding(const IMAGE_STATE &image_state) {
bool simple =
SimpleBinding(static_cast<const BINDABLE &>(image_state)) || image_state.IsSwapchainImage() || image_state.bind_swapchain;
// If it's not simple we must have an encoder.
assert(!simple || image_state.fragment_encoder.get());
return simple;
}
static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
static const 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 ResourceUsageRecord &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();
}
static std::string string_UsageIndex(SyncStageAccessIndex usage_index) {
const char *stage_access_name = "INVALID_STAGE_ACCESS";
if (usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())) {
stage_access_name = syncStageAccessInfoByStageAccessIndex[usage_index].name;
}
return std::string(stage_access_name);
}
struct NoopBarrierAction {
explicit NoopBarrierAction() {}
void operator()(ResourceAccessState *access) const {}
const bool layout_transition = false;
};
// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
: CommandBufferAccessContext(from.sync_state_) {
// Copy only the needed fields out of from for a temporary, proxy command buffer context
cb_state_ = from.cb_state_;
queue_flags_ = from.queue_flags_;
destroyed_ = from.destroyed_;
access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
command_number_ = from.command_number_;
subcommand_number_ = from.subcommand_number_;
reset_count_ = from.reset_count_;
const auto *from_context = from.GetCurrentAccessContext();
assert(from_context);
// Construct a fully resolved single access context out of from
const NoopBarrierAction noop_barrier;
for (AccessAddressType address_type : kAddressTypes) {
from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
&cb_access_context_.GetAccessStateMap(address_type), nullptr);
}
// The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
cb_access_context_.ImportAsyncContexts(*from_context);
events_context_ = from.events_context_;
// We don't want to copy the full render_pass_context_ history just for the proxy.
}
std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
std::stringstream out;
assert(tag < access_log_.size());
const auto &record = access_log_[tag];
out << string_UsageTag(record);
if (record.cb_state != cb_state_.get()) {
out << ", command_buffer: " << sync_state_->report_data->FormatHandle(record.cb_state->commandBuffer()).c_str();
if (record.cb_state->Destroyed()) {
out << " (destroyed)";
}
out << ", reset_no: " << std::to_string(record.reset_count);
} else {
out << ", reset_no: " << std::to_string(reset_count_);
}
return out.str();
}
std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
std::stringstream out;
out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
out << ", " << FormatUsage(access.tag) << ")";
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 << "(";
if (!hazard.recorded_access.get()) {
// if we have a recorded usage the usage is reported from the recorded contexts point of view
out << "usage: " << usage_info.name << ", ";
}
out << "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);
}
assert(tag < access_log_.size());
out << ", " << FormatUsage(tag) << ")";
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(ResourceUsageRecord::kMaxIndex);
static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
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 RangeMap
template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
class MapRangesRangeGenerator {
public:
// Default constructed is safe to dereference for "empty" test, but for no other operation.
MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
// Default construction for KeyType *must* be empty range
assert(current_.empty());
}
MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
SeekBegin();
}
MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
const KeyType &operator*() const { return current_; }
const KeyType *operator->() const { return ¤t_; }
MapRangesRangeGenerator &operator++() {
++map_pos_;
UpdateCurrent();
return *this;
}
bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
protected:
void UpdateCurrent() {
if (map_pos_ != map_->cend()) {
current_ = range_ & map_pos_->first;
} else {
current_ = KeyType();
}
}
void SeekBegin() {
map_pos_ = map_->lower_bound(range_);
UpdateCurrent();
}
// Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
// Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
template <typename Pred>
MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
do {
++map_pos_;
} while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
UpdateCurrent();
return *this;
}
const KeyType range_;
const RangeMap *map_;
typename RangeMap::const_iterator map_pos_;
KeyType current_;
};
using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
public:
using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
// Default constructed is safe to dereference for "empty" test, but for no other operation.
PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
: Base(filter, range), pred_(pred) {}
PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
PredicatedMapRangesRangeGenerator &operator++() {
Base::PredicatedIncrement(pred_);
return *this;
}
protected:
Predicate pred_;
};
// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
// Templated to allow for different Range generators or map sources...
template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::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 RangeMap &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 RangeMap *filter_;
RangeGen gen_;
typename RangeMap::const_iterator filter_pos_;
KeyType current_;
};
using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
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 AttachmentViewGenVector &attachment_views,
uint32_t subpass) {
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],
AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
SyncOrdering::kColorAttachment);
action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
SyncOrdering::kColorAttachment);
}
}
}
// 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;
// Figure out which aspects are actually touched during resolve operations
const char *aspect_string = nullptr;
AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
if (resolve_depth && resolve_stencil) {
aspect_string = "depth/stencil";
} else if (resolve_depth) {
// Validate depth only
gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
aspect_string = "depth";
} else if (resolve_stencil) {
// Validate all stencil only
gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
aspect_string = "stencil";
}
if (aspect_string) {
action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
}
}
}
// 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 AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
SyncOrdering ordering_rule) {
HazardResult hazard;
hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
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, ResourceUsageTag tag) : context_(context), tag_(tag) {}
void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
// Ignores validation only arguments...
context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, 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 = layer_data::make_unique<const ResourceAccessState>(*access_state_);
usage_index = usage_index_;
hazard = hazard_;
prior_access = prior_;
tag = tag_;
}
void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
}
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];
bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
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 (has_barrier_from_external) {
// Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
src_external_ = &prev_.back();
}
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 the_end = accesses.cend(); // End is not invalidated
auto pos = accesses.lower_bound(range);
ResourceAccessRange gap = {range.begin, range.begin};
while (pos != the_end && pos->first.begin < range.end) {
// 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;
++pos;
}
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);
auto pos = accesses.lower_bound(range);
const auto the_end = accesses.end();
HazardResult hazard;
while (pos != the_end && pos->first.begin < range.end) {
hazard = detector.DetectAsync(pos, start_tag_);
if (hazard.hazard) break;
++pos;
}
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 ApplyTrackbackStackAction {
explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
const ResourceAccessStateFunction *previous_barrier_ = nullptr)
: barriers(barriers_), previous_barrier(previous_barrier_) {}
void operator()(ResourceAccessState *access) const {
assert(access);
assert(!access->HasPendingState());
access->ApplyBarriers(barriers, false);
access->ApplyPendingBarriers(kCurrentCommandTag);
if (previous_barrier) {
assert(bool(*previous_barrier));
(*previous_barrier)(access);
}
}
const std::vector<SyncBarrier> &barriers;
const ResourceAccessStateFunction *previous_barrier;
};
// 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) {
ResourceAccessRange recurrence_range = current_range;
// The current context is empty for the current range, so recur to fill the gap.
// Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
// is not valid, to minimize that recurrence
if (current->pos_B.at_end()) {
// Do the remainder here....
recurrence_range.end = range.end;
} else {
// Recur only over the range until B becomes valid (within the limits of range).
recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
}
ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
// 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 = recurrence_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};
ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
}
}
template <typename BarrierAction>
void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
const BarrierAction &previous_barrier) const {
ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
}
void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
const ResourceAccessStateFunction *previous_barrier) const {
if (prev_.size() == 0) {
if (range.non_empty() && infill_state) {
// Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
ResourceAccessState state_copy;
if (previous_barrier) {
assert(bool(*previous_barrier));
state_copy = *infill_state;
(*previous_barrier)(&state_copy);
infill_state = &state_copy;
}
sparse_container::update_range_value(*descent_map, range, *infill_state,