blob: ab645716450cc318db510f7286718c9876abc7da [file] [log] [blame]
John Zulaufab7756b2020-12-29 16:10:16 -07001/* Copyright (c) 2019-2021 The Khronos Group Inc.
2 * Copyright (c) 2019-2021 Valve Corporation
3 * Copyright (c) 2019-2021 LunarG, Inc.
John Zulauf9cb530d2019-09-30 14:14:10 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: John Zulauf <jzulauf@lunarg.com>
John Zulaufab7756b2020-12-29 16:10:16 -070018 * Author: Locke Lin <locke@lunarg.com>
19 * Author: Jeremy Gebben <jeremyg@lunarg.com>
John Zulauf9cb530d2019-09-30 14:14:10 -060020 */
21
22#include <limits>
23#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060024#include <memory>
25#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060026#include "synchronization_validation.h"
Jeremy Gebben5f585ae2021-02-02 09:03:06 -070027#include "sync_utils.h"
John Zulauf9cb530d2019-09-30 14:14:10 -060028
John Zulauf264cce02021-02-05 14:40:47 -070029static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; }
30
John Zulauf43cc7462020-12-03 12:33:12 -070031const static std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
32 AccessAddressType::kLinear, AccessAddressType::kIdealized};
33
John Zulaufd5115702021-01-18 12:34:33 -070034static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
John Zulauf264cce02021-02-05 14:40:47 -070035static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
36 return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
37}
John Zulaufd5115702021-01-18 12:34:33 -070038
John Zulauf9cb530d2019-09-30 14:14:10 -060039static const char *string_SyncHazardVUID(SyncHazard hazard) {
40 switch (hazard) {
41 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070042 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060043 break;
44 case SyncHazard::READ_AFTER_WRITE:
45 return "SYNC-HAZARD-READ_AFTER_WRITE";
46 break;
47 case SyncHazard::WRITE_AFTER_READ:
48 return "SYNC-HAZARD-WRITE_AFTER_READ";
49 break;
50 case SyncHazard::WRITE_AFTER_WRITE:
51 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
52 break;
John Zulauf2f952d22020-02-10 11:34:51 -070053 case SyncHazard::READ_RACING_WRITE:
54 return "SYNC-HAZARD-READ-RACING-WRITE";
55 break;
56 case SyncHazard::WRITE_RACING_WRITE:
57 return "SYNC-HAZARD-WRITE-RACING-WRITE";
58 break;
59 case SyncHazard::WRITE_RACING_READ:
60 return "SYNC-HAZARD-WRITE-RACING-READ";
61 break;
John Zulauf9cb530d2019-09-30 14:14:10 -060062 default:
63 assert(0);
64 }
65 return "SYNC-HAZARD-INVALID";
66}
67
John Zulauf59e25072020-07-17 10:55:21 -060068static bool IsHazardVsRead(SyncHazard hazard) {
69 switch (hazard) {
70 case SyncHazard::NONE:
71 return false;
72 break;
73 case SyncHazard::READ_AFTER_WRITE:
74 return false;
75 break;
76 case SyncHazard::WRITE_AFTER_READ:
77 return true;
78 break;
79 case SyncHazard::WRITE_AFTER_WRITE:
80 return false;
81 break;
82 case SyncHazard::READ_RACING_WRITE:
83 return false;
84 break;
85 case SyncHazard::WRITE_RACING_WRITE:
86 return false;
87 break;
88 case SyncHazard::WRITE_RACING_READ:
89 return true;
90 break;
91 default:
92 assert(0);
93 }
94 return false;
95}
96
John Zulauf9cb530d2019-09-30 14:14:10 -060097static const char *string_SyncHazard(SyncHazard hazard) {
98 switch (hazard) {
99 case SyncHazard::NONE:
100 return "NONR";
101 break;
102 case SyncHazard::READ_AFTER_WRITE:
103 return "READ_AFTER_WRITE";
104 break;
105 case SyncHazard::WRITE_AFTER_READ:
106 return "WRITE_AFTER_READ";
107 break;
108 case SyncHazard::WRITE_AFTER_WRITE:
109 return "WRITE_AFTER_WRITE";
110 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700111 case SyncHazard::READ_RACING_WRITE:
112 return "READ_RACING_WRITE";
113 break;
114 case SyncHazard::WRITE_RACING_WRITE:
115 return "WRITE_RACING_WRITE";
116 break;
117 case SyncHazard::WRITE_RACING_READ:
118 return "WRITE_RACING_READ";
119 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600120 default:
121 assert(0);
122 }
123 return "INVALID HAZARD";
124}
125
John Zulauf37ceaed2020-07-03 16:18:15 -0600126static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
127 // Return the info for the first bit found
128 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700129 for (size_t i = 0; i < flags.size(); i++) {
130 if (flags.test(i)) {
131 info = &syncStageAccessInfoByStageAccessIndex[i];
132 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600133 }
134 }
135 return info;
136}
137
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700138static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600139 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700140 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600141 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700142 } else {
143 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
144 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
145 if ((flags & info.stage_access_bit).any()) {
146 if (!out_str.empty()) {
147 out_str.append(sep);
148 }
149 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600150 }
John Zulauf59e25072020-07-17 10:55:21 -0600151 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700152 if (out_str.length() == 0) {
153 out_str.append("Unhandled SyncStageAccess");
154 }
John Zulauf59e25072020-07-17 10:55:21 -0600155 }
156 return out_str;
157}
158
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700159static std::string string_UsageTag(const ResourceUsageTag &tag) {
160 std::stringstream out;
161
John Zulauffaea0ee2021-01-14 14:01:32 -0700162 out << "command: " << CommandTypeString(tag.command);
163 out << ", seq_no: " << tag.seq_num;
164 if (tag.sub_command != 0) {
165 out << ", subcmd: " << tag.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700166 }
167 return out.str();
168}
169
John Zulauffaea0ee2021-01-14 14:01:32 -0700170std::string CommandBufferAccessContext::FormatUsage(const HazardResult &hazard) const {
John Zulauf37ceaed2020-07-03 16:18:15 -0600171 const auto &tag = hazard.tag;
John Zulauf59e25072020-07-17 10:55:21 -0600172 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
173 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
John Zulauf1dae9192020-06-16 15:46:44 -0600174 std::stringstream out;
John Zulauf37ceaed2020-07-03 16:18:15 -0600175 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
176 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
John Zulauf59e25072020-07-17 10:55:21 -0600177 out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name;
178 if (IsHazardVsRead(hazard.hazard)) {
179 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
180 out << ", read_barriers: " << string_VkPipelineStageFlags(barriers);
181 } else {
182 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
183 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
184 }
185
John Zulauffaea0ee2021-01-14 14:01:32 -0700186 // PHASE2 TODO -- add comand buffer and reset from secondary if applicable
187 out << ", " << string_UsageTag(tag) << ", reset_no: " << reset_count_;
John Zulauf1dae9192020-06-16 15:46:44 -0600188 return out.str();
189}
190
John Zulaufd14743a2020-07-03 09:42:39 -0600191// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
192// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
193// also reflects this special case for read hazard detection (using access instead of exec scope)
John Zulaufb027cdb2020-05-21 14:25:22 -0600194static constexpr VkPipelineStageFlags kColorAttachmentExecScope = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700195static const SyncStageAccessFlags kColorAttachmentAccessScope =
196 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
197 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
198 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
199 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulaufb027cdb2020-05-21 14:25:22 -0600200static constexpr VkPipelineStageFlags kDepthStencilAttachmentExecScope =
201 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700202static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
203 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
204 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
205 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulauf8e3c3e92021-01-06 11:19:36 -0700206static constexpr VkPipelineStageFlags kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
207static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600208
John Zulauf8e3c3e92021-01-06 11:19:36 -0700209ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
210 {{0U, SyncStageAccessFlags()},
211 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
212 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
213 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
214
John Zulauf7635de32020-05-29 17:14:15 -0600215// Sometimes we have an internal access conflict, and we using the kCurrentCommandTag to set and detect in temporary/proxy contexts
John Zulauffaea0ee2021-01-14 14:01:32 -0700216static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, ResourceUsageTag::kMaxCount,
217 ResourceUsageTag::kMaxCount, CMD_NONE);
John Zulaufb027cdb2020-05-21 14:25:22 -0600218
John Zulaufb02c1eb2020-10-06 16:33:36 -0600219static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) {
220 return bindable.binding.offset + bindable.binding.mem_state->fake_base_address;
221}
222
locke-lunarg3c038002020-04-30 23:08:08 -0600223inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
224 if (size == VK_WHOLE_SIZE) {
225 return (whole_size - offset);
226 }
227 return size;
228}
229
John Zulauf3e86bf02020-09-12 10:47:57 -0600230static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
231 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
232}
233
John Zulauf16adfc92020-04-08 10:28:33 -0600234template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600235static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600236 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
237}
238
John Zulauf355e49b2020-04-24 15:11:15 -0600239static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600240
John Zulauf3e86bf02020-09-12 10:47:57 -0600241static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
242 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
243}
244
245static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
246 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
247}
248
John Zulauf4a6105a2020-11-17 15:11:05 -0700249// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
250//
John Zulauf10f1f522020-12-18 12:00:35 -0700251// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
252//
John Zulauf4a6105a2020-11-17 15:11:05 -0700253// Usage:
254// Constructor() -- initializes the generator to point to the begin of the space declared.
255// * -- the current range of the generator empty signfies end
256// ++ -- advance to the next non-empty range (or end)
257
258// A wrapper for a single range with the same semantics as the actual generators below
259template <typename KeyType>
260class SingleRangeGenerator {
261 public:
262 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700263 const KeyType &operator*() const { return current_; }
264 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700265 SingleRangeGenerator &operator++() {
266 current_ = KeyType(); // just one real range
267 return *this;
268 }
269
270 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
271
272 private:
273 SingleRangeGenerator() = default;
274 const KeyType range_;
275 KeyType current_;
276};
277
278// Generate the ranges that are the intersection of range and the entries in the FilterMap
279template <typename FilterMap, typename KeyType = typename FilterMap::key_type>
280class FilteredRangeGenerator {
281 public:
John Zulaufd5115702021-01-18 12:34:33 -0700282 // Default constructed is safe to dereference for "empty" test, but for no other operation.
283 FilteredRangeGenerator() : range_(), filter_(nullptr), filter_pos_(), current_() {
284 // Default construction for KeyType *must* be empty range
285 assert(current_.empty());
286 }
John Zulauf4a6105a2020-11-17 15:11:05 -0700287 FilteredRangeGenerator(const FilterMap &filter, const KeyType &range)
288 : range_(range), filter_(&filter), filter_pos_(), current_() {
289 SeekBegin();
290 }
John Zulaufd5115702021-01-18 12:34:33 -0700291 FilteredRangeGenerator(const FilteredRangeGenerator &from) = default;
292
John Zulauf4a6105a2020-11-17 15:11:05 -0700293 const KeyType &operator*() const { return current_; }
294 const KeyType *operator->() const { return &current_; }
295 FilteredRangeGenerator &operator++() {
296 ++filter_pos_;
297 UpdateCurrent();
298 return *this;
299 }
300
301 bool operator==(const FilteredRangeGenerator &other) const { return current_ == other.current_; }
302
303 private:
John Zulauf4a6105a2020-11-17 15:11:05 -0700304 void UpdateCurrent() {
305 if (filter_pos_ != filter_->cend()) {
306 current_ = range_ & filter_pos_->first;
307 } else {
308 current_ = KeyType();
309 }
310 }
311 void SeekBegin() {
312 filter_pos_ = filter_->lower_bound(range_);
313 UpdateCurrent();
314 }
315 const KeyType range_;
316 const FilterMap *filter_;
317 typename FilterMap::const_iterator filter_pos_;
318 KeyType current_;
319};
John Zulaufd5115702021-01-18 12:34:33 -0700320using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700321using EventSimpleRangeGenerator = FilteredRangeGenerator<SyncEventState::ScopeMap>;
322
323// Templated to allow for different Range generators or map sources...
324
325// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulauf4a6105a2020-11-17 15:11:05 -0700326template <typename FilterMap, typename RangeGen, typename KeyType = typename FilterMap::key_type>
327class FilteredGeneratorGenerator {
328 public:
John Zulaufd5115702021-01-18 12:34:33 -0700329 // Default constructed is safe to dereference for "empty" test, but for no other operation.
330 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
331 // Default construction for KeyType *must* be empty range
332 assert(current_.empty());
333 }
334 FilteredGeneratorGenerator(const FilterMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700335 SeekBegin();
336 }
John Zulaufd5115702021-01-18 12:34:33 -0700337 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700338 const KeyType &operator*() const { return current_; }
339 const KeyType *operator->() const { return &current_; }
340 FilteredGeneratorGenerator &operator++() {
341 KeyType gen_range = GenRange();
342 KeyType filter_range = FilterRange();
343 current_ = KeyType();
344 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
345 if (gen_range.end > filter_range.end) {
346 // if the generated range is beyond the filter_range, advance the filter range
347 filter_range = AdvanceFilter();
348 } else {
349 gen_range = AdvanceGen();
350 }
351 current_ = gen_range & filter_range;
352 }
353 return *this;
354 }
355
356 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
357
358 private:
359 KeyType AdvanceFilter() {
360 ++filter_pos_;
361 auto filter_range = FilterRange();
362 if (filter_range.valid()) {
363 FastForwardGen(filter_range);
364 }
365 return filter_range;
366 }
367 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700368 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700369 auto gen_range = GenRange();
370 if (gen_range.valid()) {
371 FastForwardFilter(gen_range);
372 }
373 return gen_range;
374 }
375
376 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700377 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700378
379 KeyType FastForwardFilter(const KeyType &range) {
380 auto filter_range = FilterRange();
381 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700382 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700383 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
384 if (retry_count < kRetryLimit) {
385 ++filter_pos_;
386 filter_range = FilterRange();
387 retry_count++;
388 } else {
389 // Okay we've tried walking, do a seek.
390 filter_pos_ = filter_->lower_bound(range);
391 break;
392 }
393 }
394 return FilterRange();
395 }
396
397 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
398 // faster.
399 KeyType FastForwardGen(const KeyType &range) {
400 auto gen_range = GenRange();
401 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700402 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700403 gen_range = GenRange();
404 }
405 return gen_range;
406 }
407
408 void SeekBegin() {
409 auto gen_range = GenRange();
410 if (gen_range.empty()) {
411 current_ = KeyType();
412 filter_pos_ = filter_->cend();
413 } else {
414 filter_pos_ = filter_->lower_bound(gen_range);
415 current_ = gen_range & FilterRange();
416 }
417 }
418
John Zulauf4a6105a2020-11-17 15:11:05 -0700419 const FilterMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700420 RangeGen gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700421 typename FilterMap::const_iterator filter_pos_;
422 KeyType current_;
423};
424
425using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
426
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700427static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
John Zulauf5c5e88d2019-12-26 11:22:02 -0700428
John Zulauf3e86bf02020-09-12 10:47:57 -0600429ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
430 VkDeviceSize stride) {
431 VkDeviceSize range_start = offset + first_index * stride;
432 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600433 if (count == UINT32_MAX) {
434 range_size = buf_whole_size - range_start;
435 } else {
436 range_size = count * stride;
437 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600438 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600439}
440
locke-lunarg654e3692020-06-04 17:19:15 -0600441SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
442 VkShaderStageFlagBits stage_flag) {
443 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
444 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
445 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
446 }
447 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
448 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
449 assert(0);
450 }
451 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
452 return stage_access->second.uniform_read;
453 }
454
455 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
456 // Because if write hazard happens, read hazard might or might not happen.
457 // But if write hazard doesn't happen, read hazard is impossible to happen.
458 if (descriptor_data.is_writable) {
459 return stage_access->second.shader_write;
460 }
461 return stage_access->second.shader_read;
462}
463
locke-lunarg37047832020-06-12 13:44:45 -0600464bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
465 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
466 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
467 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
468 ? true
469 : false;
470}
471
472bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
473 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
474 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
475 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
476 ? true
477 : false;
478}
479
John Zulauf355e49b2020-04-24 15:11:15 -0600480// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600481template <typename Action>
482static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
483 Action &action) {
484 // At this point the "apply over range" logic only supports a single memory binding
485 if (!SimpleBinding(image_state)) return;
486 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600487 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700488 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
489 image_state.createInfo.extent, base_address);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600490 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700491 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600492 }
493}
494
John Zulauf7635de32020-05-29 17:14:15 -0600495// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
496// Used by both validation and record operations
497//
498// The signature for Action() reflect the needs of both uses.
499template <typename Action>
500void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
501 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) {
502 VkExtent3D extent = CastTo3D(render_area.extent);
503 VkOffset3D offset = CastTo3D(render_area.offset);
504 const auto &rp_ci = rp_state.createInfo;
505 const auto *attachment_ci = rp_ci.pAttachments;
506 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
507
508 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
509 const auto *color_attachments = subpass_ci.pColorAttachments;
510 const auto *color_resolve = subpass_ci.pResolveAttachments;
511 if (color_resolve && color_attachments) {
512 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
513 const auto &color_attach = color_attachments[i].attachment;
514 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
515 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
516 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700517 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600518 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700519 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600520 }
521 }
522 }
523
524 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700525 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600526 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
527 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
528 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
529 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
530 const auto src_ci = attachment_ci[src_at];
531 // The formats are required to match so we can pick either
532 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
533 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
534 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
535 VkImageAspectFlags aspect_mask = 0u;
536
537 // Figure out which aspects are actually touched during resolve operations
538 const char *aspect_string = nullptr;
539 if (resolve_depth && resolve_stencil) {
540 // Validate all aspects together
541 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
542 aspect_string = "depth/stencil";
543 } else if (resolve_depth) {
544 // Validate depth only
545 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
546 aspect_string = "depth";
547 } else if (resolve_stencil) {
548 // Validate all stencil only
549 aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT;
550 aspect_string = "stencil";
551 }
552
553 if (aspect_mask) {
554 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700555 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600556 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700557 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600558 }
559 }
560}
561
562// Action for validating resolve operations
563class ValidateResolveAction {
564 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700565 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
566 const CommandBufferAccessContext &cb_context, const char *func_name)
John Zulauf7635de32020-05-29 17:14:15 -0600567 : render_pass_(render_pass),
568 subpass_(subpass),
569 context_(context),
John Zulauffaea0ee2021-01-14 14:01:32 -0700570 cb_context_(cb_context),
John Zulauf7635de32020-05-29 17:14:15 -0600571 func_name_(func_name),
572 skip_(false) {}
573 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulauf8e3c3e92021-01-06 11:19:36 -0700574 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600575 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
576 HazardResult hazard;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700577 hazard = context_.DetectHazard(view, current_usage, ordering_rule, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600578 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700579 skip_ |=
580 cb_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
581 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
582 " to resolve attachment %" PRIu32 ". Access info %s.",
583 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
584 attachment_name, src_at, dst_at, cb_context_.FormatUsage(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600585 }
586 }
587 // Providing a mechanism for the constructing caller to get the result of the validation
588 bool GetSkip() const { return skip_; }
589
590 private:
591 VkRenderPass render_pass_;
592 const uint32_t subpass_;
593 const AccessContext &context_;
John Zulauffaea0ee2021-01-14 14:01:32 -0700594 const CommandBufferAccessContext &cb_context_;
John Zulauf7635de32020-05-29 17:14:15 -0600595 const char *func_name_;
596 bool skip_;
597};
598
599// Update action for resolve operations
600class UpdateStateResolveAction {
601 public:
602 UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {}
603 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulauf8e3c3e92021-01-06 11:19:36 -0700604 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600605 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
606 // Ignores validation only arguments...
John Zulauf8e3c3e92021-01-06 11:19:36 -0700607 context_.UpdateAccessState(view, current_usage, ordering_rule, offset, extent, aspect_mask, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600608 }
609
610 private:
611 AccessContext &context_;
612 const ResourceUsageTag &tag_;
613};
614
John Zulauf59e25072020-07-17 10:55:21 -0600615void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700616 const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) {
John Zulauf59e25072020-07-17 10:55:21 -0600617 access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_));
618 usage_index = usage_index_;
619 hazard = hazard_;
620 prior_access = prior_;
621 tag = tag_;
622}
623
John Zulauf540266b2020-04-06 18:54:53 -0600624AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
625 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600626 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600627 Reset();
628 const auto &subpass_dep = dependencies[subpass];
629 prev_.reserve(subpass_dep.prev.size());
John Zulauf355e49b2020-04-24 15:11:15 -0600630 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600631 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600632 const auto prev_pass = prev_dep.first->pass;
633 const auto &prev_barriers = prev_dep.second;
634 assert(prev_dep.second.size());
635 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
636 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700637 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600638
639 async_.reserve(subpass_dep.async.size());
640 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700641 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600642 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600643 if (subpass_dep.barrier_from_external.size()) {
644 src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external);
John Zulaufe5da6e52020-03-18 15:32:18 -0600645 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600646 if (subpass_dep.barrier_to_external.size()) {
647 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600648 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700649}
650
John Zulauf5f13a792020-03-10 07:31:21 -0600651template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700652HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600653 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600654 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600655 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600656
657 HazardResult hazard;
658 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
659 hazard = detector.Detect(prev);
660 }
661 return hazard;
662}
663
John Zulauf4a6105a2020-11-17 15:11:05 -0700664template <typename Action>
665void AccessContext::ForAll(Action &&action) {
666 for (const auto address_type : kAddressTypes) {
667 auto &accesses = GetAccessStateMap(address_type);
668 for (const auto &access : accesses) {
669 action(address_type, access);
670 }
671 }
672}
673
John Zulauf3d84f1b2020-03-09 13:33:25 -0600674// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
675// the DAG of the contexts (for example subpasses)
676template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700677HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600678 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600679 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600680
John Zulauf1a224292020-06-30 14:52:13 -0600681 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600682 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
683 // so we'll check these first
684 for (const auto &async_context : async_) {
685 hazard = async_context->DetectAsyncHazard(type, detector, range);
686 if (hazard.hazard) return hazard;
687 }
John Zulauf5f13a792020-03-10 07:31:21 -0600688 }
689
John Zulauf1a224292020-06-30 14:52:13 -0600690 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600691
John Zulauf69133422020-05-20 14:55:53 -0600692 const auto &accesses = GetAccessStateMap(type);
693 const auto from = accesses.lower_bound(range);
694 const auto to = accesses.upper_bound(range);
695 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600696
John Zulauf69133422020-05-20 14:55:53 -0600697 for (auto pos = from; pos != to; ++pos) {
698 // Cover any leading gap, or gap between entries
699 if (detect_prev) {
700 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
701 // Cover any leading gap, or gap between entries
702 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600703 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600704 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600705 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600706 if (hazard.hazard) return hazard;
707 }
John Zulauf69133422020-05-20 14:55:53 -0600708 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
709 gap.begin = pos->first.end;
710 }
711
712 hazard = detector.Detect(pos);
713 if (hazard.hazard) return hazard;
714 }
715
716 if (detect_prev) {
717 // Detect in the trailing empty as needed
718 gap.end = range.end;
719 if (gap.non_empty()) {
720 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600721 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600722 }
723
724 return hazard;
725}
726
727// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
728template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700729HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
730 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600731 auto &accesses = GetAccessStateMap(type);
732 const auto from = accesses.lower_bound(range);
733 const auto to = accesses.upper_bound(range);
734
John Zulauf3d84f1b2020-03-09 13:33:25 -0600735 HazardResult hazard;
John Zulauf16adfc92020-04-08 10:28:33 -0600736 for (auto pos = from; pos != to && !hazard.hazard; ++pos) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700737 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600738 }
John Zulauf16adfc92020-04-08 10:28:33 -0600739
John Zulauf3d84f1b2020-03-09 13:33:25 -0600740 return hazard;
741}
742
John Zulaufb02c1eb2020-10-06 16:33:36 -0600743struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700744 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600745 void operator()(ResourceAccessState *access) const {
746 assert(access);
747 access->ApplyBarriers(barriers, true);
748 }
749 const std::vector<SyncBarrier> &barriers;
750};
751
752struct ApplyTrackbackBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700753 explicit ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600754 void operator()(ResourceAccessState *access) const {
755 assert(access);
756 assert(!access->HasPendingState());
757 access->ApplyBarriers(barriers, false);
758 access->ApplyPendingBarriers(kCurrentCommandTag);
759 }
760 const std::vector<SyncBarrier> &barriers;
761};
762
763// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
764// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
765// *different* map from dest.
766// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
767// range [first, last)
768template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600769static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
770 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600771 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600772 auto at = entry;
773 for (auto pos = first; pos != last; ++pos) {
774 // Every member of the input iterator range must fit within the remaining portion of entry
775 assert(at->first.includes(pos->first));
776 assert(at != dest->end());
777 // Trim up at to the same size as the entry to resolve
778 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600779 auto access = pos->second; // intentional copy
780 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600781 at->second.Resolve(access);
782 ++at; // Go to the remaining unused section of entry
783 }
784}
785
John Zulaufa0a98292020-09-18 09:30:10 -0600786static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
787 SyncBarrier merged = {};
788 for (const auto &barrier : barriers) {
789 merged.Merge(barrier);
790 }
791 return merged;
792}
793
John Zulaufb02c1eb2020-10-06 16:33:36 -0600794template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700795void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600796 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
797 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600798 if (!range.non_empty()) return;
799
John Zulauf355e49b2020-04-24 15:11:15 -0600800 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
801 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600802 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600803 if (current->pos_B->valid) {
804 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600805 auto access = src_pos->second; // intentional copy
806 barrier_action(&access);
807
John Zulauf16adfc92020-04-08 10:28:33 -0600808 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600809 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
810 trimmed->second.Resolve(access);
811 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600812 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600813 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600814 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600815 }
John Zulauf16adfc92020-04-08 10:28:33 -0600816 } else {
817 // we have to descend to fill this gap
818 if (recur_to_infill) {
John Zulauf355e49b2020-04-24 15:11:15 -0600819 if (current->pos_A->valid) {
820 // Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation
821 ResourceAccessRangeMap gap_map;
John Zulauf3bcab5e2020-06-19 14:42:32 -0600822 ResolvePreviousAccess(type, current_range, &gap_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600823 ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -0600824 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600825 // There isn't anything in dest in current)range, so we can accumulate directly into it.
826 ResolvePreviousAccess(type, current_range, resolve_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600827 // Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current
828 for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) {
829 barrier_action(&pos->second);
John Zulauf355e49b2020-04-24 15:11:15 -0600830 }
831 }
832 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
833 // iterator of the outer while.
834
835 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
836 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
837 // we stepped on the dest map
locke-lunarg88dbb542020-06-23 22:05:42 -0600838 const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
839 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -0600840 current.seek(seek_to);
841 } else if (!current->pos_A->valid && infill_state) {
842 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
843 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
844 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -0600845 }
John Zulauf5f13a792020-03-10 07:31:21 -0600846 }
John Zulauf16adfc92020-04-08 10:28:33 -0600847 ++current;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600848 }
John Zulauf1a224292020-06-30 14:52:13 -0600849
850 // Infill if range goes passed both the current and resolve map prior contents
851 if (recur_to_infill && (current->range.end < range.end)) {
852 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
853 ResourceAccessRangeMap gap_map;
854 const auto the_end = resolve_map->end();
855 ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state);
856 for (auto &access : gap_map) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600857 barrier_action(&access.second);
John Zulauf1a224292020-06-30 14:52:13 -0600858 resolve_map->insert(the_end, access);
859 }
860 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600861}
862
John Zulauf43cc7462020-12-03 12:33:12 -0700863void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
864 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufe5da6e52020-03-18 15:32:18 -0600865 if ((prev_.size() == 0) && (src_external_.context == nullptr)) {
John Zulauf5f13a792020-03-10 07:31:21 -0600866 if (range.non_empty() && infill_state) {
867 descent_map->insert(std::make_pair(range, *infill_state));
868 }
869 } else {
870 // Look for something to fill the gap further along.
871 for (const auto &prev_dep : prev_) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600872 const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers);
873 prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600874 }
875
John Zulaufe5da6e52020-03-18 15:32:18 -0600876 if (src_external_.context) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600877 const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers);
878 src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600879 }
880 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600881}
882
John Zulauf4a6105a2020-11-17 15:11:05 -0700883// Non-lazy import of all accesses, WaitEvents needs this.
884void AccessContext::ResolvePreviousAccesses() {
885 ResourceAccessState default_state;
886 for (const auto address_type : kAddressTypes) {
887 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
888 }
889}
890
John Zulauf43cc7462020-12-03 12:33:12 -0700891AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
892 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -0600893}
894
John Zulauf1507ee42020-05-18 11:33:09 -0600895static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
896 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
897 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE;
898 return stage_access;
899}
900static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
901 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
902 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE;
903 return stage_access;
904}
905
John Zulauf7635de32020-05-29 17:14:15 -0600906// Caller must manage returned pointer
907static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
908 uint32_t subpass, const VkRect2D &render_area,
909 std::vector<const IMAGE_VIEW_STATE *> attachment_views) {
910 auto *proxy = new AccessContext(context);
911 proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulaufaff20662020-06-01 14:07:58 -0600912 proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulauf7635de32020-05-29 17:14:15 -0600913 return proxy;
914}
915
John Zulaufb02c1eb2020-10-06 16:33:36 -0600916template <typename BarrierAction>
John Zulauf52446eb2020-10-22 16:40:08 -0600917class ResolveAccessRangeFunctor {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600918 public:
John Zulauf43cc7462020-12-03 12:33:12 -0700919 ResolveAccessRangeFunctor(const AccessContext &context, AccessAddressType address_type, ResourceAccessRangeMap *descent_map,
920 const ResourceAccessState *infill_state, BarrierAction &barrier_action)
John Zulauf52446eb2020-10-22 16:40:08 -0600921 : context_(context),
922 address_type_(address_type),
923 descent_map_(descent_map),
924 infill_state_(infill_state),
925 barrier_action_(barrier_action) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600926 ResolveAccessRangeFunctor() = delete;
927 void operator()(const ResourceAccessRange &range) const {
928 context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_);
929 }
930
931 private:
John Zulauf52446eb2020-10-22 16:40:08 -0600932 const AccessContext &context_;
John Zulauf43cc7462020-12-03 12:33:12 -0700933 const AccessAddressType address_type_;
John Zulauf52446eb2020-10-22 16:40:08 -0600934 ResourceAccessRangeMap *const descent_map_;
935 const ResourceAccessState *infill_state_;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600936 BarrierAction &barrier_action_;
937};
938
John Zulaufb02c1eb2020-10-06 16:33:36 -0600939template <typename BarrierAction>
940void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -0700941 BarrierAction &barrier_action, AccessAddressType address_type,
942 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600943 const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action);
944 ApplyOverImageRange(image_state, subresource_range, action);
John Zulauf62f10592020-04-03 12:20:02 -0600945}
946
John Zulauf7635de32020-05-29 17:14:15 -0600947// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulauffaea0ee2021-01-14 14:01:32 -0700948bool AccessContext::ValidateLayoutTransitions(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600949 const VkRect2D &render_area, uint32_t subpass,
950 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
951 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -0600952 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -0600953 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
954 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
955 // those affects have not been recorded yet.
956 //
957 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
958 // to apply and only copy then, if this proves a hot spot.
959 std::unique_ptr<AccessContext> proxy_for_prev;
960 TrackBack proxy_track_back;
961
John Zulauf355e49b2020-04-24 15:11:15 -0600962 const auto &transitions = rp_state.subpass_transitions[subpass];
963 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -0600964 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
965
966 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
967 if (prev_needs_proxy) {
968 if (!proxy_for_prev) {
969 proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass,
970 render_area, attachment_views));
971 proxy_track_back = *track_back;
972 proxy_track_back.context = proxy_for_prev.get();
973 }
974 track_back = &proxy_track_back;
975 }
976 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -0600977 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700978 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
979 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
980 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
981 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
982 string_VkImageLayout(transition.old_layout),
983 string_VkImageLayout(transition.new_layout),
984 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -0600985 }
986 }
987 return skip;
988}
989
John Zulauffaea0ee2021-01-14 14:01:32 -0700990bool AccessContext::ValidateLoadOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600991 const VkRect2D &render_area, uint32_t subpass,
992 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
993 const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -0600994 bool skip = false;
995 const auto *attachment_ci = rp_state.createInfo.pAttachments;
996 VkExtent3D extent = CastTo3D(render_area.extent);
997 VkOffset3D offset = CastTo3D(render_area.offset);
John Zulaufa0a98292020-09-18 09:30:10 -0600998
John Zulauf1507ee42020-05-18 11:33:09 -0600999 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1000 if (subpass == rp_state.attachment_first_subpass[i]) {
1001 if (attachment_views[i] == nullptr) continue;
1002 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1003 const IMAGE_STATE *image = view.image_state.get();
1004 if (image == nullptr) continue;
1005 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001006
1007 // Need check in the following way
1008 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1009 // vs. transition
1010 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1011 // for each aspect loaded.
1012
1013 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001014 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001015 const bool is_color = !(has_depth || has_stencil);
1016
1017 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001018 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001019
John Zulaufaff20662020-06-01 14:07:58 -06001020 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001021 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001022
John Zulaufb02c1eb2020-10-06 16:33:36 -06001023 auto hazard_range = view.normalized_subresource_range;
1024 bool checked_stencil = false;
1025 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001026 hazard = DetectHazard(*image, load_index, view.normalized_subresource_range, SyncOrdering::kColorAttachment, offset,
John Zulauf859089b2020-10-29 17:37:03 -06001027 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001028 aspect = "color";
1029 } else {
1030 if (has_depth) {
1031 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001032 hazard = DetectHazard(*image, load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset, extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001033 aspect = "depth";
1034 }
1035 if (!hazard.hazard && has_stencil) {
1036 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001037 hazard = DetectHazard(*image, stencil_load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset,
1038 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001039 aspect = "stencil";
1040 checked_stencil = true;
1041 }
1042 }
1043
1044 if (hazard.hazard) {
1045 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001046 const auto &sync_state = cb_context.GetSyncState();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001047 if (hazard.tag == kCurrentCommandTag) {
1048 // Hazard vs. ILT
1049 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1050 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1051 " aspect %s during load with loadOp %s.",
1052 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1053 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06001054 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1055 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001056 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001057 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauffaea0ee2021-01-14 14:01:32 -07001058 cb_context.FormatUsage(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001059 }
1060 }
1061 }
1062 }
1063 return skip;
1064}
1065
John Zulaufaff20662020-06-01 14:07:58 -06001066// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1067// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1068// store is part of the same Next/End operation.
1069// The latter is handled in layout transistion validation directly
John Zulauffaea0ee2021-01-14 14:01:32 -07001070bool AccessContext::ValidateStoreOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001071 const VkRect2D &render_area, uint32_t subpass,
1072 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1073 const char *func_name) const {
1074 bool skip = false;
1075 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1076 VkExtent3D extent = CastTo3D(render_area.extent);
1077 VkOffset3D offset = CastTo3D(render_area.offset);
1078
1079 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1080 if (subpass == rp_state.attachment_last_subpass[i]) {
1081 if (attachment_views[i] == nullptr) continue;
1082 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1083 const IMAGE_STATE *image = view.image_state.get();
1084 if (image == nullptr) continue;
1085 const auto &ci = attachment_ci[i];
1086
1087 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1088 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1089 // sake, we treat DONT_CARE as writing.
1090 const bool has_depth = FormatHasDepth(ci.format);
1091 const bool has_stencil = FormatHasStencil(ci.format);
1092 const bool is_color = !(has_depth || has_stencil);
1093 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1094 if (!has_stencil && !store_op_stores) continue;
1095
1096 HazardResult hazard;
1097 const char *aspect = nullptr;
1098 bool checked_stencil = false;
1099 if (is_color) {
1100 hazard = DetectHazard(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001101 view.normalized_subresource_range, SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001102 aspect = "color";
1103 } else {
1104 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1105 auto hazard_range = view.normalized_subresource_range;
1106 if (has_depth && store_op_stores) {
1107 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1108 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001109 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001110 aspect = "depth";
1111 }
1112 if (!hazard.hazard && has_stencil && stencil_op_stores) {
1113 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1114 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001115 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001116 aspect = "stencil";
1117 checked_stencil = true;
1118 }
1119 }
1120
1121 if (hazard.hazard) {
1122 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1123 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001124 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1125 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1126 " %s aspect during store with %s %s. Access info %s",
1127 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect,
1128 op_type_string, store_op_string, cb_context.FormatUsage(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001129 }
1130 }
1131 }
1132 return skip;
1133}
1134
John Zulauffaea0ee2021-01-14 14:01:32 -07001135bool AccessContext::ValidateResolveOperations(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufb027cdb2020-05-21 14:25:22 -06001136 const VkRect2D &render_area,
1137 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name,
1138 uint32_t subpass) const {
John Zulauffaea0ee2021-01-14 14:01:32 -07001139 ValidateResolveAction validate_action(rp_state.renderPass, subpass, *this, cb_context, func_name);
John Zulauf7635de32020-05-29 17:14:15 -06001140 ResolveOperation(validate_action, rp_state, render_area, attachment_views, subpass);
1141 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001142}
1143
John Zulauf3d84f1b2020-03-09 13:33:25 -06001144class HazardDetector {
1145 SyncStageAccessIndex usage_index_;
1146
1147 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001148 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001149 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1150 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001151 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001152 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001153};
1154
John Zulauf69133422020-05-20 14:55:53 -06001155class HazardDetectorWithOrdering {
1156 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001157 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001158
1159 public:
1160 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001161 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001162 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001163 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1164 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001165 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001166 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001167};
1168
John Zulauf16adfc92020-04-08 10:28:33 -06001169HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001170 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001171 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001172 const auto base_address = ResourceBaseAddress(buffer);
1173 HazardDetector detector(usage_index);
1174 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001175}
1176
John Zulauf69133422020-05-20 14:55:53 -06001177template <typename Detector>
1178HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1179 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1180 const VkExtent3D &extent, DetectOptions options) const {
1181 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001182 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001183 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1184 base_address);
1185 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001186 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001187 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001188 if (hazard.hazard) return hazard;
1189 }
1190 return HazardResult();
1191}
1192
John Zulauf540266b2020-04-06 18:54:53 -06001193HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1194 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1195 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001196 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1197 subresource.layerCount};
John Zulauf1507ee42020-05-18 11:33:09 -06001198 return DetectHazard(image, current_usage, subresource_range, offset, extent);
1199}
1200
1201HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1202 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1203 const VkExtent3D &extent) const {
John Zulauf69133422020-05-20 14:55:53 -06001204 HazardDetector detector(current_usage);
1205 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
1206}
1207
1208HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001209 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
John Zulauf69133422020-05-20 14:55:53 -06001210 const VkOffset3D &offset, const VkExtent3D &extent) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001211 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06001212 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001213}
1214
John Zulaufb027cdb2020-05-21 14:25:22 -06001215// Some common code for looking at attachments, if there's anything wrong, we return no hazard, core validation
1216// should have reported the issue regarding an invalid attachment entry
1217HazardResult AccessContext::DetectHazard(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001218 SyncOrdering ordering_rule, const VkOffset3D &offset, const VkExtent3D &extent,
John Zulaufb027cdb2020-05-21 14:25:22 -06001219 VkImageAspectFlags aspect_mask) const {
1220 if (view != nullptr) {
1221 const IMAGE_STATE *image = view->image_state.get();
1222 if (image != nullptr) {
1223 auto *detect_range = &view->normalized_subresource_range;
1224 VkImageSubresourceRange masked_range;
1225 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1226 masked_range = view->normalized_subresource_range;
1227 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1228 detect_range = &masked_range;
1229 }
1230
1231 // NOTE: The range encoding code is not robust to invalid ranges, so we protect it from our change
1232 if (detect_range->aspectMask) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001233 return DetectHazard(*image, current_usage, *detect_range, ordering_rule, offset, extent);
John Zulaufb027cdb2020-05-21 14:25:22 -06001234 }
1235 }
1236 }
1237 return HazardResult();
1238}
John Zulauf43cc7462020-12-03 12:33:12 -07001239
John Zulauf3d84f1b2020-03-09 13:33:25 -06001240class BarrierHazardDetector {
1241 public:
1242 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1243 SyncStageAccessFlags src_access_scope)
1244 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1245
John Zulauf5f13a792020-03-10 07:31:21 -06001246 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1247 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001248 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001249 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001250 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001251 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001252 }
1253
1254 private:
1255 SyncStageAccessIndex usage_index_;
1256 VkPipelineStageFlags src_exec_scope_;
1257 SyncStageAccessFlags src_access_scope_;
1258};
1259
John Zulauf4a6105a2020-11-17 15:11:05 -07001260class EventBarrierHazardDetector {
1261 public:
1262 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1263 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
1264 const ResourceUsageTag &scope_tag)
1265 : usage_index_(usage_index),
1266 src_exec_scope_(src_exec_scope),
1267 src_access_scope_(src_access_scope),
1268 event_scope_(event_scope),
1269 scope_pos_(event_scope.cbegin()),
1270 scope_end_(event_scope.cend()),
1271 scope_tag_(scope_tag) {}
1272
1273 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1274 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1275 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1276 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1277 if (scope_pos_ == scope_end_) return HazardResult();
1278 if (!scope_pos_->first.intersects(pos->first)) {
1279 event_scope_.lower_bound(pos->first);
1280 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1281 }
1282
1283 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1284 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1285 }
1286 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1287 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1288 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1289 }
1290
1291 private:
1292 SyncStageAccessIndex usage_index_;
1293 VkPipelineStageFlags src_exec_scope_;
1294 SyncStageAccessFlags src_access_scope_;
1295 const SyncEventState::ScopeMap &event_scope_;
1296 SyncEventState::ScopeMap::const_iterator scope_pos_;
1297 SyncEventState::ScopeMap::const_iterator scope_end_;
1298 const ResourceUsageTag &scope_tag_;
1299};
1300
1301HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
1302 const SyncStageAccessFlags &src_access_scope,
1303 const VkImageSubresourceRange &subresource_range,
1304 const SyncEventState &sync_event, DetectOptions options) const {
1305 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1306 // first access scope map to use, and there's no easy way to plumb it in below.
1307 const auto address_type = ImageAddressType(image);
1308 const auto &event_scope = sync_event.FirstScope(address_type);
1309
1310 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1311 event_scope, sync_event.first_scope_tag);
1312 VkOffset3D zero_offset = {0, 0, 0};
1313 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
1314}
1315
John Zulauf16adfc92020-04-08 10:28:33 -06001316HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001317 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001318 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001319 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001320 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
1321 VkOffset3D zero_offset = {0, 0, 0};
1322 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001323}
1324
John Zulauf355e49b2020-04-24 15:11:15 -06001325HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001326 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001327 const VkImageMemoryBarrier &barrier) const {
1328 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1329 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1330 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1331}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001332HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
1333 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope,
John Zulaufd5115702021-01-18 12:34:33 -07001334 image_barrier.barrier.src_access_scope, image_barrier.range.subresource_range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001335}
John Zulauf355e49b2020-04-24 15:11:15 -06001336
John Zulauf9cb530d2019-09-30 14:14:10 -06001337template <typename Flags, typename Map>
1338SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1339 SyncStageAccessFlags scope = 0;
1340 for (const auto &bit_scope : map) {
1341 if (flag_mask < bit_scope.first) break;
1342
1343 if (flag_mask & bit_scope.first) {
1344 scope |= bit_scope.second;
1345 }
1346 }
1347 return scope;
1348}
1349
1350SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags stages) {
1351 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1352}
1353
1354SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags accesses) {
1355 return AccessScopeImpl(accesses, syncStageAccessMaskByAccessBit);
1356}
1357
1358// Getting from stage mask and access mask to stage/acess masks is something we need to be good at...
1359SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags stages, VkAccessFlags accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001360 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1361 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1362 // of the union of all stage/access types for all the stages and the same unions for the access mask...
John Zulauf9cb530d2019-09-30 14:14:10 -06001363 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1364}
1365
1366template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001367void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001368 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1369 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001370 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001371 auto pos = accesses->lower_bound(range);
1372 if (pos == accesses->end() || !pos->first.intersects(range)) {
1373 // The range is empty, fill it with a default value.
1374 pos = action.Infill(accesses, pos, range);
1375 } else if (range.begin < pos->first.begin) {
1376 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001377 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001378 } else if (pos->first.begin < range.begin) {
1379 // Trim the beginning if needed
1380 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1381 ++pos;
1382 }
1383
1384 const auto the_end = accesses->end();
1385 while ((pos != the_end) && pos->first.intersects(range)) {
1386 if (pos->first.end > range.end) {
1387 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1388 }
1389
1390 pos = action(accesses, pos);
1391 if (pos == the_end) break;
1392
1393 auto next = pos;
1394 ++next;
1395 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1396 // Need to infill if next is disjoint
1397 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001398 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001399 next = action.Infill(accesses, next, new_range);
1400 }
1401 pos = next;
1402 }
1403}
John Zulaufd5115702021-01-18 12:34:33 -07001404
1405// Give a comparable interface for range generators and ranges
1406template <typename Action>
1407inline void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
1408 assert(range);
1409 UpdateMemoryAccessState(accesses, *range, action);
1410}
1411
John Zulauf4a6105a2020-11-17 15:11:05 -07001412template <typename Action, typename RangeGen>
1413void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1414 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001415 RangeGen &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
John Zulauf4a6105a2020-11-17 15:11:05 -07001416 for (; range_gen->non_empty(); ++range_gen) {
1417 UpdateMemoryAccessState(accesses, *range_gen, action);
1418 }
1419}
John Zulauf9cb530d2019-09-30 14:14:10 -06001420
1421struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001422 using Iterator = ResourceAccessRangeMap::iterator;
1423 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001424 // this is only called on gaps, and never returns a gap.
1425 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001426 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001427 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001428 }
John Zulauf5f13a792020-03-10 07:31:21 -06001429
John Zulauf5c5e88d2019-12-26 11:22:02 -07001430 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001431 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001432 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001433 return pos;
1434 }
1435
John Zulauf43cc7462020-12-03 12:33:12 -07001436 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001437 SyncOrdering ordering_rule_, const ResourceUsageTag &tag_)
1438 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001439 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001440 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001441 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001442 const SyncOrdering ordering_rule;
John Zulauf9cb530d2019-09-30 14:14:10 -06001443 const ResourceUsageTag &tag;
1444};
1445
John Zulauf4a6105a2020-11-17 15:11:05 -07001446// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001447struct PipelineBarrierOp {
1448 SyncBarrier barrier;
1449 bool layout_transition;
1450 PipelineBarrierOp(const SyncBarrier &barrier_, bool layout_transition_)
1451 : barrier(barrier_), layout_transition(layout_transition_) {}
1452 PipelineBarrierOp() = default;
John Zulaufd5115702021-01-18 12:34:33 -07001453 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf1e331ec2020-12-04 18:29:38 -07001454 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(barrier, layout_transition); }
1455};
John Zulauf4a6105a2020-11-17 15:11:05 -07001456// The barrier operation for wait events
1457struct WaitEventBarrierOp {
1458 const ResourceUsageTag *scope_tag;
1459 SyncBarrier barrier;
1460 bool layout_transition;
1461 WaitEventBarrierOp(const ResourceUsageTag &scope_tag_, const SyncBarrier &barrier_, bool layout_transition_)
1462 : scope_tag(&scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1463 WaitEventBarrierOp() = default;
1464 void operator()(ResourceAccessState *access_state) const {
1465 assert(scope_tag); // Not valid to have a non-scope op executed, default construct included for std::vector support
1466 access_state->ApplyBarrier(*scope_tag, barrier, layout_transition);
1467 }
1468};
John Zulauf1e331ec2020-12-04 18:29:38 -07001469
John Zulauf4a6105a2020-11-17 15:11:05 -07001470// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1471// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1472// of a collection is known/present.
John Zulauf1e331ec2020-12-04 18:29:38 -07001473template <typename BarrierOp>
John Zulauf89311b42020-09-29 16:28:47 -06001474class ApplyBarrierOpsFunctor {
1475 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001476 using Iterator = ResourceAccessRangeMap::iterator;
1477 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
John Zulauf9cb530d2019-09-30 14:14:10 -06001478
John Zulauf5c5e88d2019-12-26 11:22:02 -07001479 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001480 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001481 for (const auto &op : barrier_ops_) {
1482 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001483 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001484
John Zulauf89311b42020-09-29 16:28:47 -06001485 if (resolve_) {
1486 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1487 // another walk
1488 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001489 }
1490 return pos;
1491 }
1492
John Zulauf89311b42020-09-29 16:28:47 -06001493 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulaufd5115702021-01-18 12:34:33 -07001494 ApplyBarrierOpsFunctor(bool resolve, size_t size_hint, const ResourceUsageTag &tag)
1495 : resolve_(resolve), barrier_ops_(), tag_(tag) {
1496 barrier_ops_.reserve(size_hint);
1497 }
1498 void EmplaceBack(const BarrierOp &op) { barrier_ops_.emplace_back(op); }
John Zulauf89311b42020-09-29 16:28:47 -06001499
1500 private:
1501 bool resolve_;
John Zulaufd5115702021-01-18 12:34:33 -07001502 std::vector<BarrierOp> barrier_ops_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001503 const ResourceUsageTag &tag_;
1504};
1505
John Zulauf4a6105a2020-11-17 15:11:05 -07001506// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1507// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1508template <typename BarrierOp>
1509class ApplyBarrierFunctor {
1510 public:
1511 using Iterator = ResourceAccessRangeMap::iterator;
1512 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1513
1514 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1515 auto &access_state = pos->second;
1516 barrier_op_(&access_state);
1517 return pos;
1518 }
1519
1520 ApplyBarrierFunctor(const BarrierOp &barrier_op) : barrier_op_(barrier_op) {}
1521
1522 private:
John Zulaufd5115702021-01-18 12:34:33 -07001523 BarrierOp barrier_op_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001524};
1525
John Zulauf1e331ec2020-12-04 18:29:38 -07001526// This functor resolves the pendinging state.
1527class ResolvePendingBarrierFunctor {
1528 public:
1529 using Iterator = ResourceAccessRangeMap::iterator;
1530 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1531
1532 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1533 auto &access_state = pos->second;
1534 access_state.ApplyPendingBarriers(tag_);
1535 return pos;
1536 }
1537
1538 ResolvePendingBarrierFunctor(const ResourceUsageTag &tag) : tag_(tag) {}
1539
1540 private:
John Zulauf89311b42020-09-29 16:28:47 -06001541 const ResourceUsageTag &tag_;
John Zulauf9cb530d2019-09-30 14:14:10 -06001542};
1543
John Zulauf8e3c3e92021-01-06 11:19:36 -07001544void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1545 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
1546 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001547 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001548}
1549
John Zulauf8e3c3e92021-01-06 11:19:36 -07001550void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001551 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001552 if (!SimpleBinding(buffer)) return;
1553 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001554 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001555}
John Zulauf355e49b2020-04-24 15:11:15 -06001556
John Zulauf8e3c3e92021-01-06 11:19:36 -07001557void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001558 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf540266b2020-04-06 18:54:53 -06001559 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001560 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001561 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001562 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1563 base_address);
1564 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001565 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf5f13a792020-03-10 07:31:21 -06001566 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001567 UpdateMemoryAccessState(&GetAccessStateMap(address_type), *range_gen, action);
John Zulauf5f13a792020-03-10 07:31:21 -06001568 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001569}
John Zulauf8e3c3e92021-01-06 11:19:36 -07001570void AccessContext::UpdateAccessState(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1571 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask,
1572 const ResourceUsageTag &tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001573 if (view != nullptr) {
1574 const IMAGE_STATE *image = view->image_state.get();
1575 if (image != nullptr) {
1576 auto *update_range = &view->normalized_subresource_range;
1577 VkImageSubresourceRange masked_range;
1578 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1579 masked_range = view->normalized_subresource_range;
1580 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1581 update_range = &masked_range;
1582 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001583 UpdateAccessState(*image, current_usage, ordering_rule, *update_range, offset, extent, tag);
John Zulauf7635de32020-05-29 17:14:15 -06001584 }
1585 }
1586}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001587
John Zulauf8e3c3e92021-01-06 11:19:36 -07001588void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001589 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1590 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001591 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1592 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001593 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001594}
1595
John Zulauf540266b2020-04-06 18:54:53 -06001596template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001597void AccessContext::UpdateResourceAccess(const BUFFER_STATE &buffer, const ResourceAccessRange &range, const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001598 if (!SimpleBinding(buffer)) return;
1599 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf43cc7462020-12-03 12:33:12 -07001600 UpdateMemoryAccessState(&GetAccessStateMap(AccessAddressType::kLinear), (range + base_address), action);
John Zulauf540266b2020-04-06 18:54:53 -06001601}
1602
1603template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001604void AccessContext::UpdateResourceAccess(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1605 const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001606 if (!SimpleBinding(image)) return;
1607 const auto address_type = ImageAddressType(image);
1608 auto *accesses = &GetAccessStateMap(address_type);
John Zulauf540266b2020-04-06 18:54:53 -06001609
John Zulauf16adfc92020-04-08 10:28:33 -06001610 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001611 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, {0, 0, 0},
1612 image.createInfo.extent, base_address);
1613
John Zulauf540266b2020-04-06 18:54:53 -06001614 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001615 UpdateMemoryAccessState(accesses, *range_gen, action);
John Zulauf540266b2020-04-06 18:54:53 -06001616 }
1617}
1618
John Zulauf7635de32020-05-29 17:14:15 -06001619void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1620 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1621 const ResourceUsageTag &tag) {
1622 UpdateStateResolveAction update(*this, tag);
1623 ResolveOperation(update, rp_state, render_area, attachment_views, subpass);
1624}
1625
John Zulaufaff20662020-06-01 14:07:58 -06001626void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1627 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1628 const ResourceUsageTag &tag) {
1629 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1630 VkExtent3D extent = CastTo3D(render_area.extent);
1631 VkOffset3D offset = CastTo3D(render_area.offset);
1632
1633 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1634 if (rp_state.attachment_last_subpass[i] == subpass) {
1635 if (attachment_views[i] == nullptr) continue; // UNUSED
1636 const auto &view = *attachment_views[i];
1637 const IMAGE_STATE *image = view.image_state.get();
1638 if (image == nullptr) continue;
1639
1640 const auto &ci = attachment_ci[i];
1641 const bool has_depth = FormatHasDepth(ci.format);
1642 const bool has_stencil = FormatHasStencil(ci.format);
1643 const bool is_color = !(has_depth || has_stencil);
1644 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1645
1646 if (is_color && store_op_stores) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001647 UpdateAccessState(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1648 view.normalized_subresource_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001649 } else {
1650 auto update_range = view.normalized_subresource_range;
1651 if (has_depth && store_op_stores) {
1652 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001653 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1654 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001655 }
1656 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1657 if (has_stencil && stencil_op_stores) {
1658 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001659 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1660 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001661 }
1662 }
1663 }
1664 }
1665}
1666
John Zulauf540266b2020-04-06 18:54:53 -06001667template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001668void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001669 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001670 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001671 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001672 }
1673}
1674
1675void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001676 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1677 auto &context = contexts[subpass_index];
John Zulaufb02c1eb2020-10-06 16:33:36 -06001678 ApplyTrackbackBarriersAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001679 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001680 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001681 }
1682 }
1683}
1684
John Zulauf355e49b2020-04-24 15:11:15 -06001685// Suitable only for *subpass* access contexts
John Zulauf7635de32020-05-29 17:14:15 -06001686HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const IMAGE_VIEW_STATE *attach_view) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001687 if (!attach_view) return HazardResult();
1688 const auto image_state = attach_view->image_state.get();
1689 if (!image_state) return HazardResult();
1690
John Zulauf355e49b2020-04-24 15:11:15 -06001691 // We should never ask for a transition from a context we don't have
John Zulauf7635de32020-05-29 17:14:15 -06001692 assert(track_back.context);
John Zulauf355e49b2020-04-24 15:11:15 -06001693
1694 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001695 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1696 const auto merged_barrier = MergeBarriers(track_back.barriers);
1697 HazardResult hazard =
1698 track_back.context->DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
1699 attach_view->normalized_subresource_range, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001700 if (!hazard.hazard) {
1701 // The Async hazard check is against the current context's async set.
John Zulaufa0a98292020-09-18 09:30:10 -06001702 hazard = DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001703 attach_view->normalized_subresource_range, kDetectAsync);
1704 }
John Zulaufa0a98292020-09-18 09:30:10 -06001705
John Zulauf355e49b2020-04-24 15:11:15 -06001706 return hazard;
1707}
1708
John Zulaufb02c1eb2020-10-06 16:33:36 -06001709void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
1710 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1711 const ResourceUsageTag &tag) {
1712 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001713 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001714 for (const auto &transition : transitions) {
1715 const auto prev_pass = transition.prev_pass;
1716 const auto attachment_view = attachment_views[transition.attachment];
1717 if (!attachment_view) continue;
1718 const auto *image = attachment_view->image_state.get();
1719 if (!image) continue;
1720 if (!SimpleBinding(*image)) continue;
1721
1722 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1723 assert(trackback);
1724
1725 // Import the attachments into the current context
1726 const auto *prev_context = trackback->context;
1727 assert(prev_context);
1728 const auto address_type = ImageAddressType(*image);
1729 auto &target_map = GetAccessStateMap(address_type);
1730 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
1731 prev_context->ResolveAccessRange(*image, attachment_view->normalized_subresource_range, barrier_action, address_type,
John Zulauf646cc292020-10-23 09:16:45 -06001732 &target_map, &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001733 }
1734
John Zulauf86356ca2020-10-19 11:46:41 -06001735 // If there were no transitions skip this global map walk
1736 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001737 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001738 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001739 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001740}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001741
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001742void CommandBufferAccessContext::ApplyGlobalBarriersToEvents(const SyncExecScope &src, const SyncExecScope &dst) {
1743 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
John Zulauf669dfd52021-01-27 17:15:28 -07001744
1745 auto *events_context = GetCurrentEventsContext();
1746 assert(events_context);
1747 for (auto &event_pair : *events_context) {
John Zulauf4a6105a2020-11-17 15:11:05 -07001748 assert(event_pair.second); // Shouldn't be storing empty
1749 auto &sync_event = *event_pair.second;
1750 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001751 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
1752 sync_event.barriers |= dst.exec_scope;
1753 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
John Zulauf4a6105a2020-11-17 15:11:05 -07001754 }
1755 }
1756}
1757
John Zulauf355e49b2020-04-24 15:11:15 -06001758// Class CommandBufferAccessContext: Keep track of resource access state information for a specific command buffer
1759bool CommandBufferAccessContext::ValidateBeginRenderPass(const RENDER_PASS_STATE &rp_state,
1760
1761 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001762 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001763 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
1764 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06001765
John Zulauf86356ca2020-10-19 11:46:41 -06001766 assert(pRenderPassBegin);
1767 if (nullptr == pRenderPassBegin) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06001768
John Zulauf86356ca2020-10-19 11:46:41 -06001769 const uint32_t subpass = 0;
John Zulauf355e49b2020-04-24 15:11:15 -06001770
John Zulauf86356ca2020-10-19 11:46:41 -06001771 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
1772 // hasn't happened yet)
1773 const std::vector<AccessContext> empty_context_vector;
1774 AccessContext temp_context(subpass, queue_flags_, rp_state.subpass_dependencies, empty_context_vector,
1775 const_cast<AccessContext *>(&cb_access_context_));
John Zulauf355e49b2020-04-24 15:11:15 -06001776
John Zulauf86356ca2020-10-19 11:46:41 -06001777 // Create a view list
1778 const auto fb_state = sync_state_->Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
1779 assert(fb_state);
1780 if (nullptr == fb_state) return skip;
1781 // NOTE: Must not use COMMAND_BUFFER_STATE variant of this as RecordCmdBeginRenderPass hasn't run and thus
1782 // the activeRenderPass.* fields haven't been set.
1783 const auto views = sync_state_->GetAttachmentViews(*pRenderPassBegin, *fb_state);
1784
1785 // Validate transitions
John Zulauffaea0ee2021-01-14 14:01:32 -07001786 skip |= temp_context.ValidateLayoutTransitions(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf86356ca2020-10-19 11:46:41 -06001787
1788 // Validate load operations if there were no layout transition hazards
1789 if (!skip) {
1790 temp_context.RecordLayoutTransitions(rp_state, subpass, views, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07001791 skip |= temp_context.ValidateLoadOperation(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06001792 }
John Zulauf86356ca2020-10-19 11:46:41 -06001793
John Zulauf355e49b2020-04-24 15:11:15 -06001794 return skip;
1795}
1796
locke-lunarg61870c22020-06-09 14:51:50 -06001797bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1798 const char *func_name) const {
1799 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001800 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001801 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001802 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1803 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001804 return skip;
1805 }
1806
1807 using DescriptorClass = cvdescriptorset::DescriptorClass;
1808 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1809 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1810 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1811 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1812
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001813 for (const auto &stage_state : pipe->stage_state) {
1814 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1815 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001816 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001817 }
locke-lunarg61870c22020-06-09 14:51:50 -06001818 for (const auto &set_binding : stage_state.descriptor_uses) {
1819 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1820 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1821 set_binding.first.second);
1822 const auto descriptor_type = binding_it.GetType();
1823 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1824 auto array_idx = 0;
1825
1826 if (binding_it.IsVariableDescriptorCount()) {
1827 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1828 }
1829 SyncStageAccessIndex sync_index =
1830 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1831
1832 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1833 uint32_t index = i - index_range.start;
1834 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1835 switch (descriptor->GetClass()) {
1836 case DescriptorClass::ImageSampler:
1837 case DescriptorClass::Image: {
1838 const IMAGE_VIEW_STATE *img_view_state = nullptr;
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001839 VkImageLayout image_layout;
locke-lunarg61870c22020-06-09 14:51:50 -06001840 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001841 const auto image_sampler_descriptor = static_cast<const ImageSamplerDescriptor *>(descriptor);
1842 img_view_state = image_sampler_descriptor->GetImageViewState();
1843 image_layout = image_sampler_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001844 } else {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001845 const auto image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1846 img_view_state = image_descriptor->GetImageViewState();
1847 image_layout = image_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001848 }
1849 if (!img_view_state) continue;
1850 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1851 VkExtent3D extent = {};
1852 VkOffset3D offset = {};
1853 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1854 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1855 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1856 } else {
1857 extent = img_state->createInfo.extent;
1858 }
John Zulauf361fb532020-07-22 10:45:39 -06001859 HazardResult hazard;
1860 const auto &subresource_range = img_view_state->normalized_subresource_range;
1861 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
1862 // Input attachments are subject to raster ordering rules
1863 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001864 SyncOrdering::kRaster, offset, extent);
John Zulauf361fb532020-07-22 10:45:39 -06001865 } else {
1866 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, offset, extent);
1867 }
John Zulauf33fc1d52020-07-17 11:01:10 -06001868 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001869 skip |= sync_state_->LogError(
1870 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001871 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1872 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001873 func_name, string_SyncHazard(hazard.hazard),
1874 sync_state_->report_data->FormatHandle(img_view_state->image_view).c_str(),
1875 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001876 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001877 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1878 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauffaea0ee2021-01-14 14:01:32 -07001879 set_binding.first.second, index, FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001880 }
1881 break;
1882 }
1883 case DescriptorClass::TexelBuffer: {
1884 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1885 if (!buf_view_state) continue;
1886 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06001887 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06001888 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06001889 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001890 skip |= sync_state_->LogError(
1891 buf_view_state->buffer_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001892 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1893 func_name, string_SyncHazard(hazard.hazard),
locke-lunarg88dbb542020-06-23 22:05:42 -06001894 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view).c_str(),
1895 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001896 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001897 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1898 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001899 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001900 }
1901 break;
1902 }
1903 case DescriptorClass::GeneralBuffer: {
1904 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
1905 auto buf_state = buffer_descriptor->GetBufferState();
1906 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06001907 const ResourceAccessRange range =
1908 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06001909 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06001910 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001911 skip |= sync_state_->LogError(
1912 buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001913 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1914 func_name, string_SyncHazard(hazard.hazard),
1915 sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
locke-lunarg88dbb542020-06-23 22:05:42 -06001916 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001917 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001918 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1919 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001920 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001921 }
1922 break;
1923 }
1924 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
1925 default:
1926 break;
1927 }
1928 }
1929 }
1930 }
1931 return skip;
1932}
1933
1934void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1935 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001936 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001937 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001938 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1939 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001940 return;
1941 }
1942
1943 using DescriptorClass = cvdescriptorset::DescriptorClass;
1944 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1945 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1946 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1947 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1948
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001949 for (const auto &stage_state : pipe->stage_state) {
1950 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1951 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001952 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001953 }
locke-lunarg61870c22020-06-09 14:51:50 -06001954 for (const auto &set_binding : stage_state.descriptor_uses) {
1955 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1956 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1957 set_binding.first.second);
1958 const auto descriptor_type = binding_it.GetType();
1959 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1960 auto array_idx = 0;
1961
1962 if (binding_it.IsVariableDescriptorCount()) {
1963 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1964 }
1965 SyncStageAccessIndex sync_index =
1966 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1967
1968 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1969 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1970 switch (descriptor->GetClass()) {
1971 case DescriptorClass::ImageSampler:
1972 case DescriptorClass::Image: {
1973 const IMAGE_VIEW_STATE *img_view_state = nullptr;
1974 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
1975 img_view_state = static_cast<const ImageSamplerDescriptor *>(descriptor)->GetImageViewState();
1976 } else {
1977 img_view_state = static_cast<const ImageDescriptor *>(descriptor)->GetImageViewState();
1978 }
1979 if (!img_view_state) continue;
1980 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1981 VkExtent3D extent = {};
1982 VkOffset3D offset = {};
1983 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1984 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1985 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1986 } else {
1987 extent = img_state->createInfo.extent;
1988 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001989 SyncOrdering ordering_rule = (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)
1990 ? SyncOrdering::kRaster
1991 : SyncOrdering::kNonAttachment;
1992 current_context_->UpdateAccessState(*img_state, sync_index, ordering_rule,
1993 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06001994 break;
1995 }
1996 case DescriptorClass::TexelBuffer: {
1997 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1998 if (!buf_view_state) continue;
1999 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002000 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002001 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002002 break;
2003 }
2004 case DescriptorClass::GeneralBuffer: {
2005 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
2006 auto buf_state = buffer_descriptor->GetBufferState();
2007 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06002008 const ResourceAccessRange range =
2009 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002010 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002011 break;
2012 }
2013 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2014 default:
2015 break;
2016 }
2017 }
2018 }
2019 }
2020}
2021
2022bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2023 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002024 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2025 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002026 return skip;
2027 }
2028
2029 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2030 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002031 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002032
2033 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002034 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002035 if (binding_description.binding < binding_buffers_size) {
2036 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002037 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002038
locke-lunarg1ae57d62020-11-18 10:49:19 -07002039 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002040 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2041 vertexCount, binding_description.stride);
locke-lunarg61870c22020-06-09 14:51:50 -06002042 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range);
2043 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002044 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002045 buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002046 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002047 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002048 }
2049 }
2050 }
2051 return skip;
2052}
2053
2054void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002055 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2056 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002057 return;
2058 }
2059 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2060 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002061 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002062
2063 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002064 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002065 if (binding_description.binding < binding_buffers_size) {
2066 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002067 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002068
locke-lunarg1ae57d62020-11-18 10:49:19 -07002069 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002070 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2071 vertexCount, binding_description.stride);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002072 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, SyncOrdering::kNonAttachment,
2073 range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002074 }
2075 }
2076}
2077
2078bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2079 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002080 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->destroyed) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002081 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002082 }
locke-lunarg61870c22020-06-09 14:51:50 -06002083
locke-lunarg1ae57d62020-11-18 10:49:19 -07002084 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002085 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002086 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2087 firstIndex, indexCount, index_size);
locke-lunarg61870c22020-06-09 14:51:50 -06002088 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range);
2089 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002090 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002091 index_buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002092 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002093 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002094 }
2095
2096 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2097 // We will detect more accurate range in the future.
2098 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2099 return skip;
2100}
2101
2102void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag &tag) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002103 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->destroyed) return;
locke-lunarg61870c22020-06-09 14:51:50 -06002104
locke-lunarg1ae57d62020-11-18 10:49:19 -07002105 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002106 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002107 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2108 firstIndex, indexCount, index_size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002109 current_context_->UpdateAccessState(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002110
2111 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2112 // We will detect more accurate range in the future.
2113 RecordDrawVertex(UINT32_MAX, 0, tag);
2114}
2115
2116bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002117 bool skip = false;
2118 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002119 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(*this, *cb_state_.get(),
locke-lunarg7077d502020-06-18 21:37:26 -06002120 cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
2121 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002122}
2123
2124void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002125 if (current_renderpass_context_) {
locke-lunarg7077d502020-06-18 21:37:26 -06002126 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea,
2127 tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002128 }
locke-lunarg61870c22020-06-09 14:51:50 -06002129}
2130
John Zulauf355e49b2020-04-24 15:11:15 -06002131bool CommandBufferAccessContext::ValidateNextSubpass(const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002132 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002133 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002134 skip |= current_renderpass_context_->ValidateNextSubpass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002135
2136 return skip;
2137}
2138
2139bool CommandBufferAccessContext::ValidateEndRenderpass(const char *func_name) const {
2140 // TODO: Things to add here.
John Zulauf7635de32020-05-29 17:14:15 -06002141 // Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002142 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002143 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002144 skip |= current_renderpass_context_->ValidateEndRenderPass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002145
2146 return skip;
2147}
2148
2149void CommandBufferAccessContext::RecordBeginRenderPass(const ResourceUsageTag &tag) {
2150 assert(sync_state_);
2151 if (!cb_state_) return;
2152
2153 // Create an access context the current renderpass.
John Zulauf1a224292020-06-30 14:52:13 -06002154 render_pass_contexts_.emplace_back();
John Zulauf16adfc92020-04-08 10:28:33 -06002155 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf1a224292020-06-30 14:52:13 -06002156 current_renderpass_context_->RecordBeginRenderPass(*sync_state_, *cb_state_, &cb_access_context_, queue_flags_, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002157 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf16adfc92020-04-08 10:28:33 -06002158}
2159
John Zulauffaea0ee2021-01-14 14:01:32 -07002160void CommandBufferAccessContext::RecordNextSubpass(const RENDER_PASS_STATE &rp_state, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002161 assert(current_renderpass_context_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002162 auto prev_tag = NextCommandTag(command);
2163 auto next_tag = NextSubcommandTag(command);
2164 current_renderpass_context_->RecordNextSubpass(cb_state_->activeRenderPassBeginInfo.renderArea, prev_tag, next_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002165 current_context_ = &current_renderpass_context_->CurrentContext();
2166}
2167
John Zulauffaea0ee2021-01-14 14:01:32 -07002168void CommandBufferAccessContext::RecordEndRenderPass(const RENDER_PASS_STATE &render_pass, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002169 assert(current_renderpass_context_);
2170 if (!current_renderpass_context_) return;
2171
John Zulauffaea0ee2021-01-14 14:01:32 -07002172 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, cb_state_->activeRenderPassBeginInfo.renderArea,
2173 NextCommandTag(command));
John Zulauf355e49b2020-04-24 15:11:15 -06002174 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002175 current_renderpass_context_ = nullptr;
2176}
2177
John Zulauf49beb112020-11-04 16:06:31 -07002178bool CommandBufferAccessContext::ValidateSetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2179 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002180 // I'll put this here just in case we need to pass this in for future extension support
2181 const auto cmd = CMD_SETEVENT;
2182 bool skip = false;
John Zulauf669dfd52021-01-27 17:15:28 -07002183 const auto *event_state = sync_state_->Get<EVENT_STATE>(event);
2184 if (!event_state) return skip;
2185
2186 const auto *sync_event = GetCurrentEventsContext()->Get(event_state);
John Zulauf4a6105a2020-11-17 15:11:05 -07002187 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2188
2189 const char *const reset_set =
2190 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2191 "hazards.";
2192 const char *const wait =
2193 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
2194
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002195 const auto exec_scope = sync_utils::WithEarlierPipelineStages(sync_utils::ExpandPipelineStages(stageMask, GetQueueFlags()));
John Zulauf4a6105a2020-11-17 15:11:05 -07002196 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2197 const char *vuid = nullptr;
2198 const char *message = nullptr;
2199 switch (sync_event->last_command) {
2200 case CMD_RESETEVENT:
2201 // Needs a barrier between reset and set
2202 vuid = "SYNC-vkCmdSetEvent-missingbarrier-reset";
2203 message = reset_set;
2204 break;
2205 case CMD_SETEVENT:
2206 // Needs a barrier between set and set
2207 vuid = "SYNC-vkCmdSetEvent-missingbarrier-set";
2208 message = reset_set;
2209 break;
2210 case CMD_WAITEVENTS:
2211 // Needs a barrier or is in second execution scope
2212 vuid = "SYNC-vkCmdSetEvent-missingbarrier-wait";
2213 message = wait;
2214 break;
2215 default:
2216 // The only other valid last command that wasn't one.
2217 assert(sync_event->last_command == CMD_NONE);
2218 break;
2219 }
2220 if (vuid) {
2221 assert(nullptr != message);
2222 const char *const cmd_name = CommandTypeString(cmd);
2223 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2224 cmd_name, CommandTypeString(sync_event->last_command));
2225 }
2226 }
2227
2228 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002229}
2230
John Zulauf4a6105a2020-11-17 15:11:05 -07002231void CommandBufferAccessContext::RecordSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask,
2232 const ResourceUsageTag &tag) {
John Zulauf669dfd52021-01-27 17:15:28 -07002233 auto event_state_shared = sync_state_->GetShared<EVENT_STATE>(event);
2234 if (!event_state_shared.get()) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2235
2236 auto *sync_event = GetCurrentEventsContext()->GetFromShared(event_state_shared);
John Zulauf4a6105a2020-11-17 15:11:05 -07002237 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2238
2239 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
2240 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
2241 // any issues caused by naive scope setting here.
2242
2243 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
2244 // Given:
2245 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
2246 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002247 auto scope = SyncExecScope::MakeSrc(GetQueueFlags(), stageMask);
John Zulauf4a6105a2020-11-17 15:11:05 -07002248
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002249 if (!sync_event->HasBarrier(stageMask, scope.exec_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002250 sync_event->unsynchronized_set = sync_event->last_command;
2251 sync_event->ResetFirstScope();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002252 } else if (sync_event->scope.exec_scope == 0) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002253 // We only set the scope if there isn't one
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002254 sync_event->scope = scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07002255
2256 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
2257 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002258 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002259 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
2260 }
2261 };
2262 GetCurrentAccessContext()->ForAll(set_scope);
2263 sync_event->unsynchronized_set = CMD_NONE;
2264 sync_event->first_scope_tag = tag;
2265 }
2266 sync_event->last_command = CMD_SETEVENT;
2267 sync_event->barriers = 0U;
2268}
John Zulauf49beb112020-11-04 16:06:31 -07002269
2270bool CommandBufferAccessContext::ValidateResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2271 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002272 // I'll put this here just in case we need to pass this in for future extension support
2273 const auto cmd = CMD_RESETEVENT;
2274
2275 bool skip = false;
2276 // TODO: EVENTS:
2277 // What is it we need to check... that we've had a reset since a set? Set/Set seems ill formed...
John Zulauf669dfd52021-01-27 17:15:28 -07002278 auto event_state = sync_state_->Get<EVENT_STATE>(event);
2279 if (!event_state) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
2280
2281 const auto *sync_event = GetCurrentEventsContext()->Get(event_state);
John Zulauf4a6105a2020-11-17 15:11:05 -07002282 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2283
2284 const char *const set_wait =
2285 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2286 "hazards.";
2287 const char *message = set_wait; // Only one message this call.
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002288 const auto exec_scope = sync_utils::WithEarlierPipelineStages(sync_utils::ExpandPipelineStages(stageMask, GetQueueFlags()));
John Zulauf4a6105a2020-11-17 15:11:05 -07002289 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2290 const char *vuid = nullptr;
2291 switch (sync_event->last_command) {
2292 case CMD_SETEVENT:
2293 // Needs a barrier between set and reset
2294 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
2295 break;
2296 case CMD_WAITEVENTS: {
2297 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
2298 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
2299 break;
2300 }
2301 default:
2302 // The only other valid last command that wasn't one.
2303 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT));
2304 break;
2305 }
2306 if (vuid) {
2307 const char *const cmd_name = CommandTypeString(cmd);
2308 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2309 cmd_name, CommandTypeString(sync_event->last_command));
2310 }
2311 }
2312 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002313}
2314
John Zulauf4a6105a2020-11-17 15:11:05 -07002315void CommandBufferAccessContext::RecordResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
2316 const auto cmd = CMD_RESETEVENT;
John Zulauf669dfd52021-01-27 17:15:28 -07002317 auto event_state_shared = sync_state_->GetShared<EVENT_STATE>(event);
2318 if (!event_state_shared.get()) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2319
2320 auto *sync_event = GetCurrentEventsContext()->GetFromShared(event_state_shared);
John Zulauf4a6105a2020-11-17 15:11:05 -07002321 if (!sync_event) return;
John Zulauf49beb112020-11-04 16:06:31 -07002322
John Zulauf4a6105a2020-11-17 15:11:05 -07002323 // Clear out the first sync scope, any races vs. wait or set are reported, so we'll keep the bookkeeping simple assuming
2324 // the safe case
2325 for (const auto address_type : kAddressTypes) {
2326 sync_event->first_scope[static_cast<size_t>(address_type)].clear();
2327 }
2328
2329 // Update the event state
2330 sync_event->last_command = cmd;
2331 sync_event->unsynchronized_set = CMD_NONE;
2332 sync_event->ResetFirstScope();
2333 sync_event->barriers = 0U;
2334}
2335
John Zulauf4a6105a2020-11-17 15:11:05 -07002336void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2337 // Erase is okay with the key not being
John Zulauf669dfd52021-01-27 17:15:28 -07002338 const auto *event_state = sync_state_->Get<EVENT_STATE>(event);
2339 if (event_state) {
2340 GetCurrentEventsContext()->Destroy(event_state);
John Zulaufd5115702021-01-18 12:34:33 -07002341 }
2342}
2343
John Zulauffaea0ee2021-01-14 14:01:32 -07002344bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandBufferAccessContext &cb_context,
2345 const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2346 const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002347 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002348 const auto &sync_state = cb_context.GetSyncState();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002349 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2350 if (!pipe ||
2351 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002352 return skip;
2353 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002354 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002355 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2356 VkExtent3D extent = CastTo3D(render_area.extent);
2357 VkOffset3D offset = CastTo3D(render_area.offset);
locke-lunarg37047832020-06-12 13:44:45 -06002358
John Zulauf1a224292020-06-30 14:52:13 -06002359 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002360 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002361 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2362 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002363 if (location >= subpass.colorAttachmentCount ||
2364 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002365 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002366 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002367 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf1a224292020-06-30 14:52:13 -06002368 HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002369 SyncOrdering::kColorAttachment, offset, extent);
locke-lunarg96dc9632020-06-10 17:22:18 -06002370 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002371 skip |= sync_state.LogError(img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002372 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002373 func_name, string_SyncHazard(hazard.hazard),
2374 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2375 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002376 location, cb_context.FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002377 }
2378 }
2379 }
locke-lunarg37047832020-06-12 13:44:45 -06002380
2381 // PHASE1 TODO: Add layout based read/vs. write selection.
2382 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002383 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002384 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002385 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002386 bool depth_write = false, stencil_write = false;
2387
2388 // PHASE1 TODO: These validation should be in core_checks.
2389 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002390 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2391 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002392 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2393 depth_write = true;
2394 }
2395 // PHASE1 TODO: It needs to check if stencil is writable.
2396 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2397 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2398 // PHASE1 TODO: These validation should be in core_checks.
2399 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002400 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002401 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2402 stencil_write = true;
2403 }
2404
2405 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2406 if (depth_write) {
2407 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002408 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002409 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002410 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002411 skip |= sync_state.LogError(
2412 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002413 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002414 func_name, string_SyncHazard(hazard.hazard),
2415 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2416 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002417 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002418 }
2419 }
2420 if (stencil_write) {
2421 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002422 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002423 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002424 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002425 skip |= sync_state.LogError(
2426 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002427 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002428 func_name, string_SyncHazard(hazard.hazard),
2429 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2430 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002431 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002432 }
locke-lunarg61870c22020-06-09 14:51:50 -06002433 }
2434 }
2435 return skip;
2436}
2437
locke-lunarg96dc9632020-06-10 17:22:18 -06002438void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2439 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002440 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2441 if (!pipe ||
2442 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002443 return;
2444 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002445 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002446 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2447 VkExtent3D extent = CastTo3D(render_area.extent);
2448 VkOffset3D offset = CastTo3D(render_area.offset);
2449
John Zulauf1a224292020-06-30 14:52:13 -06002450 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002451 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002452 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2453 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002454 if (location >= subpass.colorAttachmentCount ||
2455 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002456 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002457 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002458 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf8e3c3e92021-01-06 11:19:36 -07002459 current_context.UpdateAccessState(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
2460 SyncOrdering::kColorAttachment, offset, extent, 0, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002461 }
2462 }
locke-lunarg37047832020-06-12 13:44:45 -06002463
2464 // PHASE1 TODO: Add layout based read/vs. write selection.
2465 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002466 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002467 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002468 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002469 bool depth_write = false, stencil_write = false;
2470
2471 // PHASE1 TODO: These validation should be in core_checks.
2472 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002473 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2474 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002475 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2476 depth_write = true;
2477 }
2478 // PHASE1 TODO: It needs to check if stencil is writable.
2479 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2480 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2481 // PHASE1 TODO: These validation should be in core_checks.
2482 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002483 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002484 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2485 stencil_write = true;
2486 }
2487
2488 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2489 if (depth_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002490 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2491 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT,
2492 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002493 }
2494 if (stencil_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002495 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2496 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT,
2497 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002498 }
locke-lunarg61870c22020-06-09 14:51:50 -06002499 }
2500}
2501
John Zulauffaea0ee2021-01-14 14:01:32 -07002502bool RenderPassAccessContext::ValidateNextSubpass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf1507ee42020-05-18 11:33:09 -06002503 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002504 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002505 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002506 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002507 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002508 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002509 func_name);
2510
John Zulauf355e49b2020-04-24 15:11:15 -06002511 const auto next_subpass = current_subpass_ + 1;
John Zulauf1507ee42020-05-18 11:33:09 -06002512 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauffaea0ee2021-01-14 14:01:32 -07002513 skip |= next_context.ValidateLayoutTransitions(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002514 if (!skip) {
2515 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2516 // on a copy of the (empty) next context.
2517 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2518 AccessContext temp_context(next_context);
2519 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07002520 skip |= temp_context.ValidateLoadOperation(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002521 }
John Zulauf7635de32020-05-29 17:14:15 -06002522 return skip;
2523}
John Zulauffaea0ee2021-01-14 14:01:32 -07002524bool RenderPassAccessContext::ValidateEndRenderPass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf7635de32020-05-29 17:14:15 -06002525 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002526 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002527 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002528 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002529 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002530 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002531 func_name);
John Zulauffaea0ee2021-01-14 14:01:32 -07002532 skip |= ValidateFinalSubpassLayoutTransitions(cb_context, render_area, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002533 return skip;
2534}
2535
John Zulauf7635de32020-05-29 17:14:15 -06002536AccessContext *RenderPassAccessContext::CreateStoreResolveProxy(const VkRect2D &render_area) const {
2537 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, render_area, attachment_views_);
2538}
2539
John Zulauffaea0ee2021-01-14 14:01:32 -07002540bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandBufferAccessContext &cb_context,
2541 const VkRect2D &render_area, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002542 bool skip = false;
2543
John Zulauf7635de32020-05-29 17:14:15 -06002544 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2545 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2546 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2547 // to apply and only copy then, if this proves a hot spot.
2548 std::unique_ptr<AccessContext> proxy_for_current;
2549
John Zulauf355e49b2020-04-24 15:11:15 -06002550 // Validate the "finalLayout" transitions to external
2551 // Get them from where there we're hidding in the extra entry.
2552 const auto &final_transitions = rp_state_->subpass_transitions.back();
2553 for (const auto &transition : final_transitions) {
2554 const auto &attach_view = attachment_views_[transition.attachment];
2555 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
2556 assert(trackback.context); // Transitions are given implicit transitions if the StateTracker is working correctly
John Zulauf7635de32020-05-29 17:14:15 -06002557 auto *context = trackback.context;
2558
2559 if (transition.prev_pass == current_subpass_) {
2560 if (!proxy_for_current) {
2561 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
2562 proxy_for_current.reset(CreateStoreResolveProxy(render_area));
2563 }
2564 context = proxy_for_current.get();
2565 }
2566
John Zulaufa0a98292020-09-18 09:30:10 -06002567 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2568 const auto merged_barrier = MergeBarriers(trackback.barriers);
2569 auto hazard = context->DetectImageBarrierHazard(*attach_view->image_state, merged_barrier.src_exec_scope,
2570 merged_barrier.src_access_scope, attach_view->normalized_subresource_range,
2571 AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002572 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -07002573 skip |= cb_context.GetSyncState().LogError(
2574 rp_state_->renderPass, string_SyncHazardVUID(hazard.hazard),
2575 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2576 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2577 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2578 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
2579 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06002580 }
2581 }
2582 return skip;
2583}
2584
2585void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag &tag) {
2586 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002587 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002588}
2589
John Zulauf1507ee42020-05-18 11:33:09 -06002590void RenderPassAccessContext::RecordLoadOperations(const VkRect2D &render_area, const ResourceUsageTag &tag) {
2591 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2592 auto &subpass_context = subpass_contexts_[current_subpass_];
2593 VkExtent3D extent = CastTo3D(render_area.extent);
2594 VkOffset3D offset = CastTo3D(render_area.offset);
2595
2596 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2597 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
2598 if (attachment_views_[i] == nullptr) continue; // UNUSED
2599 const auto &view = *attachment_views_[i];
2600 const IMAGE_STATE *image = view.image_state.get();
2601 if (image == nullptr) continue;
2602
2603 const auto &ci = attachment_ci[i];
2604 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002605 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002606 const bool is_color = !(has_depth || has_stencil);
2607
2608 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002609 subpass_context.UpdateAccessState(*image, ColorLoadUsage(ci.loadOp), SyncOrdering::kColorAttachment,
2610 view.normalized_subresource_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002611 } else {
2612 auto update_range = view.normalized_subresource_range;
2613 if (has_depth) {
2614 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002615 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.loadOp),
2616 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002617 }
2618 if (has_stencil) {
2619 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002620 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.stencilLoadOp),
2621 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002622 }
2623 }
2624 }
2625 }
2626}
2627
John Zulauf355e49b2020-04-24 15:11:15 -06002628void RenderPassAccessContext::RecordBeginRenderPass(const SyncValidator &state, const CMD_BUFFER_STATE &cb_state,
John Zulauf1a224292020-06-30 14:52:13 -06002629 const AccessContext *external_context, VkQueueFlags queue_flags,
2630 const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002631 current_subpass_ = 0;
locke-lunargaecf2152020-05-12 17:15:41 -06002632 rp_state_ = cb_state.activeRenderPass.get();
John Zulauf355e49b2020-04-24 15:11:15 -06002633 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
2634 // Add this for all subpasses here so that they exsist during next subpass validation
2635 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002636 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulauf355e49b2020-04-24 15:11:15 -06002637 }
2638 attachment_views_ = state.GetCurrentAttachmentViews(cb_state);
2639
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002640 subpass_contexts_[current_subpass_].SetStartTag(tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002641 RecordLayoutTransitions(tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002642 RecordLoadOperations(cb_state.activeRenderPassBeginInfo.renderArea, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002643}
John Zulauf1507ee42020-05-18 11:33:09 -06002644
John Zulauffaea0ee2021-01-14 14:01:32 -07002645void RenderPassAccessContext::RecordNextSubpass(const VkRect2D &render_area, const ResourceUsageTag &prev_subpass_tag,
2646 const ResourceUsageTag &next_subpass_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002647 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauffaea0ee2021-01-14 14:01:32 -07002648 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
2649 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002650
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002651 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2652 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002653 current_subpass_++;
2654 assert(current_subpass_ < subpass_contexts_.size());
John Zulauffaea0ee2021-01-14 14:01:32 -07002655 subpass_contexts_[current_subpass_].SetStartTag(next_subpass_tag);
2656 RecordLayoutTransitions(next_subpass_tag);
2657 RecordLoadOperations(render_area, next_subpass_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002658}
2659
John Zulauf1a224292020-06-30 14:52:13 -06002660void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const VkRect2D &render_area,
2661 const ResourceUsageTag &tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002662 // Add the resolve and store accesses
John Zulauf7635de32020-05-29 17:14:15 -06002663 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulaufaff20662020-06-01 14:07:58 -06002664 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulauf7635de32020-05-29 17:14:15 -06002665
John Zulauf355e49b2020-04-24 15:11:15 -06002666 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002667 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002668
2669 // Add the "finalLayout" transitions to external
2670 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002671 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2672 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2673 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002674 const auto &final_transitions = rp_state_->subpass_transitions.back();
2675 for (const auto &transition : final_transitions) {
2676 const auto &attachment = attachment_views_[transition.attachment];
2677 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufaa97d8b2020-07-14 10:58:13 -06002678 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.context);
John Zulaufd5115702021-01-18 12:34:33 -07002679 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002680 for (const auto &barrier : last_trackback.barriers) {
John Zulaufd5115702021-01-18 12:34:33 -07002681 barrier_action.EmplaceBack(PipelineBarrierOp(barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002682 }
John Zulauf1e331ec2020-12-04 18:29:38 -07002683 external_context->UpdateResourceAccess(*attachment->image_state, attachment->normalized_subresource_range, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002684 }
2685}
2686
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002687SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2688 SyncExecScope result;
2689 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002690 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2691 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002692 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2693 return result;
2694}
2695
2696SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2697 SyncExecScope result;
2698 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002699 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2700 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002701 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2702 return result;
2703}
2704
2705SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
2706 src_exec_scope = src.exec_scope;
2707 src_access_scope = 0;
2708 dst_exec_scope = dst.exec_scope;
2709 dst_access_scope = 0;
2710}
2711
2712template <typename Barrier>
2713SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
2714 src_exec_scope = src.exec_scope;
2715 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2716 dst_exec_scope = dst.exec_scope;
2717 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2718}
2719
2720SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
2721 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
2722 src_exec_scope = src.exec_scope;
2723 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2724
2725 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
2726 dst_exec_scope = dst.exec_scope;
2727 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002728}
2729
John Zulaufb02c1eb2020-10-06 16:33:36 -06002730// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2731void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
2732 for (const auto &barrier : barriers) {
2733 ApplyBarrier(barrier, layout_transition);
2734 }
2735}
2736
John Zulauf89311b42020-09-29 16:28:47 -06002737// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2738// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2739// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufb02c1eb2020-10-06 16:33:36 -06002740void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, const ResourceUsageTag &tag) {
2741 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002742 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002743 assert(!pending_write_dep_chain);
John Zulaufa0a98292020-09-18 09:30:10 -06002744 for (const auto &barrier : barriers) {
John Zulauf89311b42020-09-29 16:28:47 -06002745 ApplyBarrier(barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002746 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002747 ApplyPendingBarriers(tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002748}
John Zulauf9cb530d2019-09-30 14:14:10 -06002749HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2750 HazardResult hazard;
2751 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002752 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002753 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002754 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002755 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002756 }
2757 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002758 // Write operation:
2759 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2760 // If reads exists -- test only against them because either:
2761 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2762 // * the read weren't hazards, and thus if the write is safe w.r.t. the reads, no hazard vs. last_write is possible if
2763 // the current write happens after the reads, so just test the write against the reades
2764 // Otherwise test against last_write
2765 //
2766 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002767 if (last_reads.size()) {
2768 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002769 if (IsReadHazard(usage_stage, read_access)) {
2770 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2771 break;
2772 }
2773 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002774 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002775 // Write-After-Write check -- if we have a previous write to test against
2776 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002777 }
2778 }
2779 return hazard;
2780}
2781
John Zulauf8e3c3e92021-01-06 11:19:36 -07002782HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering &ordering_rule) const {
2783 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06002784 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2785 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002786 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002787 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002788 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2789 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002790 if (IsRead(usage_bit)) {
2791 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2792 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2793 if (is_raw_hazard) {
2794 // NOTE: we know last_write is non-zero
2795 // See if the ordering rules save us from the simple RAW check above
2796 // First check to see if the current usage is covered by the ordering rules
2797 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2798 const bool usage_is_ordered =
2799 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2800 if (usage_is_ordered) {
2801 // Now see of the most recent write (or a subsequent read) are ordered
2802 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2803 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002804 }
2805 }
John Zulauf4285ee92020-09-23 10:20:52 -06002806 if (is_raw_hazard) {
2807 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
2808 }
John Zulauf361fb532020-07-22 10:45:39 -06002809 } else {
2810 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002811 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07002812 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06002813 // Look for any WAR hazards outside the ordered set of stages
John Zulauf4285ee92020-09-23 10:20:52 -06002814 VkPipelineStageFlags ordered_stages = 0;
2815 if (usage_write_is_ordered) {
2816 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
2817 ordered_stages = GetOrderedStages(ordering);
2818 }
2819 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
2820 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07002821 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06002822 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
2823 if (IsReadHazard(usage_stage, read_access)) {
2824 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2825 break;
2826 }
John Zulaufd14743a2020-07-03 09:42:39 -06002827 }
2828 }
John Zulauf4285ee92020-09-23 10:20:52 -06002829 } else if (!(last_write_is_ordered && usage_write_is_ordered)) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002830 if (last_write.any() && IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002831 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06002832 }
John Zulauf69133422020-05-20 14:55:53 -06002833 }
2834 }
2835 return hazard;
2836}
2837
John Zulauf2f952d22020-02-10 11:34:51 -07002838// Asynchronous Hazards occur between subpasses with no connection through the DAG
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002839HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag &start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07002840 HazardResult hazard;
2841 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002842 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
2843 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
2844 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07002845 if (IsRead(usage)) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002846 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002847 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07002848 }
2849 } else {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002850 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002851 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07002852 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002853 // Any reads during the other subpass will conflict with this write, so we need to check them all.
John Zulaufab7756b2020-12-29 16:10:16 -07002854 for (const auto &read_access : last_reads) {
2855 if (read_access.tag.index >= start_tag.index) {
2856 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002857 break;
2858 }
2859 }
John Zulauf2f952d22020-02-10 11:34:51 -07002860 }
2861 }
2862 return hazard;
2863}
2864
John Zulauf36bcf6a2020-02-03 15:12:52 -07002865HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002866 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07002867 // Only supporting image layout transitions for now
2868 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2869 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06002870 // only test for WAW if there no intervening read operations.
2871 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07002872 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06002873 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07002874 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002875 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06002876 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07002877 break;
2878 }
2879 }
John Zulauf4a6105a2020-11-17 15:11:05 -07002880 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2881 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2882 }
2883
2884 return hazard;
2885}
2886
2887HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
2888 const SyncStageAccessFlags &src_access_scope,
2889 const ResourceUsageTag &event_tag) const {
2890 // Only supporting image layout transitions for now
2891 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2892 HazardResult hazard;
2893 // only test for WAW if there no intervening read operations.
2894 // See DetectHazard(SyncStagetAccessIndex) above for more details.
2895
John Zulaufab7756b2020-12-29 16:10:16 -07002896 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002897 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
2898 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07002899 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002900 if (read_access.tag.IsBefore(event_tag)) {
2901 // The read is in the events first synchronization scope, so we use a barrier hazard check
2902 // If the read stage is not in the src sync scope
2903 // *AND* not execution chained with an existing sync barrier (that's the or)
2904 // then the barrier access is unsafe (R/W after R)
2905 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
2906 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2907 break;
2908 }
2909 } else {
2910 // The read not in the event first sync scope and so is a hazard vs. the layout transition
2911 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2912 }
2913 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002914 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002915 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
2916 if (write_tag.IsBefore(event_tag)) {
2917 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
2918 // So do a normal barrier hazard check
2919 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2920 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2921 }
2922 } else {
2923 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06002924 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2925 }
John Zulaufd14743a2020-07-03 09:42:39 -06002926 }
John Zulauf361fb532020-07-22 10:45:39 -06002927
John Zulauf0cb5be22020-01-23 12:18:22 -07002928 return hazard;
2929}
2930
John Zulauf5f13a792020-03-10 07:31:21 -06002931// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
2932// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
2933// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
2934void ResourceAccessState::Resolve(const ResourceAccessState &other) {
2935 if (write_tag.IsBefore(other.write_tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002936 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
2937 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06002938 *this = other;
2939 } else if (!other.write_tag.IsBefore(write_tag)) {
2940 // This is the *equals* case for write operations, we merged the write barriers and the read state (but without the
2941 // dependency chaining logic or any stage expansion)
2942 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002943 pending_write_barriers |= other.pending_write_barriers;
2944 pending_layout_transition |= other.pending_layout_transition;
2945 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06002946
John Zulaufd14743a2020-07-03 09:42:39 -06002947 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07002948 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06002949 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07002950 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06002951 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06002952 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06002953 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06002954 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
2955 // but we should wait on profiling data for that.
2956 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06002957 auto &my_read = last_reads[my_read_index];
2958 if (other_read.stage == my_read.stage) {
2959 if (my_read.tag.IsBefore(other_read.tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002960 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06002961 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06002962 my_read.tag = other_read.tag;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002963 my_read.pending_dep_chain = other_read.pending_dep_chain;
2964 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
2965 // May require tracking more than one access per stage.
2966 my_read.barriers = other_read.barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06002967 if (my_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
2968 // Since I'm overwriting the fragement stage read, also update the input attachment info
2969 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06002970 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06002971 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002972 } else if (other_read.tag.IsBefore(my_read.tag)) {
2973 // The read tags match so merge the barriers
2974 my_read.barriers |= other_read.barriers;
2975 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06002976 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002977
John Zulauf5f13a792020-03-10 07:31:21 -06002978 break;
2979 }
2980 }
2981 } else {
2982 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07002983 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06002984 last_read_stages |= other_read.stage;
John Zulauf4285ee92020-09-23 10:20:52 -06002985 if (other_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06002986 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06002987 }
John Zulauf5f13a792020-03-10 07:31:21 -06002988 }
2989 }
John Zulauf361fb532020-07-22 10:45:39 -06002990 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06002991 } // the else clause would be that other write is before this write... in which case we supercede the other state and
2992 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07002993
2994 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
2995 // of the copy and other into this using the update first logic.
2996 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
2997 // of the other first_accesses... )
2998 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
2999 FirstAccesses firsts(std::move(first_accesses_));
3000 first_accesses_.clear();
3001 first_read_stages_ = 0U;
3002 auto a = firsts.begin();
3003 auto a_end = firsts.end();
3004 for (auto &b : other.first_accesses_) {
3005 // TODO: Determine whether "IsBefore" or "IsGloballyBefore" is needed...
3006 while (a != a_end && a->tag.IsBefore(b.tag)) {
3007 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3008 ++a;
3009 }
3010 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3011 }
3012 for (; a != a_end; ++a) {
3013 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3014 }
3015 }
John Zulauf5f13a792020-03-10 07:31:21 -06003016}
3017
John Zulauf8e3c3e92021-01-06 11:19:36 -07003018void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag &tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003019 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3020 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003021 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003022 // Mulitple outstanding reads may be of interest and do dependency chains independently
3023 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3024 const auto usage_stage = PipelineStageBit(usage_index);
3025 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003026 for (auto &read_access : last_reads) {
3027 if (read_access.stage == usage_stage) {
3028 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003029 break;
3030 }
3031 }
3032 } else {
John Zulaufab7756b2020-12-29 16:10:16 -07003033 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003034 last_read_stages |= usage_stage;
3035 }
John Zulauf4285ee92020-09-23 10:20:52 -06003036
3037 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
3038 if (usage_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003039 // TODO Revisit re: multiple reads for a given stage
3040 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003041 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003042 } else {
3043 // Assume write
3044 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003045 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003046 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003047 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003048}
John Zulauf5f13a792020-03-10 07:31:21 -06003049
John Zulauf89311b42020-09-29 16:28:47 -06003050// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3051// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3052// We can overwrite them as *this* write is now after them.
3053//
3054// Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them.
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003055void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag &tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003056 last_reads.clear();
John Zulauf89311b42020-09-29 16:28:47 -06003057 last_read_stages = 0;
3058 read_execution_barriers = 0;
John Zulauff51fbb62020-10-02 14:43:24 -06003059 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
John Zulauf89311b42020-09-29 16:28:47 -06003060
3061 write_barriers = 0;
3062 write_dependency_chain = 0;
3063 write_tag = tag;
3064 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003065}
3066
John Zulauf89311b42020-09-29 16:28:47 -06003067// Apply the memory barrier without updating the existing barriers. The execution barrier
3068// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3069// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3070// replace the current write barriers or add to them, so accumulate to pending as well.
3071void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) {
3072 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3073 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003074 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
3075 // transistion, under the theory of "most recent access". If the read/write *isn't* safe
3076 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3077 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulauf4a6105a2020-11-17 15:11:05 -07003078 if (layout_transition || WriteInSourceScopeOrChain(barrier.src_exec_scope, barrier.src_access_scope)) {
John Zulauf89311b42020-09-29 16:28:47 -06003079 pending_write_barriers |= barrier.dst_access_scope;
3080 pending_write_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003081 }
John Zulauf89311b42020-09-29 16:28:47 -06003082 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3083 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003084
John Zulauf89311b42020-09-29 16:28:47 -06003085 if (!pending_layout_transition) {
3086 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3087 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003088 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003089 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
John Zulaufab7756b2020-12-29 16:10:16 -07003090 if (barrier.src_exec_scope & (read_access.stage | read_access.barriers)) {
3091 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003092 }
3093 }
John Zulaufa0a98292020-09-18 09:30:10 -06003094 }
John Zulaufa0a98292020-09-18 09:30:10 -06003095}
3096
John Zulauf4a6105a2020-11-17 15:11:05 -07003097// Apply the tag scoped memory barrier without updating the existing barriers. The execution barrier
3098// changes the "chaining" state, but to keep barriers independent. See discussion above.
3099void ResourceAccessState::ApplyBarrier(const ResourceUsageTag &scope_tag, const SyncBarrier &barrier, bool layout_transition) {
3100 // The scope logic for events is, if we're here, the resource usage was flagged as "in the first execution scope" at
3101 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3102 // in order to know if it's in the excecution scope
3103 // Notice that the layout transition sets the pending barriers *regardless*, as any lack of src_access_scope to
3104 // guard against the layout transition should be reported in the detect barrier hazard phase, and we only report
3105 // errors w.r.t. "most recent" accesses.
3106 if (layout_transition || ((write_tag.IsBefore(scope_tag)) && (barrier.src_access_scope & last_write).any())) {
3107 pending_write_barriers |= barrier.dst_access_scope;
3108 pending_write_dep_chain |= barrier.dst_exec_scope;
3109 }
3110 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3111 pending_layout_transition |= layout_transition;
3112
3113 if (!pending_layout_transition) {
3114 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3115 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003116 for (auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003117 // If this read is the same one we included in the set event and in scope, then apply the execution barrier...
3118 // NOTE: That's not really correct... this read stage might *not* have been included in the setevent, and the barriers
3119 // representing the chain might have changed since then (that would be an odd usage), so as a first approximation
3120 // we'll assume the barriers *haven't* been changed since (if the tag hasn't), and while this could be a false
3121 // positive in the case of Set; SomeBarrier; Wait; we'll live with it until we can add more state to the first scope
3122 // capture (the specific write and read stages that *were* in scope at the moment of SetEvents.
3123 // TODO: eliminate the false positive by including write/read-stages "in scope" information in SetEvents first_scope
John Zulaufab7756b2020-12-29 16:10:16 -07003124 if (read_access.tag.IsBefore(scope_tag) && (barrier.src_exec_scope & (read_access.stage | read_access.barriers))) {
3125 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07003126 }
3127 }
3128 }
3129}
John Zulauf89311b42020-09-29 16:28:47 -06003130void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag &tag) {
3131 if (pending_layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003132 // SetWrite clobbers the read count, and thus we don't have to clear the read_state out.
3133 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003134 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf89311b42020-09-29 16:28:47 -06003135 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003136 }
John Zulauf89311b42020-09-29 16:28:47 -06003137
3138 // Apply the accumulate execution barriers (and thus update chaining information)
3139 // for layout transition, read count is zeroed by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003140 for (auto &read_access : last_reads) {
3141 read_access.barriers |= read_access.pending_dep_chain;
3142 read_execution_barriers |= read_access.barriers;
3143 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003144 }
3145
3146 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3147 write_dependency_chain |= pending_write_dep_chain;
3148 write_barriers |= pending_write_barriers;
3149 pending_write_dep_chain = 0;
3150 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003151}
3152
John Zulauf59e25072020-07-17 10:55:21 -06003153// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003154VkPipelineStageFlags ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
John Zulauf59e25072020-07-17 10:55:21 -06003155 VkPipelineStageFlags barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003156
John Zulaufab7756b2020-12-29 16:10:16 -07003157 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003158 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003159 barriers = read_access.barriers;
3160 break;
John Zulauf59e25072020-07-17 10:55:21 -06003161 }
3162 }
John Zulauf4285ee92020-09-23 10:20:52 -06003163
John Zulauf59e25072020-07-17 10:55:21 -06003164 return barriers;
3165}
3166
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003167inline bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlagBits usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003168 assert(IsRead(usage));
3169 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3170 // * the previous reads are not hazards, and thus last_write must be visible and available to
3171 // any reads that happen after.
3172 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3173 // the current read will be also not be a hazard, thus reporting a hazard here adds no needed information.
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003174 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003175}
3176
John Zulauf8e3c3e92021-01-06 11:19:36 -07003177VkPipelineStageFlags ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003178 // Whether the stage are in the ordering scope only matters if the current write is ordered
3179 VkPipelineStageFlags ordered_stages = last_read_stages & ordering.exec_scope;
3180 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003181 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003182 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003183 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
3184 ordered_stages |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
3185 }
3186
3187 return ordered_stages;
3188}
3189
John Zulauffaea0ee2021-01-14 14:01:32 -07003190void ResourceAccessState::UpdateFirst(const ResourceUsageTag &tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
3191 // Only record until we record a write.
3192 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003193 const VkPipelineStageFlags usage_stage =
3194 IsRead(usage_index) ? static_cast<VkPipelineStageFlags>(PipelineStageBit(usage_index)) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003195 if (0 == (usage_stage & first_read_stages_)) {
3196 // If this is a read we haven't seen or a write, record.
3197 first_read_stages_ |= usage_stage;
3198 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3199 }
3200 }
3201}
3202
John Zulaufd1f85d42020-04-15 12:23:15 -06003203void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003204 auto *access_context = GetAccessContextNoInsert(command_buffer);
3205 if (access_context) {
3206 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003207 }
3208}
3209
John Zulaufd1f85d42020-04-15 12:23:15 -06003210void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3211 auto access_found = cb_access_state.find(command_buffer);
3212 if (access_found != cb_access_state.end()) {
3213 access_found->second->Reset();
3214 cb_access_state.erase(access_found);
3215 }
3216}
3217
John Zulauf9cb530d2019-09-30 14:14:10 -06003218bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3219 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3220 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003221 const auto *cb_context = GetAccessContext(commandBuffer);
3222 assert(cb_context);
3223 if (!cb_context) return skip;
3224 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003225
John Zulauf3d84f1b2020-03-09 13:33:25 -06003226 // If we have no previous accesses, we have no hazards
John Zulauf3d84f1b2020-03-09 13:33:25 -06003227 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003228 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003229
3230 for (uint32_t region = 0; region < regionCount; region++) {
3231 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003232 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003233 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003234 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003235 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003236 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003237 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003238 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003239 cb_context->FormatUsage(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003240 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003241 }
John Zulauf16adfc92020-04-08 10:28:33 -06003242 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003243 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf355e49b2020-04-24 15:11:15 -06003244 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003245 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003246 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003247 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003248 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003249 cb_context->FormatUsage(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003250 }
3251 }
3252 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003253 }
3254 return skip;
3255}
3256
3257void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3258 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003259 auto *cb_context = GetAccessContext(commandBuffer);
3260 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003261 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003262 auto *context = cb_context->GetCurrentAccessContext();
3263
John Zulauf9cb530d2019-09-30 14:14:10 -06003264 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003265 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003266
3267 for (uint32_t region = 0; region < regionCount; region++) {
3268 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003269 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003270 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003271 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003272 }
John Zulauf16adfc92020-04-08 10:28:33 -06003273 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003274 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003275 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003276 }
3277 }
3278}
3279
John Zulauf4a6105a2020-11-17 15:11:05 -07003280void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3281 // Clear out events from the command buffer contexts
3282 for (auto &cb_context : cb_access_state) {
3283 cb_context.second->RecordDestroyEvent(event);
3284 }
3285}
3286
Jeff Leger178b1e52020-10-05 12:22:23 -04003287bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3288 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3289 bool skip = false;
3290 const auto *cb_context = GetAccessContext(commandBuffer);
3291 assert(cb_context);
3292 if (!cb_context) return skip;
3293 const auto *context = cb_context->GetCurrentAccessContext();
3294
3295 // If we have no previous accesses, we have no hazards
3296 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3297 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3298
3299 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3300 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3301 if (src_buffer) {
3302 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
3303 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3304 if (hazard.hazard) {
3305 // TODO -- add tag information to log msg when useful.
3306 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
3307 "vkCmdCopyBuffer2KHR(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
3308 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003309 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003310 }
3311 }
3312 if (dst_buffer && !skip) {
3313 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
3314 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3315 if (hazard.hazard) {
3316 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
3317 "vkCmdCopyBuffer2KHR(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
3318 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003319 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003320 }
3321 }
3322 if (skip) break;
3323 }
3324 return skip;
3325}
3326
3327void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3328 auto *cb_context = GetAccessContext(commandBuffer);
3329 assert(cb_context);
3330 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER2KHR);
3331 auto *context = cb_context->GetCurrentAccessContext();
3332
3333 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3334 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3335
3336 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3337 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3338 if (src_buffer) {
3339 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003340 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003341 }
3342 if (dst_buffer) {
3343 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003344 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003345 }
3346 }
3347}
3348
John Zulauf5c5e88d2019-12-26 11:22:02 -07003349bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3350 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3351 const VkImageCopy *pRegions) const {
3352 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003353 const auto *cb_access_context = GetAccessContext(commandBuffer);
3354 assert(cb_access_context);
3355 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003356
John Zulauf3d84f1b2020-03-09 13:33:25 -06003357 const auto *context = cb_access_context->GetCurrentAccessContext();
3358 assert(context);
3359 if (!context) return skip;
3360
3361 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3362 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003363 for (uint32_t region = 0; region < regionCount; region++) {
3364 const auto &copy_region = pRegions[region];
3365 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003366 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003367 copy_region.srcOffset, copy_region.extent);
3368 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003369 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003370 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003371 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003372 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003373 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003374 }
3375
3376 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003377 VkExtent3D dst_copy_extent =
3378 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf540266b2020-04-06 18:54:53 -06003379 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
locke-lunarg1df1f882020-03-02 16:42:08 -07003380 copy_region.dstOffset, dst_copy_extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003381 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003382 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003383 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003384 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003385 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003386 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07003387 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003388 }
3389 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003390
John Zulauf5c5e88d2019-12-26 11:22:02 -07003391 return skip;
3392}
3393
3394void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3395 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3396 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003397 auto *cb_access_context = GetAccessContext(commandBuffer);
3398 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003399 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003400 auto *context = cb_access_context->GetCurrentAccessContext();
3401 assert(context);
3402
John Zulauf5c5e88d2019-12-26 11:22:02 -07003403 auto *src_image = Get<IMAGE_STATE>(srcImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003404 auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003405
3406 for (uint32_t region = 0; region < regionCount; region++) {
3407 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06003408 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003409 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3410 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003411 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003412 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003413 VkExtent3D dst_copy_extent =
3414 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003415 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3416 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003417 }
3418 }
3419}
3420
Jeff Leger178b1e52020-10-05 12:22:23 -04003421bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
3422 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
3423 bool skip = false;
3424 const auto *cb_access_context = GetAccessContext(commandBuffer);
3425 assert(cb_access_context);
3426 if (!cb_access_context) return skip;
3427
3428 const auto *context = cb_access_context->GetCurrentAccessContext();
3429 assert(context);
3430 if (!context) return skip;
3431
3432 const auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3433 const auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3434 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3435 const auto &copy_region = pCopyImageInfo->pRegions[region];
3436 if (src_image) {
3437 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
3438 copy_region.srcOffset, copy_region.extent);
3439 if (hazard.hazard) {
3440 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
3441 "vkCmdCopyImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
3442 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003443 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003444 }
3445 }
3446
3447 if (dst_image) {
3448 VkExtent3D dst_copy_extent =
3449 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
3450 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
3451 copy_region.dstOffset, dst_copy_extent);
3452 if (hazard.hazard) {
3453 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
3454 "vkCmdCopyImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
3455 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003456 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003457 }
3458 if (skip) break;
3459 }
3460 }
3461
3462 return skip;
3463}
3464
3465void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
3466 auto *cb_access_context = GetAccessContext(commandBuffer);
3467 assert(cb_access_context);
3468 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE2KHR);
3469 auto *context = cb_access_context->GetCurrentAccessContext();
3470 assert(context);
3471
3472 auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3473 auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3474
3475 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3476 const auto &copy_region = pCopyImageInfo->pRegions[region];
3477 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003478 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3479 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003480 }
3481 if (dst_image) {
3482 VkExtent3D dst_copy_extent =
3483 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003484 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3485 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003486 }
3487 }
3488}
3489
John Zulauf9cb530d2019-09-30 14:14:10 -06003490bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3491 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3492 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3493 uint32_t bufferMemoryBarrierCount,
3494 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3495 uint32_t imageMemoryBarrierCount,
3496 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
3497 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003498 const auto *cb_access_context = GetAccessContext(commandBuffer);
3499 assert(cb_access_context);
3500 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07003501
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003502 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3503 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3504 imageMemoryBarrierCount, pImageMemoryBarriers);
3505 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06003506 return skip;
3507}
3508
3509void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3510 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3511 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3512 uint32_t bufferMemoryBarrierCount,
3513 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3514 uint32_t imageMemoryBarrierCount,
3515 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003516 auto *cb_access_context = GetAccessContext(commandBuffer);
3517 assert(cb_access_context);
3518 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06003519
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003520 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3521 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3522 imageMemoryBarrierCount, pImageMemoryBarriers);
3523 pipeline_barrier.Record(cb_access_context, cb_access_context->NextCommandTag(CMD_PIPELINEBARRIER));
John Zulauf9cb530d2019-09-30 14:14:10 -06003524}
3525
3526void SyncValidator::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
3527 const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
3528 // The state tracker sets up the device state
3529 StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result);
3530
John Zulauf5f13a792020-03-10 07:31:21 -06003531 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
3532 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06003533 // TODO: Find a good way to do this hooklessly.
3534 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
3535 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeSyncValidation);
3536 SyncValidator *sync_device_state = static_cast<SyncValidator *>(validation_data);
3537
John Zulaufd1f85d42020-04-15 12:23:15 -06003538 sync_device_state->SetCommandBufferResetCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3539 sync_device_state->ResetCommandBufferCallback(command_buffer);
3540 });
3541 sync_device_state->SetCommandBufferFreeCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3542 sync_device_state->FreeCommandBufferCallback(command_buffer);
3543 });
John Zulauf9cb530d2019-09-30 14:14:10 -06003544}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003545
John Zulauf355e49b2020-04-24 15:11:15 -06003546bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003547 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003548 bool skip = false;
3549 const auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
3550 auto cb_context = GetAccessContext(commandBuffer);
3551
3552 if (rp_state && cb_context) {
3553 skip |= cb_context->ValidateBeginRenderPass(*rp_state, pRenderPassBegin, pSubpassBeginInfo, func_name);
3554 }
3555
3556 return skip;
3557}
3558
3559bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3560 VkSubpassContents contents) const {
3561 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003562 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003563 subpass_begin_info.contents = contents;
3564 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, "vkCmdBeginRenderPass");
3565 return skip;
3566}
3567
3568bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003569 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003570 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3571 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2");
3572 return skip;
3573}
3574
3575bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3576 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003577 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003578 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3579 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2KHR");
3580 return skip;
3581}
3582
John Zulauf3d84f1b2020-03-09 13:33:25 -06003583void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
3584 VkResult result) {
3585 // The state tracker sets up the command buffer state
3586 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
3587
3588 // Create/initialize the structure that trackers accesses at the command buffer scope.
3589 auto cb_access_context = GetAccessContext(commandBuffer);
3590 assert(cb_access_context);
3591 cb_access_context->Reset();
3592}
3593
3594void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
John Zulauf355e49b2020-04-24 15:11:15 -06003595 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003596 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06003597 if (cb_context) {
3598 cb_context->RecordBeginRenderPass(cb_context->NextCommandTag(command));
John Zulauf3d84f1b2020-03-09 13:33:25 -06003599 }
3600}
3601
3602void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3603 VkSubpassContents contents) {
3604 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003605 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003606 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003607 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003608}
3609
3610void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3611 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3612 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003613 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003614}
3615
3616void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3617 const VkRenderPassBeginInfo *pRenderPassBegin,
3618 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3619 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003620 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
3621}
3622
Mike Schuchardt2df08912020-12-15 16:28:09 -08003623bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3624 const VkSubpassEndInfo *pSubpassEndInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003625 bool skip = false;
3626
3627 auto cb_context = GetAccessContext(commandBuffer);
3628 assert(cb_context);
3629 auto cb_state = cb_context->GetCommandBufferState();
3630 if (!cb_state) return skip;
3631
3632 auto rp_state = cb_state->activeRenderPass;
3633 if (!rp_state) return skip;
3634
3635 skip |= cb_context->ValidateNextSubpass(func_name);
3636
3637 return skip;
3638}
3639
3640bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
3641 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003642 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003643 subpass_begin_info.contents = contents;
3644 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, "vkCmdNextSubpass");
3645 return skip;
3646}
3647
Mike Schuchardt2df08912020-12-15 16:28:09 -08003648bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3649 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003650 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3651 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2KHR");
3652 return skip;
3653}
3654
3655bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3656 const VkSubpassEndInfo *pSubpassEndInfo) const {
3657 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3658 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2");
3659 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003660}
3661
3662void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003663 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003664 auto cb_context = GetAccessContext(commandBuffer);
3665 assert(cb_context);
3666 auto cb_state = cb_context->GetCommandBufferState();
3667 if (!cb_state) return;
3668
3669 auto rp_state = cb_state->activeRenderPass;
3670 if (!rp_state) return;
3671
John Zulauffaea0ee2021-01-14 14:01:32 -07003672 cb_context->RecordNextSubpass(*rp_state, command);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003673}
3674
3675void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
3676 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003677 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003678 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003679 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003680}
3681
3682void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3683 const VkSubpassEndInfo *pSubpassEndInfo) {
3684 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003685 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003686}
3687
3688void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3689 const VkSubpassEndInfo *pSubpassEndInfo) {
3690 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003691 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003692}
3693
Mike Schuchardt2df08912020-12-15 16:28:09 -08003694bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003695 const char *func_name) const {
3696 bool skip = false;
3697
3698 auto cb_context = GetAccessContext(commandBuffer);
3699 assert(cb_context);
3700 auto cb_state = cb_context->GetCommandBufferState();
3701 if (!cb_state) return skip;
3702
3703 auto rp_state = cb_state->activeRenderPass;
3704 if (!rp_state) return skip;
3705
3706 skip |= cb_context->ValidateEndRenderpass(func_name);
3707 return skip;
3708}
3709
3710bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3711 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
3712 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, "vkEndRenderPass");
3713 return skip;
3714}
3715
Mike Schuchardt2df08912020-12-15 16:28:09 -08003716bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003717 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3718 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2");
3719 return skip;
3720}
3721
3722bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003723 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003724 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3725 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2KHR");
3726 return skip;
3727}
3728
3729void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
3730 CMD_TYPE command) {
John Zulaufe5da6e52020-03-18 15:32:18 -06003731 // Resolve the all subpass contexts to the command buffer contexts
3732 auto cb_context = GetAccessContext(commandBuffer);
3733 assert(cb_context);
3734 auto cb_state = cb_context->GetCommandBufferState();
3735 if (!cb_state) return;
3736
locke-lunargaecf2152020-05-12 17:15:41 -06003737 const auto *rp_state = cb_state->activeRenderPass.get();
John Zulaufe5da6e52020-03-18 15:32:18 -06003738 if (!rp_state) return;
3739
John Zulauffaea0ee2021-01-14 14:01:32 -07003740 cb_context->RecordEndRenderPass(*rp_state, command);
John Zulaufe5da6e52020-03-18 15:32:18 -06003741}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003742
John Zulauf33fc1d52020-07-17 11:01:10 -06003743// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
3744// updates to a resource which do not conflict at the byte level.
3745// TODO: Revisit this rule to see if it needs to be tighter or looser
3746// TODO: Add programatic control over suppression heuristics
3747bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
3748 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
3749}
3750
John Zulauf3d84f1b2020-03-09 13:33:25 -06003751void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06003752 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06003753 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003754}
3755
3756void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003757 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003758 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003759}
3760
3761void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003762 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003763 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003764}
locke-lunarga19c71d2020-03-02 18:17:04 -07003765
Jeff Leger178b1e52020-10-05 12:22:23 -04003766template <typename BufferImageCopyRegionType>
3767bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3768 VkImageLayout dstImageLayout, uint32_t regionCount,
3769 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003770 bool skip = false;
3771 const auto *cb_access_context = GetAccessContext(commandBuffer);
3772 assert(cb_access_context);
3773 if (!cb_access_context) return skip;
3774
Jeff Leger178b1e52020-10-05 12:22:23 -04003775 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3776 const char *func_name = is_2khr ? "vkCmdCopyBufferToImage2KHR()" : "vkCmdCopyBufferToImage()";
3777
locke-lunarga19c71d2020-03-02 18:17:04 -07003778 const auto *context = cb_access_context->GetCurrentAccessContext();
3779 assert(context);
3780 if (!context) return skip;
3781
3782 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
locke-lunarga19c71d2020-03-02 18:17:04 -07003783 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
3784
3785 for (uint32_t region = 0; region < regionCount; region++) {
3786 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07003787 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07003788 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003789 if (src_buffer) {
3790 ResourceAccessRange src_range =
3791 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3792 hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3793 if (hazard.hazard) {
3794 // PHASE1 TODO -- add tag information to log msg when useful.
3795 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
3796 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3797 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003798 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003799 }
3800 }
3801
3802 hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource,
3803 copy_region.imageOffset, copy_region.imageExtent);
locke-lunarga19c71d2020-03-02 18:17:04 -07003804 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003805 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003806 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003807 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003808 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003809 }
3810 if (skip) break;
3811 }
3812 if (skip) break;
3813 }
3814 return skip;
3815}
3816
Jeff Leger178b1e52020-10-05 12:22:23 -04003817bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3818 VkImageLayout dstImageLayout, uint32_t regionCount,
3819 const VkBufferImageCopy *pRegions) const {
3820 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
3821 COPY_COMMAND_VERSION_1);
3822}
3823
3824bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3825 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
3826 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3827 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3828 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3829}
3830
3831template <typename BufferImageCopyRegionType>
3832void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3833 VkImageLayout dstImageLayout, uint32_t regionCount,
3834 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003835 auto *cb_access_context = GetAccessContext(commandBuffer);
3836 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003837
3838 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3839 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYBUFFERTOIMAGE2KHR : CMD_COPYBUFFERTOIMAGE;
3840
3841 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003842 auto *context = cb_access_context->GetCurrentAccessContext();
3843 assert(context);
3844
3845 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf16adfc92020-04-08 10:28:33 -06003846 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003847
3848 for (uint32_t region = 0; region < regionCount; region++) {
3849 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07003850 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003851 if (src_buffer) {
3852 ResourceAccessRange src_range =
3853 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3854 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
3855 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07003856 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3857 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07003858 }
3859 }
3860}
3861
Jeff Leger178b1e52020-10-05 12:22:23 -04003862void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3863 VkImageLayout dstImageLayout, uint32_t regionCount,
3864 const VkBufferImageCopy *pRegions) {
3865 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
3866 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1);
3867}
3868
3869void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3870 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
3871 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
3872 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3873 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3874 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3875}
3876
3877template <typename BufferImageCopyRegionType>
3878bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3879 VkBuffer dstBuffer, uint32_t regionCount,
3880 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003881 bool skip = false;
3882 const auto *cb_access_context = GetAccessContext(commandBuffer);
3883 assert(cb_access_context);
3884 if (!cb_access_context) return skip;
3885
Jeff Leger178b1e52020-10-05 12:22:23 -04003886 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3887 const char *func_name = is_2khr ? "vkCmdCopyImageToBuffer2KHR()" : "vkCmdCopyImageToBuffer()";
3888
locke-lunarga19c71d2020-03-02 18:17:04 -07003889 const auto *context = cb_access_context->GetCurrentAccessContext();
3890 assert(context);
3891 if (!context) return skip;
3892
3893 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3894 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3895 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
3896 for (uint32_t region = 0; region < regionCount; region++) {
3897 const auto &copy_region = pRegions[region];
3898 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003899 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07003900 copy_region.imageOffset, copy_region.imageExtent);
3901 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003902 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003903 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003904 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003905 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003906 }
John Zulauf477700e2021-01-06 11:41:49 -07003907 if (dst_mem) {
3908 ResourceAccessRange dst_range =
3909 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
3910 hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3911 if (hazard.hazard) {
3912 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
3913 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3914 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003915 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003916 }
locke-lunarga19c71d2020-03-02 18:17:04 -07003917 }
3918 }
3919 if (skip) break;
3920 }
3921 return skip;
3922}
3923
Jeff Leger178b1e52020-10-05 12:22:23 -04003924bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
3925 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
3926 const VkBufferImageCopy *pRegions) const {
3927 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
3928 COPY_COMMAND_VERSION_1);
3929}
3930
3931bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
3932 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
3933 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
3934 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
3935 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
3936}
3937
3938template <typename BufferImageCopyRegionType>
3939void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3940 VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions,
3941 CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003942 auto *cb_access_context = GetAccessContext(commandBuffer);
3943 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003944
3945 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3946 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYIMAGETOBUFFER2KHR : CMD_COPYIMAGETOBUFFER;
3947
3948 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003949 auto *context = cb_access_context->GetCurrentAccessContext();
3950 assert(context);
3951
3952 const auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003953 auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3954 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06003955 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07003956
3957 for (uint32_t region = 0; region < regionCount; region++) {
3958 const auto &copy_region = pRegions[region];
3959 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003960 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3961 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07003962 if (dst_buffer) {
3963 ResourceAccessRange dst_range =
3964 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
3965 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
3966 }
locke-lunarga19c71d2020-03-02 18:17:04 -07003967 }
3968 }
3969}
3970
Jeff Leger178b1e52020-10-05 12:22:23 -04003971void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3972 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
3973 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
3974 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1);
3975}
3976
3977void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
3978 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
3979 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
3980 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
3981 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
3982 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
3983}
3984
3985template <typename RegionType>
3986bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3987 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3988 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003989 bool skip = false;
3990 const auto *cb_access_context = GetAccessContext(commandBuffer);
3991 assert(cb_access_context);
3992 if (!cb_access_context) return skip;
3993
3994 const auto *context = cb_access_context->GetCurrentAccessContext();
3995 assert(context);
3996 if (!context) return skip;
3997
3998 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3999 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4000
4001 for (uint32_t region = 0; region < regionCount; region++) {
4002 const auto &blit_region = pRegions[region];
4003 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004004 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4005 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4006 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4007 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4008 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4009 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
4010 auto hazard =
4011 context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004012 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004013 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004014 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004015 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004016 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004017 }
4018 }
4019
4020 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004021 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4022 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4023 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4024 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4025 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4026 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
4027 auto hazard =
4028 context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004029 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004030 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004031 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004032 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004033 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004034 }
4035 if (skip) break;
4036 }
4037 }
4038
4039 return skip;
4040}
4041
Jeff Leger178b1e52020-10-05 12:22:23 -04004042bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4043 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4044 const VkImageBlit *pRegions, VkFilter filter) const {
4045 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4046 "vkCmdBlitImage");
4047}
4048
4049bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4050 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4051 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4052 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4053 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4054}
4055
4056template <typename RegionType>
4057void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4058 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4059 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004060 auto *cb_access_context = GetAccessContext(commandBuffer);
4061 assert(cb_access_context);
4062 auto *context = cb_access_context->GetCurrentAccessContext();
4063 assert(context);
4064
4065 auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004066 auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004067
4068 for (uint32_t region = 0; region < regionCount; region++) {
4069 const auto &blit_region = pRegions[region];
4070 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004071 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4072 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4073 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4074 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4075 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4076 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004077 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4078 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004079 }
4080 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004081 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4082 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4083 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4084 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4085 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4086 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004087 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4088 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004089 }
4090 }
4091}
locke-lunarg36ba2592020-04-03 09:42:04 -06004092
Jeff Leger178b1e52020-10-05 12:22:23 -04004093void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4094 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4095 const VkImageBlit *pRegions, VkFilter filter) {
4096 auto *cb_access_context = GetAccessContext(commandBuffer);
4097 assert(cb_access_context);
4098 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4099 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4100 pRegions, filter);
4101 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4102}
4103
4104void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4105 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4106 auto *cb_access_context = GetAccessContext(commandBuffer);
4107 assert(cb_access_context);
4108 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4109 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4110 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4111 pBlitImageInfo->filter, tag);
4112}
4113
John Zulauffaea0ee2021-01-14 14:01:32 -07004114bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4115 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4116 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4117 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004118 bool skip = false;
4119 if (drawCount == 0) return skip;
4120
4121 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4122 VkDeviceSize size = struct_size;
4123 if (drawCount == 1 || stride == size) {
4124 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004125 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004126 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4127 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004128 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004129 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004130 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004131 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004132 }
4133 } else {
4134 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004135 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004136 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4137 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004138 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004139 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4140 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004141 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004142 break;
4143 }
4144 }
4145 }
4146 return skip;
4147}
4148
locke-lunarg61870c22020-06-09 14:51:50 -06004149void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag &tag, const VkDeviceSize struct_size,
4150 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4151 uint32_t stride) {
locke-lunargff255f92020-05-13 18:53:52 -06004152 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4153 VkDeviceSize size = struct_size;
4154 if (drawCount == 1 || stride == size) {
4155 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004156 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004157 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004158 } else {
4159 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004160 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004161 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4162 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004163 }
4164 }
4165}
4166
John Zulauffaea0ee2021-01-14 14:01:32 -07004167bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4168 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4169 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004170 bool skip = false;
4171
4172 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004173 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004174 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4175 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004176 skip |= LogError(count_buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004177 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004178 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004179 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004180 }
4181 return skip;
4182}
4183
locke-lunarg61870c22020-06-09 14:51:50 -06004184void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag &tag, VkBuffer buffer, VkDeviceSize offset) {
locke-lunargff255f92020-05-13 18:53:52 -06004185 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004186 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004187 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004188}
4189
locke-lunarg36ba2592020-04-03 09:42:04 -06004190bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004191 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004192 const auto *cb_access_context = GetAccessContext(commandBuffer);
4193 assert(cb_access_context);
4194 if (!cb_access_context) return skip;
4195
locke-lunarg61870c22020-06-09 14:51:50 -06004196 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004197 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004198}
4199
4200void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004201 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004202 auto *cb_access_context = GetAccessContext(commandBuffer);
4203 assert(cb_access_context);
4204 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004205
locke-lunarg61870c22020-06-09 14:51:50 -06004206 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004207}
locke-lunarge1a67022020-04-29 00:15:36 -06004208
4209bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004210 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004211 const auto *cb_access_context = GetAccessContext(commandBuffer);
4212 assert(cb_access_context);
4213 if (!cb_access_context) return skip;
4214
4215 const auto *context = cb_access_context->GetCurrentAccessContext();
4216 assert(context);
4217 if (!context) return skip;
4218
locke-lunarg61870c22020-06-09 14:51:50 -06004219 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004220 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4221 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004222 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004223}
4224
4225void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004226 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004227 auto *cb_access_context = GetAccessContext(commandBuffer);
4228 assert(cb_access_context);
4229 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4230 auto *context = cb_access_context->GetCurrentAccessContext();
4231 assert(context);
4232
locke-lunarg61870c22020-06-09 14:51:50 -06004233 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4234 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004235}
4236
4237bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4238 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004239 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004240 const auto *cb_access_context = GetAccessContext(commandBuffer);
4241 assert(cb_access_context);
4242 if (!cb_access_context) return skip;
4243
locke-lunarg61870c22020-06-09 14:51:50 -06004244 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4245 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4246 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004247 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004248}
4249
4250void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4251 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004252 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004253 auto *cb_access_context = GetAccessContext(commandBuffer);
4254 assert(cb_access_context);
4255 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004256
locke-lunarg61870c22020-06-09 14:51:50 -06004257 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4258 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4259 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004260}
4261
4262bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4263 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004264 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004265 const auto *cb_access_context = GetAccessContext(commandBuffer);
4266 assert(cb_access_context);
4267 if (!cb_access_context) return skip;
4268
locke-lunarg61870c22020-06-09 14:51:50 -06004269 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4270 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4271 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004272 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004273}
4274
4275void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4276 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004277 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004278 auto *cb_access_context = GetAccessContext(commandBuffer);
4279 assert(cb_access_context);
4280 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004281
locke-lunarg61870c22020-06-09 14:51:50 -06004282 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4283 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4284 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004285}
4286
4287bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4288 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004289 bool skip = false;
4290 if (drawCount == 0) return skip;
4291
locke-lunargff255f92020-05-13 18:53:52 -06004292 const auto *cb_access_context = GetAccessContext(commandBuffer);
4293 assert(cb_access_context);
4294 if (!cb_access_context) return skip;
4295
4296 const auto *context = cb_access_context->GetCurrentAccessContext();
4297 assert(context);
4298 if (!context) return skip;
4299
locke-lunarg61870c22020-06-09 14:51:50 -06004300 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4301 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004302 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4303 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004304
4305 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4306 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4307 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004308 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004309 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004310}
4311
4312void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4313 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004314 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004315 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06004316 auto *cb_access_context = GetAccessContext(commandBuffer);
4317 assert(cb_access_context);
4318 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
4319 auto *context = cb_access_context->GetCurrentAccessContext();
4320 assert(context);
4321
locke-lunarg61870c22020-06-09 14:51:50 -06004322 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4323 cb_access_context->RecordDrawSubpassAttachment(tag);
4324 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004325
4326 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4327 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4328 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004329 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004330}
4331
4332bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4333 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004334 bool skip = false;
4335 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06004336 const auto *cb_access_context = GetAccessContext(commandBuffer);
4337 assert(cb_access_context);
4338 if (!cb_access_context) return skip;
4339
4340 const auto *context = cb_access_context->GetCurrentAccessContext();
4341 assert(context);
4342 if (!context) return skip;
4343
locke-lunarg61870c22020-06-09 14:51:50 -06004344 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
4345 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004346 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4347 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004348
4349 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4350 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4351 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004352 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004353 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004354}
4355
4356void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4357 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004358 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004359 auto *cb_access_context = GetAccessContext(commandBuffer);
4360 assert(cb_access_context);
4361 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
4362 auto *context = cb_access_context->GetCurrentAccessContext();
4363 assert(context);
4364
locke-lunarg61870c22020-06-09 14:51:50 -06004365 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4366 cb_access_context->RecordDrawSubpassAttachment(tag);
4367 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004368
4369 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4370 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4371 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004372 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004373}
4374
4375bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4376 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4377 uint32_t stride, const char *function) const {
4378 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004379 const auto *cb_access_context = GetAccessContext(commandBuffer);
4380 assert(cb_access_context);
4381 if (!cb_access_context) return skip;
4382
4383 const auto *context = cb_access_context->GetCurrentAccessContext();
4384 assert(context);
4385 if (!context) return skip;
4386
locke-lunarg61870c22020-06-09 14:51:50 -06004387 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4388 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004389 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4390 maxDrawCount, stride, function);
4391 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004392
4393 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4394 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4395 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004396 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004397 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004398}
4399
4400bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4401 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4402 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004403 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4404 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004405}
4406
4407void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4408 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4409 uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004410 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4411 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004412 auto *cb_access_context = GetAccessContext(commandBuffer);
4413 assert(cb_access_context);
4414 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECTCOUNT);
4415 auto *context = cb_access_context->GetCurrentAccessContext();
4416 assert(context);
4417
locke-lunarg61870c22020-06-09 14:51:50 -06004418 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4419 cb_access_context->RecordDrawSubpassAttachment(tag);
4420 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
4421 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004422
4423 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4424 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4425 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004426 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004427}
4428
4429bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4430 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4431 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004432 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4433 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004434}
4435
4436void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4437 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4438 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004439 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4440 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004441 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004442}
4443
4444bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4445 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4446 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004447 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4448 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004449}
4450
4451void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4452 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4453 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004454 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4455 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004456 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4457}
4458
4459bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4460 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4461 uint32_t stride, const char *function) const {
4462 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004463 const auto *cb_access_context = GetAccessContext(commandBuffer);
4464 assert(cb_access_context);
4465 if (!cb_access_context) return skip;
4466
4467 const auto *context = cb_access_context->GetCurrentAccessContext();
4468 assert(context);
4469 if (!context) return skip;
4470
locke-lunarg61870c22020-06-09 14:51:50 -06004471 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4472 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004473 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4474 offset, maxDrawCount, stride, function);
4475 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004476
4477 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4478 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4479 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004480 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004481 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004482}
4483
4484bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4485 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4486 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004487 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4488 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004489}
4490
4491void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4492 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4493 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004494 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4495 maxDrawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004496 auto *cb_access_context = GetAccessContext(commandBuffer);
4497 assert(cb_access_context);
4498 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECTCOUNT);
4499 auto *context = cb_access_context->GetCurrentAccessContext();
4500 assert(context);
4501
locke-lunarg61870c22020-06-09 14:51:50 -06004502 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4503 cb_access_context->RecordDrawSubpassAttachment(tag);
4504 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
4505 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004506
4507 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4508 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06004509 // We will update the index and vertex buffer in SubmitQueue in the future.
4510 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004511}
4512
4513bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
4514 VkDeviceSize offset, VkBuffer countBuffer,
4515 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4516 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004517 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4518 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004519}
4520
4521void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4522 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4523 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004524 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4525 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004526 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4527}
4528
4529bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
4530 VkDeviceSize offset, VkBuffer countBuffer,
4531 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4532 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004533 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4534 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004535}
4536
4537void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4538 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4539 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004540 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4541 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004542 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4543}
4544
4545bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4546 const VkClearColorValue *pColor, uint32_t rangeCount,
4547 const VkImageSubresourceRange *pRanges) const {
4548 bool skip = false;
4549 const auto *cb_access_context = GetAccessContext(commandBuffer);
4550 assert(cb_access_context);
4551 if (!cb_access_context) return skip;
4552
4553 const auto *context = cb_access_context->GetCurrentAccessContext();
4554 assert(context);
4555 if (!context) return skip;
4556
4557 const auto *image_state = Get<IMAGE_STATE>(image);
4558
4559 for (uint32_t index = 0; index < rangeCount; index++) {
4560 const auto &range = pRanges[index];
4561 if (image_state) {
4562 auto hazard =
4563 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4564 if (hazard.hazard) {
4565 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004566 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004567 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004568 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004569 }
4570 }
4571 }
4572 return skip;
4573}
4574
4575void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4576 const VkClearColorValue *pColor, uint32_t rangeCount,
4577 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004578 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004579 auto *cb_access_context = GetAccessContext(commandBuffer);
4580 assert(cb_access_context);
4581 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
4582 auto *context = cb_access_context->GetCurrentAccessContext();
4583 assert(context);
4584
4585 const auto *image_state = Get<IMAGE_STATE>(image);
4586
4587 for (uint32_t index = 0; index < rangeCount; index++) {
4588 const auto &range = pRanges[index];
4589 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004590 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4591 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004592 }
4593 }
4594}
4595
4596bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4597 VkImageLayout imageLayout,
4598 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4599 const VkImageSubresourceRange *pRanges) const {
4600 bool skip = false;
4601 const auto *cb_access_context = GetAccessContext(commandBuffer);
4602 assert(cb_access_context);
4603 if (!cb_access_context) return skip;
4604
4605 const auto *context = cb_access_context->GetCurrentAccessContext();
4606 assert(context);
4607 if (!context) return skip;
4608
4609 const auto *image_state = Get<IMAGE_STATE>(image);
4610
4611 for (uint32_t index = 0; index < rangeCount; index++) {
4612 const auto &range = pRanges[index];
4613 if (image_state) {
4614 auto hazard =
4615 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4616 if (hazard.hazard) {
4617 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004618 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004619 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004620 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004621 }
4622 }
4623 }
4624 return skip;
4625}
4626
4627void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4628 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4629 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004630 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004631 auto *cb_access_context = GetAccessContext(commandBuffer);
4632 assert(cb_access_context);
4633 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
4634 auto *context = cb_access_context->GetCurrentAccessContext();
4635 assert(context);
4636
4637 const auto *image_state = Get<IMAGE_STATE>(image);
4638
4639 for (uint32_t index = 0; index < rangeCount; index++) {
4640 const auto &range = pRanges[index];
4641 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004642 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4643 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004644 }
4645 }
4646}
4647
4648bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
4649 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
4650 VkDeviceSize dstOffset, VkDeviceSize stride,
4651 VkQueryResultFlags flags) const {
4652 bool skip = false;
4653 const auto *cb_access_context = GetAccessContext(commandBuffer);
4654 assert(cb_access_context);
4655 if (!cb_access_context) return skip;
4656
4657 const auto *context = cb_access_context->GetCurrentAccessContext();
4658 assert(context);
4659 if (!context) return skip;
4660
4661 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4662
4663 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004664 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
locke-lunarge1a67022020-04-29 00:15:36 -06004665 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4666 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004667 skip |=
4668 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4669 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004670 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004671 }
4672 }
locke-lunargff255f92020-05-13 18:53:52 -06004673
4674 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004675 return skip;
4676}
4677
4678void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
4679 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4680 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004681 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
4682 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06004683 auto *cb_access_context = GetAccessContext(commandBuffer);
4684 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06004685 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06004686 auto *context = cb_access_context->GetCurrentAccessContext();
4687 assert(context);
4688
4689 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4690
4691 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004692 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004693 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004694 }
locke-lunargff255f92020-05-13 18:53:52 -06004695
4696 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004697}
4698
4699bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4700 VkDeviceSize size, uint32_t data) const {
4701 bool skip = false;
4702 const auto *cb_access_context = GetAccessContext(commandBuffer);
4703 assert(cb_access_context);
4704 if (!cb_access_context) return skip;
4705
4706 const auto *context = cb_access_context->GetCurrentAccessContext();
4707 assert(context);
4708 if (!context) return skip;
4709
4710 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4711
4712 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004713 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
locke-lunarge1a67022020-04-29 00:15:36 -06004714 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4715 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004716 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004717 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004718 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004719 }
4720 }
4721 return skip;
4722}
4723
4724void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4725 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004726 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06004727 auto *cb_access_context = GetAccessContext(commandBuffer);
4728 assert(cb_access_context);
4729 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
4730 auto *context = cb_access_context->GetCurrentAccessContext();
4731 assert(context);
4732
4733 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4734
4735 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004736 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004737 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004738 }
4739}
4740
4741bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4742 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4743 const VkImageResolve *pRegions) const {
4744 bool skip = false;
4745 const auto *cb_access_context = GetAccessContext(commandBuffer);
4746 assert(cb_access_context);
4747 if (!cb_access_context) return skip;
4748
4749 const auto *context = cb_access_context->GetCurrentAccessContext();
4750 assert(context);
4751 if (!context) return skip;
4752
4753 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4754 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4755
4756 for (uint32_t region = 0; region < regionCount; region++) {
4757 const auto &resolve_region = pRegions[region];
4758 if (src_image) {
4759 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4760 resolve_region.srcOffset, resolve_region.extent);
4761 if (hazard.hazard) {
4762 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004763 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004764 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004765 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004766 }
4767 }
4768
4769 if (dst_image) {
4770 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4771 resolve_region.dstOffset, resolve_region.extent);
4772 if (hazard.hazard) {
4773 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004774 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004775 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004776 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004777 }
4778 if (skip) break;
4779 }
4780 }
4781
4782 return skip;
4783}
4784
4785void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4786 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4787 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004788 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4789 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06004790 auto *cb_access_context = GetAccessContext(commandBuffer);
4791 assert(cb_access_context);
4792 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
4793 auto *context = cb_access_context->GetCurrentAccessContext();
4794 assert(context);
4795
4796 auto *src_image = Get<IMAGE_STATE>(srcImage);
4797 auto *dst_image = Get<IMAGE_STATE>(dstImage);
4798
4799 for (uint32_t region = 0; region < regionCount; region++) {
4800 const auto &resolve_region = pRegions[region];
4801 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004802 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4803 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004804 }
4805 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004806 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4807 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004808 }
4809 }
4810}
4811
Jeff Leger178b1e52020-10-05 12:22:23 -04004812bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4813 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
4814 bool skip = false;
4815 const auto *cb_access_context = GetAccessContext(commandBuffer);
4816 assert(cb_access_context);
4817 if (!cb_access_context) return skip;
4818
4819 const auto *context = cb_access_context->GetCurrentAccessContext();
4820 assert(context);
4821 if (!context) return skip;
4822
4823 const auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4824 const auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4825
4826 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4827 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4828 if (src_image) {
4829 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4830 resolve_region.srcOffset, resolve_region.extent);
4831 if (hazard.hazard) {
4832 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
4833 "vkCmdResolveImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
4834 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004835 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004836 }
4837 }
4838
4839 if (dst_image) {
4840 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4841 resolve_region.dstOffset, resolve_region.extent);
4842 if (hazard.hazard) {
4843 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
4844 "vkCmdResolveImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
4845 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004846 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004847 }
4848 if (skip) break;
4849 }
4850 }
4851
4852 return skip;
4853}
4854
4855void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4856 const VkResolveImageInfo2KHR *pResolveImageInfo) {
4857 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
4858 auto *cb_access_context = GetAccessContext(commandBuffer);
4859 assert(cb_access_context);
4860 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE2KHR);
4861 auto *context = cb_access_context->GetCurrentAccessContext();
4862 assert(context);
4863
4864 auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4865 auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4866
4867 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4868 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4869 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004870 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4871 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004872 }
4873 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004874 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4875 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004876 }
4877 }
4878}
4879
locke-lunarge1a67022020-04-29 00:15:36 -06004880bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4881 VkDeviceSize dataSize, const void *pData) const {
4882 bool skip = false;
4883 const auto *cb_access_context = GetAccessContext(commandBuffer);
4884 assert(cb_access_context);
4885 if (!cb_access_context) return skip;
4886
4887 const auto *context = cb_access_context->GetCurrentAccessContext();
4888 assert(context);
4889 if (!context) return skip;
4890
4891 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4892
4893 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004894 // VK_WHOLE_SIZE not allowed
4895 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
locke-lunarge1a67022020-04-29 00:15:36 -06004896 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4897 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004898 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004899 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004900 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004901 }
4902 }
4903 return skip;
4904}
4905
4906void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4907 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004908 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06004909 auto *cb_access_context = GetAccessContext(commandBuffer);
4910 assert(cb_access_context);
4911 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
4912 auto *context = cb_access_context->GetCurrentAccessContext();
4913 assert(context);
4914
4915 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4916
4917 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004918 // VK_WHOLE_SIZE not allowed
4919 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004920 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004921 }
4922}
locke-lunargff255f92020-05-13 18:53:52 -06004923
4924bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4925 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
4926 bool skip = false;
4927 const auto *cb_access_context = GetAccessContext(commandBuffer);
4928 assert(cb_access_context);
4929 if (!cb_access_context) return skip;
4930
4931 const auto *context = cb_access_context->GetCurrentAccessContext();
4932 assert(context);
4933 if (!context) return skip;
4934
4935 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4936
4937 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004938 const ResourceAccessRange range = MakeRange(dstOffset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004939 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4940 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004941 skip |=
4942 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4943 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004944 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004945 }
4946 }
4947 return skip;
4948}
4949
4950void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4951 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004952 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06004953 auto *cb_access_context = GetAccessContext(commandBuffer);
4954 assert(cb_access_context);
4955 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
4956 auto *context = cb_access_context->GetCurrentAccessContext();
4957 assert(context);
4958
4959 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4960
4961 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004962 const ResourceAccessRange range = MakeRange(dstOffset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004963 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004964 }
4965}
John Zulauf49beb112020-11-04 16:06:31 -07004966
4967bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
4968 bool skip = false;
4969 const auto *cb_context = GetAccessContext(commandBuffer);
4970 assert(cb_context);
4971 if (!cb_context) return skip;
4972
4973 return cb_context->ValidateSetEvent(commandBuffer, event, stageMask);
4974}
4975
4976void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
4977 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
4978 auto *cb_context = GetAccessContext(commandBuffer);
4979 assert(cb_context);
4980 if (!cb_context) return;
John Zulauf4a6105a2020-11-17 15:11:05 -07004981 const auto tag = cb_context->NextCommandTag(CMD_SETEVENT);
4982 cb_context->RecordSetEvent(commandBuffer, event, stageMask, tag);
John Zulauf49beb112020-11-04 16:06:31 -07004983}
4984
4985bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
4986 VkPipelineStageFlags stageMask) const {
4987 bool skip = false;
4988 const auto *cb_context = GetAccessContext(commandBuffer);
4989 assert(cb_context);
4990 if (!cb_context) return skip;
4991
4992 return cb_context->ValidateResetEvent(commandBuffer, event, stageMask);
4993}
4994
4995void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
4996 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
4997 auto *cb_context = GetAccessContext(commandBuffer);
4998 assert(cb_context);
4999 if (!cb_context) return;
5000
5001 cb_context->RecordResetEvent(commandBuffer, event, stageMask);
5002}
5003
5004bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5005 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5006 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5007 uint32_t bufferMemoryBarrierCount,
5008 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5009 uint32_t imageMemoryBarrierCount,
5010 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5011 bool skip = false;
5012 const auto *cb_context = GetAccessContext(commandBuffer);
5013 assert(cb_context);
5014 if (!cb_context) return skip;
5015
John Zulauf669dfd52021-01-27 17:15:28 -07005016 SyncOpWaitEvents wait_events_op(*this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
John Zulaufd5115702021-01-18 12:34:33 -07005017 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5018 imageMemoryBarrierCount, pImageMemoryBarriers);
5019 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005020}
5021
5022void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5023 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5024 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5025 uint32_t bufferMemoryBarrierCount,
5026 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5027 uint32_t imageMemoryBarrierCount,
5028 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5029 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5030 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5031 imageMemoryBarrierCount, pImageMemoryBarriers);
5032
5033 auto *cb_context = GetAccessContext(commandBuffer);
5034 assert(cb_context);
5035 if (!cb_context) return;
5036
John Zulauf4a6105a2020-11-17 15:11:05 -07005037 const auto tag = cb_context->NextCommandTag(CMD_WAITEVENTS);
John Zulauf669dfd52021-01-27 17:15:28 -07005038 SyncOpWaitEvents wait_events_op(*this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
John Zulaufd5115702021-01-18 12:34:33 -07005039 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5040 imageMemoryBarrierCount, pImageMemoryBarriers);
5041 return wait_events_op.Record(cb_context, tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07005042}
5043
5044void SyncEventState::ResetFirstScope() {
5045 for (const auto address_type : kAddressTypes) {
5046 first_scope[static_cast<size_t>(address_type)].clear();
5047 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005048 scope = SyncExecScope();
John Zulauf4a6105a2020-11-17 15:11:05 -07005049}
5050
5051// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
5052SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(VkPipelineStageFlags srcStageMask) const {
5053 IgnoreReason reason = NotIgnored;
5054
5055 if (last_command == CMD_RESETEVENT && !HasBarrier(0U, 0U)) {
5056 reason = ResetWaitRace;
5057 } else if (unsynchronized_set) {
5058 reason = SetRace;
5059 } else {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005060 const VkPipelineStageFlags missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005061 if (missing_bits) reason = MissingStageBits;
5062 }
5063
5064 return reason;
5065}
5066
5067bool SyncEventState::HasBarrier(VkPipelineStageFlags stageMask, VkPipelineStageFlags exec_scope_arg) const {
5068 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5069 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5070 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005071}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005072
John Zulaufd5115702021-01-18 12:34:33 -07005073SyncOpBarriers::SyncOpBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags, VkPipelineStageFlags srcStageMask,
5074 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5075 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5076 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5077 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005078 : dependency_flags_(dependencyFlags),
5079 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, srcStageMask)),
5080 dst_exec_scope_(SyncExecScope::MakeDst(queue_flags, dstStageMask)) {
5081 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5082 MakeMemoryBarriers(src_exec_scope_, dst_exec_scope_, dependencyFlags, memoryBarrierCount, pMemoryBarriers);
5083 MakeBufferMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, bufferMemoryBarrierCount,
5084 pBufferMemoryBarriers);
5085 MakeImageMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, imageMemoryBarrierCount,
5086 pImageMemoryBarriers);
5087}
5088
John Zulaufd5115702021-01-18 12:34:33 -07005089SyncOpPipelineBarrier::SyncOpPipelineBarrier(const SyncValidator &sync_state, VkQueueFlags queue_flags,
5090 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5091 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5092 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5093 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5094 const VkImageMemoryBarrier *pImageMemoryBarriers)
5095 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
5096 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5097
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005098bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
5099 bool skip = false;
5100 const auto *context = cb_context.GetCurrentAccessContext();
5101 assert(context);
5102 if (!context) return skip;
5103 // Validate Image Layout transitions
Nathaniel Cesarioe3025c62021-02-03 16:36:22 -07005104 for (const auto &image_barrier : image_memory_barriers_) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005105 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
5106 const auto *image_state = image_barrier.image.get();
5107 if (!image_state) continue;
5108 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
5109 if (hazard.hazard) {
5110 // PHASE1 TODO -- add tag information to log msg when useful.
5111 const auto &sync_state = cb_context.GetSyncState();
5112 const auto image_handle = image_state->image;
5113 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
5114 "vkCmdPipelineBarrier: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.",
5115 string_SyncHazard(hazard.hazard), image_barrier.index,
5116 sync_state.report_data->FormatHandle(image_handle).c_str(),
5117 cb_context.FormatUsage(hazard).c_str());
5118 }
5119 }
5120
5121 return skip;
5122}
5123
John Zulaufd5115702021-01-18 12:34:33 -07005124struct SyncOpPipelineBarrierFunctorFactory {
5125 using BarrierOpFunctor = PipelineBarrierOp;
5126 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5127 using GlobalBarrierOpFunctor = PipelineBarrierOp;
5128 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5129 using BufferRange = ResourceAccessRange;
5130 using ImageRange = subresource_adapter::ImageRangeGenerator;
5131 using GlobalRange = ResourceAccessRange;
5132
5133 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier, bool layout_transition) const {
5134 return ApplyFunctor(BarrierOpFunctor(barrier, layout_transition));
5135 }
5136 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5137 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
5138 }
5139 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier) const {
5140 return GlobalBarrierOpFunctor(barrier, false);
5141 }
5142
5143 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
5144 if (!SimpleBinding(buffer)) return ResourceAccessRange();
5145 const auto base_address = ResourceBaseAddress(buffer);
5146 return (range + base_address);
5147 }
5148 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
John Zulauf264cce02021-02-05 14:40:47 -07005149 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07005150
5151 const auto base_address = ResourceBaseAddress(image);
5152 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), range.subresource_range, range.offset,
5153 range.extent, base_address);
5154 return range_gen;
5155 }
5156 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
5157};
5158
5159template <typename Barriers, typename FunctorFactory>
5160void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5161 AccessContext *context) {
5162 for (const auto &barrier : barriers) {
5163 const auto *state = barrier.GetState();
5164 if (state) {
5165 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
5166 auto update_action = factory.MakeApplyFunctor(barrier.barrier, barrier.IsLayoutTransition());
5167 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
5168 UpdateMemoryAccessState(accesses, update_action, &range_gen);
5169 }
5170 }
5171}
5172
5173template <typename Barriers, typename FunctorFactory>
5174void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5175 AccessContext *access_context) {
5176 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
5177 for (const auto &barrier : barriers) {
5178 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(barrier));
5179 }
5180 for (const auto address_type : kAddressTypes) {
5181 auto range_gen = factory.MakeGlobalRangeGen(address_type);
5182 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
5183 }
5184}
5185
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005186void SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07005187 SyncOpPipelineBarrierFunctorFactory factory;
5188 auto *access_context = cb_context->GetCurrentAccessContext();
5189 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5190 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5191 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005192
5193 cb_context->ApplyGlobalBarriersToEvents(src_exec_scope_, dst_exec_scope_);
5194}
5195
John Zulaufd5115702021-01-18 12:34:33 -07005196void SyncOpBarriers::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst, VkDependencyFlags dependency_flags,
5197 uint32_t memory_barrier_count, const VkMemoryBarrier *memory_barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005198 memory_barriers_.reserve(std::min<uint32_t>(1, memory_barrier_count));
5199 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
5200 const auto &barrier = memory_barriers[barrier_index];
5201 SyncBarrier sync_barrier(barrier, src, dst);
5202 memory_barriers_.emplace_back(sync_barrier);
5203 }
5204 if (0 == memory_barrier_count) {
5205 // If there are no global memory barriers, force an exec barrier
5206 memory_barriers_.emplace_back(SyncBarrier(src, dst));
5207 }
5208}
5209
John Zulaufd5115702021-01-18 12:34:33 -07005210void SyncOpBarriers::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5211 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5212 const VkBufferMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005213 buffer_memory_barriers_.reserve(barrier_count);
5214 for (uint32_t index = 0; index < barrier_count; index++) {
5215 const auto &barrier = barriers[index];
5216 auto buffer = sync_state.GetShared<BUFFER_STATE>(barrier.buffer);
5217 if (buffer) {
5218 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
5219 const auto range = MakeRange(barrier.offset, barrier_size);
5220 const SyncBarrier sync_barrier(barrier, src, dst);
5221 buffer_memory_barriers_.emplace_back(buffer, sync_barrier, range);
5222 } else {
5223 buffer_memory_barriers_.emplace_back();
5224 }
5225 }
5226}
5227
John Zulaufd5115702021-01-18 12:34:33 -07005228void SyncOpBarriers::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5229 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5230 const VkImageMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005231 image_memory_barriers_.reserve(barrier_count);
5232 for (uint32_t index = 0; index < barrier_count; index++) {
5233 const auto &barrier = barriers[index];
5234 const auto image = sync_state.GetShared<IMAGE_STATE>(barrier.image);
5235 if (image) {
5236 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
5237 const SyncBarrier sync_barrier(barrier, src, dst);
5238 image_memory_barriers_.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout,
5239 subresource_range);
5240 } else {
5241 image_memory_barriers_.emplace_back();
5242 image_memory_barriers_.back().index = index; // Just in case we're interested in the ones we skipped.
5243 }
5244 }
5245}
John Zulaufd5115702021-01-18 12:34:33 -07005246
John Zulauf669dfd52021-01-27 17:15:28 -07005247SyncOpWaitEvents::SyncOpWaitEvents(const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
John Zulaufd5115702021-01-18 12:34:33 -07005248 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5249 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5250 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5251 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf669dfd52021-01-27 17:15:28 -07005252 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005253 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
5254 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07005255 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07005256}
5257
5258bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
5259 const auto cmd = CMD_WAITEVENTS;
5260 const char *const ignored = "Wait operation is ignored for this event.";
5261 bool skip = false;
5262 const auto &sync_state = cb_context.GetSyncState();
5263 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer;
5264
5265 if (src_exec_scope_.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
5266 const char *const cmd_name = CommandTypeString(cmd);
5267 const char *const vuid = "SYNC-vkCmdWaitEvents-hostevent-unsupported";
5268 skip = sync_state.LogInfo(command_buffer_handle, vuid,
5269 "%s, srcStageMask includes %s, unsupported by synchronization validaton.", cmd_name,
5270 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT), ignored);
5271 }
5272
5273 VkPipelineStageFlags event_stage_masks = 0U;
5274 bool events_not_found = false;
John Zulauf669dfd52021-01-27 17:15:28 -07005275 const auto *events_context = cb_context.GetCurrentEventsContext();
5276 assert(events_context);
5277 for (const auto &sync_event_pair : *events_context) {
5278 const auto *sync_event = sync_event_pair.second.get();
John Zulaufd5115702021-01-18 12:34:33 -07005279 if (!sync_event) {
5280 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
John Zulauf669dfd52021-01-27 17:15:28 -07005281 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
5282 // new validation error... wait without previously submitted set event...
5283 events_not_found = true; // Demote "extra_stage_bits" error to warning, to avoid false positives at *record time*
John Zulaufd5115702021-01-18 12:34:33 -07005284
5285 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
5286 }
5287 const auto event = sync_event->event->event;
5288 // TODO add "destroyed" checks
5289
5290 event_stage_masks |= sync_event->scope.mask_param;
5291 const auto ignore_reason = sync_event->IsIgnoredByWait(src_exec_scope_.mask_param);
5292 if (ignore_reason) {
5293 switch (ignore_reason) {
5294 case SyncEventState::ResetWaitRace: {
5295 const char *const cmd_name = CommandTypeString(cmd);
5296 const char *const vuid = "SYNC-vkCmdWaitEvents-missingbarrier-reset";
5297 const char *const message =
5298 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
5299 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5300 cmd_name, CommandTypeString(sync_event->last_command), ignored);
5301 break;
5302 }
5303 case SyncEventState::SetRace: {
5304 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for this
5305 // event
5306 const char *const cmd_name = CommandTypeString(cmd);
5307 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
5308 const char *const message =
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07005309 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
John Zulaufd5115702021-01-18 12:34:33 -07005310 const char *const reason = "First synchronization scope is undefined.";
5311 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5312 CommandTypeString(sync_event->last_command), reason, ignored);
5313 break;
5314 }
5315 case SyncEventState::MissingStageBits: {
5316 const VkPipelineStageFlags missing_bits = sync_event->scope.mask_param & ~src_exec_scope_.mask_param;
5317 // Issue error message that event waited for is not in wait events scope
5318 const char *const cmd_name = CommandTypeString(cmd);
5319 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5320 const char *const message =
5321 "%s: %s stageMask 0x%" PRIx32 " includes bits not present in srcStageMask 0x%" PRIx32
5322 ". Bits missing from srcStageMask %s. %s";
5323 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5324 sync_event->scope.mask_param, src_exec_scope_.mask_param,
5325 string_VkPipelineStageFlags(missing_bits).c_str(), ignored);
5326 break;
5327 }
5328 default:
5329 assert(ignore_reason == SyncEventState::NotIgnored);
5330 }
5331 } else if (image_memory_barriers_.size()) {
5332 const auto *context = cb_context.GetCurrentAccessContext();
5333 assert(context);
5334 for (const auto &image_memory_barrier : image_memory_barriers_) {
5335 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
5336 const auto *image_state = image_memory_barrier.image.get();
5337 if (!image_state) continue;
5338 const auto &subresource_range = image_memory_barrier.range.subresource_range;
5339 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
5340 const auto hazard =
5341 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
5342 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
5343 if (hazard.hazard) {
5344 const char *const cmd_name = CommandTypeString(cmd);
5345 skip |= sync_state.LogError(image_state->image, string_SyncHazardVUID(hazard.hazard),
5346 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", cmd_name,
5347 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
5348 sync_state.report_data->FormatHandle(image_state->image).c_str(),
5349 cb_context.FormatUsage(hazard).c_str());
5350 break;
5351 }
5352 }
5353 }
5354 }
5355
5356 // Note that we can't check for HOST in pEvents as we don't track that set event type
5357 const auto extra_stage_bits = (src_exec_scope_.mask_param & ~VK_PIPELINE_STAGE_HOST_BIT) & ~event_stage_masks;
5358 if (extra_stage_bits) {
5359 // Issue error message that event waited for is not in wait events scope
5360 const char *const cmd_name = CommandTypeString(cmd);
5361 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5362 const char *const message =
5363 "%s: srcStageMask 0x%" PRIx32 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
5364 if (events_not_found) {
5365 skip |= sync_state.LogInfo(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5366 string_VkPipelineStageFlags(extra_stage_bits).c_str(),
5367 " vkCmdSetEvent may be in previously submitted command buffer.");
5368 } else {
5369 skip |= sync_state.LogError(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5370 string_VkPipelineStageFlags(extra_stage_bits).c_str(), "");
5371 }
5372 }
5373 return skip;
5374}
5375
5376struct SyncOpWaitEventsFunctorFactory {
5377 using BarrierOpFunctor = WaitEventBarrierOp;
5378 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5379 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
5380 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5381 using BufferRange = EventSimpleRangeGenerator;
5382 using ImageRange = EventImageRangeGenerator;
5383 using GlobalRange = EventSimpleRangeGenerator;
5384
5385 // Need to restrict to only valid exec and access scope for this event
5386 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
5387 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
5388 barrier.src_exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope;
5389 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
5390 return barrier;
5391 }
5392 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier_arg, bool layout_transition) const {
5393 auto barrier = RestrictToEvent(barrier_arg);
5394 return ApplyFunctor(BarrierOpFunctor(sync_event->first_scope_tag, barrier, layout_transition));
5395 }
5396 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5397 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
5398 }
5399 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier_arg) const {
5400 auto barrier = RestrictToEvent(barrier_arg);
5401 return GlobalBarrierOpFunctor(sync_event->first_scope_tag, barrier, false);
5402 }
5403
5404 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
5405 const AccessAddressType address_type = GetAccessAddressType(buffer);
5406 const auto base_address = ResourceBaseAddress(buffer);
5407 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
5408 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
5409 return filtered_range_gen;
5410 }
5411 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5412 if (!SimpleBinding(image)) return ImageRange();
5413 const auto address_type = GetAccessAddressType(image);
5414 const auto base_address = ResourceBaseAddress(image);
5415 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), range.subresource_range,
5416 range.offset, range.extent, base_address);
5417 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
5418
5419 return filtered_range_gen;
5420 }
5421 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
5422 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
5423 }
5424 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
5425 SyncEventState *sync_event;
5426};
5427
5428void SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
5429 auto *access_context = cb_context->GetCurrentAccessContext();
5430 assert(access_context);
5431 if (!access_context) return;
John Zulauf669dfd52021-01-27 17:15:28 -07005432 auto *events_context = cb_context->GetCurrentEventsContext();
5433 assert(events_context);
5434 if (!events_context) return;
John Zulaufd5115702021-01-18 12:34:33 -07005435
5436 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
5437 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
5438 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
5439 access_context->ResolvePreviousAccesses();
5440
5441 const auto &dst = dst_exec_scope_;
5442 // TODO... this needs change the SyncEventContext it's using depending on whether this is replay... the recorded
5443 // sync_event will be in the recorded context, but we need to update the sync_events in the current context....
John Zulauf669dfd52021-01-27 17:15:28 -07005444 for (auto &event_shared : events_) {
5445 if (!event_shared.get()) continue;
5446 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07005447
5448 sync_event->last_command = CMD_WAITEVENTS;
5449
5450 if (!sync_event->IsIgnoredByWait(src_exec_scope_.mask_param)) {
5451 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
5452 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
5453 // of the barriers is maintained.
5454 SyncOpWaitEventsFunctorFactory factory(sync_event);
5455 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5456 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5457 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
5458
5459 // Apply the global barrier to the event itself (for race condition tracking)
5460 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
5461 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
5462 sync_event->barriers |= dst.exec_scope;
5463 } else {
5464 // We ignored this wait, so we don't have any effective synchronization barriers for it.
5465 sync_event->barriers = 0U;
5466 }
5467 }
5468
5469 // Apply the pending barriers
5470 ResolvePendingBarrierFunctor apply_pending_action(tag);
5471 access_context->ApplyToContext(apply_pending_action);
5472}
5473
John Zulauf669dfd52021-01-27 17:15:28 -07005474void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07005475 events_.reserve(event_count);
5476 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
John Zulauf669dfd52021-01-27 17:15:28 -07005477 events_.emplace_back(sync_state.GetShared<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07005478 }
5479}