blob: 5b0460d98989487ce82443fa869c43a91fa96db5 [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 Zulauf43cc7462020-12-03 12:33:12 -070029const static std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
30 AccessAddressType::kLinear, AccessAddressType::kIdealized};
31
John Zulaufd5115702021-01-18 12:34:33 -070032static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
33static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) { return AccessContext::ImageAddressType(image); }
34
John Zulauf9cb530d2019-09-30 14:14:10 -060035static const char *string_SyncHazardVUID(SyncHazard hazard) {
36 switch (hazard) {
37 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070038 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060039 break;
40 case SyncHazard::READ_AFTER_WRITE:
41 return "SYNC-HAZARD-READ_AFTER_WRITE";
42 break;
43 case SyncHazard::WRITE_AFTER_READ:
44 return "SYNC-HAZARD-WRITE_AFTER_READ";
45 break;
46 case SyncHazard::WRITE_AFTER_WRITE:
47 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
48 break;
John Zulauf2f952d22020-02-10 11:34:51 -070049 case SyncHazard::READ_RACING_WRITE:
50 return "SYNC-HAZARD-READ-RACING-WRITE";
51 break;
52 case SyncHazard::WRITE_RACING_WRITE:
53 return "SYNC-HAZARD-WRITE-RACING-WRITE";
54 break;
55 case SyncHazard::WRITE_RACING_READ:
56 return "SYNC-HAZARD-WRITE-RACING-READ";
57 break;
John Zulauf9cb530d2019-09-30 14:14:10 -060058 default:
59 assert(0);
60 }
61 return "SYNC-HAZARD-INVALID";
62}
63
John Zulauf59e25072020-07-17 10:55:21 -060064static bool IsHazardVsRead(SyncHazard hazard) {
65 switch (hazard) {
66 case SyncHazard::NONE:
67 return false;
68 break;
69 case SyncHazard::READ_AFTER_WRITE:
70 return false;
71 break;
72 case SyncHazard::WRITE_AFTER_READ:
73 return true;
74 break;
75 case SyncHazard::WRITE_AFTER_WRITE:
76 return false;
77 break;
78 case SyncHazard::READ_RACING_WRITE:
79 return false;
80 break;
81 case SyncHazard::WRITE_RACING_WRITE:
82 return false;
83 break;
84 case SyncHazard::WRITE_RACING_READ:
85 return true;
86 break;
87 default:
88 assert(0);
89 }
90 return false;
91}
92
John Zulauf9cb530d2019-09-30 14:14:10 -060093static const char *string_SyncHazard(SyncHazard hazard) {
94 switch (hazard) {
95 case SyncHazard::NONE:
96 return "NONR";
97 break;
98 case SyncHazard::READ_AFTER_WRITE:
99 return "READ_AFTER_WRITE";
100 break;
101 case SyncHazard::WRITE_AFTER_READ:
102 return "WRITE_AFTER_READ";
103 break;
104 case SyncHazard::WRITE_AFTER_WRITE:
105 return "WRITE_AFTER_WRITE";
106 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700107 case SyncHazard::READ_RACING_WRITE:
108 return "READ_RACING_WRITE";
109 break;
110 case SyncHazard::WRITE_RACING_WRITE:
111 return "WRITE_RACING_WRITE";
112 break;
113 case SyncHazard::WRITE_RACING_READ:
114 return "WRITE_RACING_READ";
115 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600116 default:
117 assert(0);
118 }
119 return "INVALID HAZARD";
120}
121
John Zulauf37ceaed2020-07-03 16:18:15 -0600122static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
123 // Return the info for the first bit found
124 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700125 for (size_t i = 0; i < flags.size(); i++) {
126 if (flags.test(i)) {
127 info = &syncStageAccessInfoByStageAccessIndex[i];
128 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600129 }
130 }
131 return info;
132}
133
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700134static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600135 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700136 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600137 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700138 } else {
139 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
140 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
141 if ((flags & info.stage_access_bit).any()) {
142 if (!out_str.empty()) {
143 out_str.append(sep);
144 }
145 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600146 }
John Zulauf59e25072020-07-17 10:55:21 -0600147 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700148 if (out_str.length() == 0) {
149 out_str.append("Unhandled SyncStageAccess");
150 }
John Zulauf59e25072020-07-17 10:55:21 -0600151 }
152 return out_str;
153}
154
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700155static std::string string_UsageTag(const ResourceUsageTag &tag) {
156 std::stringstream out;
157
John Zulauffaea0ee2021-01-14 14:01:32 -0700158 out << "command: " << CommandTypeString(tag.command);
159 out << ", seq_no: " << tag.seq_num;
160 if (tag.sub_command != 0) {
161 out << ", subcmd: " << tag.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700162 }
163 return out.str();
164}
165
John Zulauffaea0ee2021-01-14 14:01:32 -0700166std::string CommandBufferAccessContext::FormatUsage(const HazardResult &hazard) const {
John Zulauf37ceaed2020-07-03 16:18:15 -0600167 const auto &tag = hazard.tag;
John Zulauf59e25072020-07-17 10:55:21 -0600168 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
169 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
John Zulauf1dae9192020-06-16 15:46:44 -0600170 std::stringstream out;
John Zulauf37ceaed2020-07-03 16:18:15 -0600171 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
172 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
John Zulauf59e25072020-07-17 10:55:21 -0600173 out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name;
174 if (IsHazardVsRead(hazard.hazard)) {
175 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
176 out << ", read_barriers: " << string_VkPipelineStageFlags(barriers);
177 } else {
178 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
179 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
180 }
181
John Zulauffaea0ee2021-01-14 14:01:32 -0700182 // PHASE2 TODO -- add comand buffer and reset from secondary if applicable
183 out << ", " << string_UsageTag(tag) << ", reset_no: " << reset_count_;
John Zulauf1dae9192020-06-16 15:46:44 -0600184 return out.str();
185}
186
John Zulaufd14743a2020-07-03 09:42:39 -0600187// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
188// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
189// also reflects this special case for read hazard detection (using access instead of exec scope)
John Zulaufb027cdb2020-05-21 14:25:22 -0600190static constexpr VkPipelineStageFlags kColorAttachmentExecScope = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700191static const SyncStageAccessFlags kColorAttachmentAccessScope =
192 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
193 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
194 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
195 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulaufb027cdb2020-05-21 14:25:22 -0600196static constexpr VkPipelineStageFlags kDepthStencilAttachmentExecScope =
197 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700198static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
199 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
200 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
201 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulauf8e3c3e92021-01-06 11:19:36 -0700202static constexpr VkPipelineStageFlags kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
203static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600204
John Zulauf8e3c3e92021-01-06 11:19:36 -0700205ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
206 {{0U, SyncStageAccessFlags()},
207 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
208 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
209 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
210
John Zulauf7635de32020-05-29 17:14:15 -0600211// 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 -0700212static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, ResourceUsageTag::kMaxCount,
213 ResourceUsageTag::kMaxCount, CMD_NONE);
John Zulaufb027cdb2020-05-21 14:25:22 -0600214
John Zulaufb02c1eb2020-10-06 16:33:36 -0600215static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) {
216 return bindable.binding.offset + bindable.binding.mem_state->fake_base_address;
217}
218
219static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; }
220
locke-lunarg3c038002020-04-30 23:08:08 -0600221inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
222 if (size == VK_WHOLE_SIZE) {
223 return (whole_size - offset);
224 }
225 return size;
226}
227
John Zulauf3e86bf02020-09-12 10:47:57 -0600228static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
229 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
230}
231
John Zulauf16adfc92020-04-08 10:28:33 -0600232template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600233static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600234 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
235}
236
John Zulauf355e49b2020-04-24 15:11:15 -0600237static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600238
John Zulauf3e86bf02020-09-12 10:47:57 -0600239static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
240 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
241}
242
243static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
244 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
245}
246
John Zulauf4a6105a2020-11-17 15:11:05 -0700247// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
248//
John Zulauf10f1f522020-12-18 12:00:35 -0700249// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
250//
John Zulauf4a6105a2020-11-17 15:11:05 -0700251// Usage:
252// Constructor() -- initializes the generator to point to the begin of the space declared.
253// * -- the current range of the generator empty signfies end
254// ++ -- advance to the next non-empty range (or end)
255
256// A wrapper for a single range with the same semantics as the actual generators below
257template <typename KeyType>
258class SingleRangeGenerator {
259 public:
260 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700261 const KeyType &operator*() const { return current_; }
262 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700263 SingleRangeGenerator &operator++() {
264 current_ = KeyType(); // just one real range
265 return *this;
266 }
267
268 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
269
270 private:
271 SingleRangeGenerator() = default;
272 const KeyType range_;
273 KeyType current_;
274};
275
276// Generate the ranges that are the intersection of range and the entries in the FilterMap
277template <typename FilterMap, typename KeyType = typename FilterMap::key_type>
278class FilteredRangeGenerator {
279 public:
John Zulaufd5115702021-01-18 12:34:33 -0700280 // Default constructed is safe to dereference for "empty" test, but for no other operation.
281 FilteredRangeGenerator() : range_(), filter_(nullptr), filter_pos_(), current_() {
282 // Default construction for KeyType *must* be empty range
283 assert(current_.empty());
284 }
John Zulauf4a6105a2020-11-17 15:11:05 -0700285 FilteredRangeGenerator(const FilterMap &filter, const KeyType &range)
286 : range_(range), filter_(&filter), filter_pos_(), current_() {
287 SeekBegin();
288 }
John Zulaufd5115702021-01-18 12:34:33 -0700289 FilteredRangeGenerator(const FilteredRangeGenerator &from) = default;
290
John Zulauf4a6105a2020-11-17 15:11:05 -0700291 const KeyType &operator*() const { return current_; }
292 const KeyType *operator->() const { return &current_; }
293 FilteredRangeGenerator &operator++() {
294 ++filter_pos_;
295 UpdateCurrent();
296 return *this;
297 }
298
299 bool operator==(const FilteredRangeGenerator &other) const { return current_ == other.current_; }
300
301 private:
John Zulauf4a6105a2020-11-17 15:11:05 -0700302 void UpdateCurrent() {
303 if (filter_pos_ != filter_->cend()) {
304 current_ = range_ & filter_pos_->first;
305 } else {
306 current_ = KeyType();
307 }
308 }
309 void SeekBegin() {
310 filter_pos_ = filter_->lower_bound(range_);
311 UpdateCurrent();
312 }
313 const KeyType range_;
314 const FilterMap *filter_;
315 typename FilterMap::const_iterator filter_pos_;
316 KeyType current_;
317};
John Zulaufd5115702021-01-18 12:34:33 -0700318using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700319using EventSimpleRangeGenerator = FilteredRangeGenerator<SyncEventState::ScopeMap>;
320
321// Templated to allow for different Range generators or map sources...
322
323// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulauf4a6105a2020-11-17 15:11:05 -0700324template <typename FilterMap, typename RangeGen, typename KeyType = typename FilterMap::key_type>
325class FilteredGeneratorGenerator {
326 public:
John Zulaufd5115702021-01-18 12:34:33 -0700327 // Default constructed is safe to dereference for "empty" test, but for no other operation.
328 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
329 // Default construction for KeyType *must* be empty range
330 assert(current_.empty());
331 }
332 FilteredGeneratorGenerator(const FilterMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700333 SeekBegin();
334 }
John Zulaufd5115702021-01-18 12:34:33 -0700335 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700336 const KeyType &operator*() const { return current_; }
337 const KeyType *operator->() const { return &current_; }
338 FilteredGeneratorGenerator &operator++() {
339 KeyType gen_range = GenRange();
340 KeyType filter_range = FilterRange();
341 current_ = KeyType();
342 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
343 if (gen_range.end > filter_range.end) {
344 // if the generated range is beyond the filter_range, advance the filter range
345 filter_range = AdvanceFilter();
346 } else {
347 gen_range = AdvanceGen();
348 }
349 current_ = gen_range & filter_range;
350 }
351 return *this;
352 }
353
354 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
355
356 private:
357 KeyType AdvanceFilter() {
358 ++filter_pos_;
359 auto filter_range = FilterRange();
360 if (filter_range.valid()) {
361 FastForwardGen(filter_range);
362 }
363 return filter_range;
364 }
365 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700366 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700367 auto gen_range = GenRange();
368 if (gen_range.valid()) {
369 FastForwardFilter(gen_range);
370 }
371 return gen_range;
372 }
373
374 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700375 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700376
377 KeyType FastForwardFilter(const KeyType &range) {
378 auto filter_range = FilterRange();
379 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700380 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700381 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
382 if (retry_count < kRetryLimit) {
383 ++filter_pos_;
384 filter_range = FilterRange();
385 retry_count++;
386 } else {
387 // Okay we've tried walking, do a seek.
388 filter_pos_ = filter_->lower_bound(range);
389 break;
390 }
391 }
392 return FilterRange();
393 }
394
395 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
396 // faster.
397 KeyType FastForwardGen(const KeyType &range) {
398 auto gen_range = GenRange();
399 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700400 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700401 gen_range = GenRange();
402 }
403 return gen_range;
404 }
405
406 void SeekBegin() {
407 auto gen_range = GenRange();
408 if (gen_range.empty()) {
409 current_ = KeyType();
410 filter_pos_ = filter_->cend();
411 } else {
412 filter_pos_ = filter_->lower_bound(gen_range);
413 current_ = gen_range & FilterRange();
414 }
415 }
416
John Zulauf4a6105a2020-11-17 15:11:05 -0700417 const FilterMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700418 RangeGen gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700419 typename FilterMap::const_iterator filter_pos_;
420 KeyType current_;
421};
422
423using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
424
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700425static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
John Zulauf5c5e88d2019-12-26 11:22:02 -0700426
John Zulauf3e86bf02020-09-12 10:47:57 -0600427ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
428 VkDeviceSize stride) {
429 VkDeviceSize range_start = offset + first_index * stride;
430 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600431 if (count == UINT32_MAX) {
432 range_size = buf_whole_size - range_start;
433 } else {
434 range_size = count * stride;
435 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600436 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600437}
438
locke-lunarg654e3692020-06-04 17:19:15 -0600439SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
440 VkShaderStageFlagBits stage_flag) {
441 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
442 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
443 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
444 }
445 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
446 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
447 assert(0);
448 }
449 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
450 return stage_access->second.uniform_read;
451 }
452
453 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
454 // Because if write hazard happens, read hazard might or might not happen.
455 // But if write hazard doesn't happen, read hazard is impossible to happen.
456 if (descriptor_data.is_writable) {
457 return stage_access->second.shader_write;
458 }
459 return stage_access->second.shader_read;
460}
461
locke-lunarg37047832020-06-12 13:44:45 -0600462bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
463 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
464 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
465 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
466 ? true
467 : false;
468}
469
470bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
471 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
472 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
473 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
474 ? true
475 : false;
476}
477
John Zulauf355e49b2020-04-24 15:11:15 -0600478// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600479template <typename Action>
480static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
481 Action &action) {
482 // At this point the "apply over range" logic only supports a single memory binding
483 if (!SimpleBinding(image_state)) return;
484 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600485 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700486 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
487 image_state.createInfo.extent, base_address);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600488 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700489 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600490 }
491}
492
John Zulauf7635de32020-05-29 17:14:15 -0600493// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
494// Used by both validation and record operations
495//
496// The signature for Action() reflect the needs of both uses.
497template <typename Action>
498void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
499 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) {
500 VkExtent3D extent = CastTo3D(render_area.extent);
501 VkOffset3D offset = CastTo3D(render_area.offset);
502 const auto &rp_ci = rp_state.createInfo;
503 const auto *attachment_ci = rp_ci.pAttachments;
504 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
505
506 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
507 const auto *color_attachments = subpass_ci.pColorAttachments;
508 const auto *color_resolve = subpass_ci.pResolveAttachments;
509 if (color_resolve && color_attachments) {
510 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
511 const auto &color_attach = color_attachments[i].attachment;
512 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
513 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
514 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700515 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600516 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700517 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600518 }
519 }
520 }
521
522 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700523 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600524 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
525 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
526 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
527 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
528 const auto src_ci = attachment_ci[src_at];
529 // The formats are required to match so we can pick either
530 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
531 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
532 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
533 VkImageAspectFlags aspect_mask = 0u;
534
535 // Figure out which aspects are actually touched during resolve operations
536 const char *aspect_string = nullptr;
537 if (resolve_depth && resolve_stencil) {
538 // Validate all aspects together
539 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
540 aspect_string = "depth/stencil";
541 } else if (resolve_depth) {
542 // Validate depth only
543 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
544 aspect_string = "depth";
545 } else if (resolve_stencil) {
546 // Validate all stencil only
547 aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT;
548 aspect_string = "stencil";
549 }
550
551 if (aspect_mask) {
552 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700553 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600554 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700555 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600556 }
557 }
558}
559
560// Action for validating resolve operations
561class ValidateResolveAction {
562 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700563 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
564 const CommandBufferAccessContext &cb_context, const char *func_name)
John Zulauf7635de32020-05-29 17:14:15 -0600565 : render_pass_(render_pass),
566 subpass_(subpass),
567 context_(context),
John Zulauffaea0ee2021-01-14 14:01:32 -0700568 cb_context_(cb_context),
John Zulauf7635de32020-05-29 17:14:15 -0600569 func_name_(func_name),
570 skip_(false) {}
571 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 -0700572 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600573 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
574 HazardResult hazard;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700575 hazard = context_.DetectHazard(view, current_usage, ordering_rule, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600576 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700577 skip_ |=
578 cb_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
579 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
580 " to resolve attachment %" PRIu32 ". Access info %s.",
581 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
582 attachment_name, src_at, dst_at, cb_context_.FormatUsage(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600583 }
584 }
585 // Providing a mechanism for the constructing caller to get the result of the validation
586 bool GetSkip() const { return skip_; }
587
588 private:
589 VkRenderPass render_pass_;
590 const uint32_t subpass_;
591 const AccessContext &context_;
John Zulauffaea0ee2021-01-14 14:01:32 -0700592 const CommandBufferAccessContext &cb_context_;
John Zulauf7635de32020-05-29 17:14:15 -0600593 const char *func_name_;
594 bool skip_;
595};
596
597// Update action for resolve operations
598class UpdateStateResolveAction {
599 public:
600 UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {}
601 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 -0700602 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600603 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
604 // Ignores validation only arguments...
John Zulauf8e3c3e92021-01-06 11:19:36 -0700605 context_.UpdateAccessState(view, current_usage, ordering_rule, offset, extent, aspect_mask, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600606 }
607
608 private:
609 AccessContext &context_;
610 const ResourceUsageTag &tag_;
611};
612
John Zulauf59e25072020-07-17 10:55:21 -0600613void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700614 const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) {
John Zulauf59e25072020-07-17 10:55:21 -0600615 access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_));
616 usage_index = usage_index_;
617 hazard = hazard_;
618 prior_access = prior_;
619 tag = tag_;
620}
621
John Zulauf540266b2020-04-06 18:54:53 -0600622AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
623 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600624 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600625 Reset();
626 const auto &subpass_dep = dependencies[subpass];
627 prev_.reserve(subpass_dep.prev.size());
John Zulauf355e49b2020-04-24 15:11:15 -0600628 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600629 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600630 const auto prev_pass = prev_dep.first->pass;
631 const auto &prev_barriers = prev_dep.second;
632 assert(prev_dep.second.size());
633 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
634 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700635 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600636
637 async_.reserve(subpass_dep.async.size());
638 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700639 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600640 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600641 if (subpass_dep.barrier_from_external.size()) {
642 src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external);
John Zulaufe5da6e52020-03-18 15:32:18 -0600643 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600644 if (subpass_dep.barrier_to_external.size()) {
645 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600646 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700647}
648
John Zulauf5f13a792020-03-10 07:31:21 -0600649template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700650HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600651 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600652 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600653 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600654
655 HazardResult hazard;
656 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
657 hazard = detector.Detect(prev);
658 }
659 return hazard;
660}
661
John Zulauf4a6105a2020-11-17 15:11:05 -0700662template <typename Action>
663void AccessContext::ForAll(Action &&action) {
664 for (const auto address_type : kAddressTypes) {
665 auto &accesses = GetAccessStateMap(address_type);
666 for (const auto &access : accesses) {
667 action(address_type, access);
668 }
669 }
670}
671
John Zulauf3d84f1b2020-03-09 13:33:25 -0600672// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
673// the DAG of the contexts (for example subpasses)
674template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700675HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600676 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600677 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600678
John Zulauf1a224292020-06-30 14:52:13 -0600679 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600680 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
681 // so we'll check these first
682 for (const auto &async_context : async_) {
683 hazard = async_context->DetectAsyncHazard(type, detector, range);
684 if (hazard.hazard) return hazard;
685 }
John Zulauf5f13a792020-03-10 07:31:21 -0600686 }
687
John Zulauf1a224292020-06-30 14:52:13 -0600688 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600689
John Zulauf69133422020-05-20 14:55:53 -0600690 const auto &accesses = GetAccessStateMap(type);
691 const auto from = accesses.lower_bound(range);
692 const auto to = accesses.upper_bound(range);
693 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600694
John Zulauf69133422020-05-20 14:55:53 -0600695 for (auto pos = from; pos != to; ++pos) {
696 // Cover any leading gap, or gap between entries
697 if (detect_prev) {
698 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
699 // Cover any leading gap, or gap between entries
700 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600701 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600702 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600703 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600704 if (hazard.hazard) return hazard;
705 }
John Zulauf69133422020-05-20 14:55:53 -0600706 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
707 gap.begin = pos->first.end;
708 }
709
710 hazard = detector.Detect(pos);
711 if (hazard.hazard) return hazard;
712 }
713
714 if (detect_prev) {
715 // Detect in the trailing empty as needed
716 gap.end = range.end;
717 if (gap.non_empty()) {
718 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600719 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600720 }
721
722 return hazard;
723}
724
725// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
726template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700727HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
728 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600729 auto &accesses = GetAccessStateMap(type);
730 const auto from = accesses.lower_bound(range);
731 const auto to = accesses.upper_bound(range);
732
John Zulauf3d84f1b2020-03-09 13:33:25 -0600733 HazardResult hazard;
John Zulauf16adfc92020-04-08 10:28:33 -0600734 for (auto pos = from; pos != to && !hazard.hazard; ++pos) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700735 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600736 }
John Zulauf16adfc92020-04-08 10:28:33 -0600737
John Zulauf3d84f1b2020-03-09 13:33:25 -0600738 return hazard;
739}
740
John Zulaufb02c1eb2020-10-06 16:33:36 -0600741struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700742 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600743 void operator()(ResourceAccessState *access) const {
744 assert(access);
745 access->ApplyBarriers(barriers, true);
746 }
747 const std::vector<SyncBarrier> &barriers;
748};
749
750struct ApplyTrackbackBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700751 explicit ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600752 void operator()(ResourceAccessState *access) const {
753 assert(access);
754 assert(!access->HasPendingState());
755 access->ApplyBarriers(barriers, false);
756 access->ApplyPendingBarriers(kCurrentCommandTag);
757 }
758 const std::vector<SyncBarrier> &barriers;
759};
760
761// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
762// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
763// *different* map from dest.
764// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
765// range [first, last)
766template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600767static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
768 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600769 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600770 auto at = entry;
771 for (auto pos = first; pos != last; ++pos) {
772 // Every member of the input iterator range must fit within the remaining portion of entry
773 assert(at->first.includes(pos->first));
774 assert(at != dest->end());
775 // Trim up at to the same size as the entry to resolve
776 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600777 auto access = pos->second; // intentional copy
778 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600779 at->second.Resolve(access);
780 ++at; // Go to the remaining unused section of entry
781 }
782}
783
John Zulaufa0a98292020-09-18 09:30:10 -0600784static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
785 SyncBarrier merged = {};
786 for (const auto &barrier : barriers) {
787 merged.Merge(barrier);
788 }
789 return merged;
790}
791
John Zulaufb02c1eb2020-10-06 16:33:36 -0600792template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700793void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600794 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
795 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600796 if (!range.non_empty()) return;
797
John Zulauf355e49b2020-04-24 15:11:15 -0600798 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
799 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600800 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600801 if (current->pos_B->valid) {
802 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600803 auto access = src_pos->second; // intentional copy
804 barrier_action(&access);
805
John Zulauf16adfc92020-04-08 10:28:33 -0600806 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600807 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
808 trimmed->second.Resolve(access);
809 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600810 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600811 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600812 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600813 }
John Zulauf16adfc92020-04-08 10:28:33 -0600814 } else {
815 // we have to descend to fill this gap
816 if (recur_to_infill) {
John Zulauf355e49b2020-04-24 15:11:15 -0600817 if (current->pos_A->valid) {
818 // Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation
819 ResourceAccessRangeMap gap_map;
John Zulauf3bcab5e2020-06-19 14:42:32 -0600820 ResolvePreviousAccess(type, current_range, &gap_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600821 ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -0600822 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600823 // There isn't anything in dest in current)range, so we can accumulate directly into it.
824 ResolvePreviousAccess(type, current_range, resolve_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600825 // Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current
826 for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) {
827 barrier_action(&pos->second);
John Zulauf355e49b2020-04-24 15:11:15 -0600828 }
829 }
830 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
831 // iterator of the outer while.
832
833 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
834 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
835 // we stepped on the dest map
locke-lunarg88dbb542020-06-23 22:05:42 -0600836 const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
837 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -0600838 current.seek(seek_to);
839 } else if (!current->pos_A->valid && infill_state) {
840 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
841 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
842 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -0600843 }
John Zulauf5f13a792020-03-10 07:31:21 -0600844 }
John Zulauf16adfc92020-04-08 10:28:33 -0600845 ++current;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600846 }
John Zulauf1a224292020-06-30 14:52:13 -0600847
848 // Infill if range goes passed both the current and resolve map prior contents
849 if (recur_to_infill && (current->range.end < range.end)) {
850 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
851 ResourceAccessRangeMap gap_map;
852 const auto the_end = resolve_map->end();
853 ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state);
854 for (auto &access : gap_map) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600855 barrier_action(&access.second);
John Zulauf1a224292020-06-30 14:52:13 -0600856 resolve_map->insert(the_end, access);
857 }
858 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600859}
860
John Zulauf43cc7462020-12-03 12:33:12 -0700861void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
862 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufe5da6e52020-03-18 15:32:18 -0600863 if ((prev_.size() == 0) && (src_external_.context == nullptr)) {
John Zulauf5f13a792020-03-10 07:31:21 -0600864 if (range.non_empty() && infill_state) {
865 descent_map->insert(std::make_pair(range, *infill_state));
866 }
867 } else {
868 // Look for something to fill the gap further along.
869 for (const auto &prev_dep : prev_) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600870 const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers);
871 prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600872 }
873
John Zulaufe5da6e52020-03-18 15:32:18 -0600874 if (src_external_.context) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600875 const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers);
876 src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600877 }
878 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600879}
880
John Zulauf4a6105a2020-11-17 15:11:05 -0700881// Non-lazy import of all accesses, WaitEvents needs this.
882void AccessContext::ResolvePreviousAccesses() {
883 ResourceAccessState default_state;
884 for (const auto address_type : kAddressTypes) {
885 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
886 }
887}
888
John Zulauf43cc7462020-12-03 12:33:12 -0700889AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
890 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -0600891}
892
John Zulauf1507ee42020-05-18 11:33:09 -0600893static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
894 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
895 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE;
896 return stage_access;
897}
898static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
899 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
900 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE;
901 return stage_access;
902}
903
John Zulauf7635de32020-05-29 17:14:15 -0600904// Caller must manage returned pointer
905static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
906 uint32_t subpass, const VkRect2D &render_area,
907 std::vector<const IMAGE_VIEW_STATE *> attachment_views) {
908 auto *proxy = new AccessContext(context);
909 proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulaufaff20662020-06-01 14:07:58 -0600910 proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulauf7635de32020-05-29 17:14:15 -0600911 return proxy;
912}
913
John Zulaufb02c1eb2020-10-06 16:33:36 -0600914template <typename BarrierAction>
John Zulauf52446eb2020-10-22 16:40:08 -0600915class ResolveAccessRangeFunctor {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600916 public:
John Zulauf43cc7462020-12-03 12:33:12 -0700917 ResolveAccessRangeFunctor(const AccessContext &context, AccessAddressType address_type, ResourceAccessRangeMap *descent_map,
918 const ResourceAccessState *infill_state, BarrierAction &barrier_action)
John Zulauf52446eb2020-10-22 16:40:08 -0600919 : context_(context),
920 address_type_(address_type),
921 descent_map_(descent_map),
922 infill_state_(infill_state),
923 barrier_action_(barrier_action) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600924 ResolveAccessRangeFunctor() = delete;
925 void operator()(const ResourceAccessRange &range) const {
926 context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_);
927 }
928
929 private:
John Zulauf52446eb2020-10-22 16:40:08 -0600930 const AccessContext &context_;
John Zulauf43cc7462020-12-03 12:33:12 -0700931 const AccessAddressType address_type_;
John Zulauf52446eb2020-10-22 16:40:08 -0600932 ResourceAccessRangeMap *const descent_map_;
933 const ResourceAccessState *infill_state_;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600934 BarrierAction &barrier_action_;
935};
936
John Zulaufb02c1eb2020-10-06 16:33:36 -0600937template <typename BarrierAction>
938void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -0700939 BarrierAction &barrier_action, AccessAddressType address_type,
940 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600941 const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action);
942 ApplyOverImageRange(image_state, subresource_range, action);
John Zulauf62f10592020-04-03 12:20:02 -0600943}
944
John Zulauf7635de32020-05-29 17:14:15 -0600945// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulauffaea0ee2021-01-14 14:01:32 -0700946bool AccessContext::ValidateLayoutTransitions(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600947 const VkRect2D &render_area, uint32_t subpass,
948 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
949 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -0600950 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -0600951 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
952 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
953 // those affects have not been recorded yet.
954 //
955 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
956 // to apply and only copy then, if this proves a hot spot.
957 std::unique_ptr<AccessContext> proxy_for_prev;
958 TrackBack proxy_track_back;
959
John Zulauf355e49b2020-04-24 15:11:15 -0600960 const auto &transitions = rp_state.subpass_transitions[subpass];
961 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -0600962 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
963
964 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
965 if (prev_needs_proxy) {
966 if (!proxy_for_prev) {
967 proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass,
968 render_area, attachment_views));
969 proxy_track_back = *track_back;
970 proxy_track_back.context = proxy_for_prev.get();
971 }
972 track_back = &proxy_track_back;
973 }
974 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -0600975 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700976 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
977 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
978 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
979 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
980 string_VkImageLayout(transition.old_layout),
981 string_VkImageLayout(transition.new_layout),
982 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -0600983 }
984 }
985 return skip;
986}
987
John Zulauffaea0ee2021-01-14 14:01:32 -0700988bool AccessContext::ValidateLoadOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600989 const VkRect2D &render_area, uint32_t subpass,
990 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
991 const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -0600992 bool skip = false;
993 const auto *attachment_ci = rp_state.createInfo.pAttachments;
994 VkExtent3D extent = CastTo3D(render_area.extent);
995 VkOffset3D offset = CastTo3D(render_area.offset);
John Zulaufa0a98292020-09-18 09:30:10 -0600996
John Zulauf1507ee42020-05-18 11:33:09 -0600997 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
998 if (subpass == rp_state.attachment_first_subpass[i]) {
999 if (attachment_views[i] == nullptr) continue;
1000 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1001 const IMAGE_STATE *image = view.image_state.get();
1002 if (image == nullptr) continue;
1003 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001004
1005 // Need check in the following way
1006 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1007 // vs. transition
1008 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1009 // for each aspect loaded.
1010
1011 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001012 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001013 const bool is_color = !(has_depth || has_stencil);
1014
1015 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001016 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001017
John Zulaufaff20662020-06-01 14:07:58 -06001018 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001019 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001020
John Zulaufb02c1eb2020-10-06 16:33:36 -06001021 auto hazard_range = view.normalized_subresource_range;
1022 bool checked_stencil = false;
1023 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001024 hazard = DetectHazard(*image, load_index, view.normalized_subresource_range, SyncOrdering::kColorAttachment, offset,
John Zulauf859089b2020-10-29 17:37:03 -06001025 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001026 aspect = "color";
1027 } else {
1028 if (has_depth) {
1029 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001030 hazard = DetectHazard(*image, load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset, extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001031 aspect = "depth";
1032 }
1033 if (!hazard.hazard && has_stencil) {
1034 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001035 hazard = DetectHazard(*image, stencil_load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset,
1036 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001037 aspect = "stencil";
1038 checked_stencil = true;
1039 }
1040 }
1041
1042 if (hazard.hazard) {
1043 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001044 const auto &sync_state = cb_context.GetSyncState();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001045 if (hazard.tag == kCurrentCommandTag) {
1046 // Hazard vs. ILT
1047 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1048 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1049 " aspect %s during load with loadOp %s.",
1050 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1051 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06001052 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1053 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001054 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001055 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauffaea0ee2021-01-14 14:01:32 -07001056 cb_context.FormatUsage(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001057 }
1058 }
1059 }
1060 }
1061 return skip;
1062}
1063
John Zulaufaff20662020-06-01 14:07:58 -06001064// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1065// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1066// store is part of the same Next/End operation.
1067// The latter is handled in layout transistion validation directly
John Zulauffaea0ee2021-01-14 14:01:32 -07001068bool AccessContext::ValidateStoreOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001069 const VkRect2D &render_area, uint32_t subpass,
1070 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1071 const char *func_name) const {
1072 bool skip = false;
1073 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1074 VkExtent3D extent = CastTo3D(render_area.extent);
1075 VkOffset3D offset = CastTo3D(render_area.offset);
1076
1077 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1078 if (subpass == rp_state.attachment_last_subpass[i]) {
1079 if (attachment_views[i] == nullptr) continue;
1080 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1081 const IMAGE_STATE *image = view.image_state.get();
1082 if (image == nullptr) continue;
1083 const auto &ci = attachment_ci[i];
1084
1085 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1086 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1087 // sake, we treat DONT_CARE as writing.
1088 const bool has_depth = FormatHasDepth(ci.format);
1089 const bool has_stencil = FormatHasStencil(ci.format);
1090 const bool is_color = !(has_depth || has_stencil);
1091 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1092 if (!has_stencil && !store_op_stores) continue;
1093
1094 HazardResult hazard;
1095 const char *aspect = nullptr;
1096 bool checked_stencil = false;
1097 if (is_color) {
1098 hazard = DetectHazard(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001099 view.normalized_subresource_range, SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001100 aspect = "color";
1101 } else {
1102 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1103 auto hazard_range = view.normalized_subresource_range;
1104 if (has_depth && store_op_stores) {
1105 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1106 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001107 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001108 aspect = "depth";
1109 }
1110 if (!hazard.hazard && has_stencil && stencil_op_stores) {
1111 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1112 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001113 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001114 aspect = "stencil";
1115 checked_stencil = true;
1116 }
1117 }
1118
1119 if (hazard.hazard) {
1120 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1121 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001122 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1123 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1124 " %s aspect during store with %s %s. Access info %s",
1125 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect,
1126 op_type_string, store_op_string, cb_context.FormatUsage(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001127 }
1128 }
1129 }
1130 return skip;
1131}
1132
John Zulauffaea0ee2021-01-14 14:01:32 -07001133bool AccessContext::ValidateResolveOperations(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufb027cdb2020-05-21 14:25:22 -06001134 const VkRect2D &render_area,
1135 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name,
1136 uint32_t subpass) const {
John Zulauffaea0ee2021-01-14 14:01:32 -07001137 ValidateResolveAction validate_action(rp_state.renderPass, subpass, *this, cb_context, func_name);
John Zulauf7635de32020-05-29 17:14:15 -06001138 ResolveOperation(validate_action, rp_state, render_area, attachment_views, subpass);
1139 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001140}
1141
John Zulauf3d84f1b2020-03-09 13:33:25 -06001142class HazardDetector {
1143 SyncStageAccessIndex usage_index_;
1144
1145 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001146 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001147 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1148 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001149 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001150 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001151};
1152
John Zulauf69133422020-05-20 14:55:53 -06001153class HazardDetectorWithOrdering {
1154 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001155 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001156
1157 public:
1158 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001159 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001160 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001161 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1162 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001163 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001164 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001165};
1166
John Zulauf16adfc92020-04-08 10:28:33 -06001167HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001168 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001169 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001170 const auto base_address = ResourceBaseAddress(buffer);
1171 HazardDetector detector(usage_index);
1172 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001173}
1174
John Zulauf69133422020-05-20 14:55:53 -06001175template <typename Detector>
1176HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1177 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1178 const VkExtent3D &extent, DetectOptions options) const {
1179 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001180 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001181 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1182 base_address);
1183 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001184 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001185 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001186 if (hazard.hazard) return hazard;
1187 }
1188 return HazardResult();
1189}
1190
John Zulauf540266b2020-04-06 18:54:53 -06001191HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1192 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1193 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001194 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1195 subresource.layerCount};
John Zulauf1507ee42020-05-18 11:33:09 -06001196 return DetectHazard(image, current_usage, subresource_range, offset, extent);
1197}
1198
1199HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1200 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1201 const VkExtent3D &extent) const {
John Zulauf69133422020-05-20 14:55:53 -06001202 HazardDetector detector(current_usage);
1203 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
1204}
1205
1206HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001207 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
John Zulauf69133422020-05-20 14:55:53 -06001208 const VkOffset3D &offset, const VkExtent3D &extent) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001209 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06001210 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001211}
1212
John Zulaufb027cdb2020-05-21 14:25:22 -06001213// Some common code for looking at attachments, if there's anything wrong, we return no hazard, core validation
1214// should have reported the issue regarding an invalid attachment entry
1215HazardResult AccessContext::DetectHazard(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001216 SyncOrdering ordering_rule, const VkOffset3D &offset, const VkExtent3D &extent,
John Zulaufb027cdb2020-05-21 14:25:22 -06001217 VkImageAspectFlags aspect_mask) const {
1218 if (view != nullptr) {
1219 const IMAGE_STATE *image = view->image_state.get();
1220 if (image != nullptr) {
1221 auto *detect_range = &view->normalized_subresource_range;
1222 VkImageSubresourceRange masked_range;
1223 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1224 masked_range = view->normalized_subresource_range;
1225 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1226 detect_range = &masked_range;
1227 }
1228
1229 // NOTE: The range encoding code is not robust to invalid ranges, so we protect it from our change
1230 if (detect_range->aspectMask) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001231 return DetectHazard(*image, current_usage, *detect_range, ordering_rule, offset, extent);
John Zulaufb027cdb2020-05-21 14:25:22 -06001232 }
1233 }
1234 }
1235 return HazardResult();
1236}
John Zulauf43cc7462020-12-03 12:33:12 -07001237
John Zulauf3d84f1b2020-03-09 13:33:25 -06001238class BarrierHazardDetector {
1239 public:
1240 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1241 SyncStageAccessFlags src_access_scope)
1242 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1243
John Zulauf5f13a792020-03-10 07:31:21 -06001244 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1245 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001246 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001247 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001248 // 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 -07001249 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001250 }
1251
1252 private:
1253 SyncStageAccessIndex usage_index_;
1254 VkPipelineStageFlags src_exec_scope_;
1255 SyncStageAccessFlags src_access_scope_;
1256};
1257
John Zulauf4a6105a2020-11-17 15:11:05 -07001258class EventBarrierHazardDetector {
1259 public:
1260 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1261 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
1262 const ResourceUsageTag &scope_tag)
1263 : usage_index_(usage_index),
1264 src_exec_scope_(src_exec_scope),
1265 src_access_scope_(src_access_scope),
1266 event_scope_(event_scope),
1267 scope_pos_(event_scope.cbegin()),
1268 scope_end_(event_scope.cend()),
1269 scope_tag_(scope_tag) {}
1270
1271 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1272 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1273 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1274 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1275 if (scope_pos_ == scope_end_) return HazardResult();
1276 if (!scope_pos_->first.intersects(pos->first)) {
1277 event_scope_.lower_bound(pos->first);
1278 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1279 }
1280
1281 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1282 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1283 }
1284 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1285 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1286 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1287 }
1288
1289 private:
1290 SyncStageAccessIndex usage_index_;
1291 VkPipelineStageFlags src_exec_scope_;
1292 SyncStageAccessFlags src_access_scope_;
1293 const SyncEventState::ScopeMap &event_scope_;
1294 SyncEventState::ScopeMap::const_iterator scope_pos_;
1295 SyncEventState::ScopeMap::const_iterator scope_end_;
1296 const ResourceUsageTag &scope_tag_;
1297};
1298
1299HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
1300 const SyncStageAccessFlags &src_access_scope,
1301 const VkImageSubresourceRange &subresource_range,
1302 const SyncEventState &sync_event, DetectOptions options) const {
1303 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1304 // first access scope map to use, and there's no easy way to plumb it in below.
1305 const auto address_type = ImageAddressType(image);
1306 const auto &event_scope = sync_event.FirstScope(address_type);
1307
1308 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1309 event_scope, sync_event.first_scope_tag);
1310 VkOffset3D zero_offset = {0, 0, 0};
1311 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
1312}
1313
John Zulauf16adfc92020-04-08 10:28:33 -06001314HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001315 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001316 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001317 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001318 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
1319 VkOffset3D zero_offset = {0, 0, 0};
1320 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001321}
1322
John Zulauf355e49b2020-04-24 15:11:15 -06001323HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001324 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001325 const VkImageMemoryBarrier &barrier) const {
1326 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1327 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1328 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1329}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001330HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
1331 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope,
John Zulaufd5115702021-01-18 12:34:33 -07001332 image_barrier.barrier.src_access_scope, image_barrier.range.subresource_range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001333}
John Zulauf355e49b2020-04-24 15:11:15 -06001334
John Zulauf9cb530d2019-09-30 14:14:10 -06001335template <typename Flags, typename Map>
1336SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1337 SyncStageAccessFlags scope = 0;
1338 for (const auto &bit_scope : map) {
1339 if (flag_mask < bit_scope.first) break;
1340
1341 if (flag_mask & bit_scope.first) {
1342 scope |= bit_scope.second;
1343 }
1344 }
1345 return scope;
1346}
1347
1348SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags stages) {
1349 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1350}
1351
1352SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags accesses) {
1353 return AccessScopeImpl(accesses, syncStageAccessMaskByAccessBit);
1354}
1355
1356// Getting from stage mask and access mask to stage/acess masks is something we need to be good at...
1357SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags stages, VkAccessFlags accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001358 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1359 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1360 // 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 -06001361 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1362}
1363
1364template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001365void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001366 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1367 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001368 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001369 auto pos = accesses->lower_bound(range);
1370 if (pos == accesses->end() || !pos->first.intersects(range)) {
1371 // The range is empty, fill it with a default value.
1372 pos = action.Infill(accesses, pos, range);
1373 } else if (range.begin < pos->first.begin) {
1374 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001375 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001376 } else if (pos->first.begin < range.begin) {
1377 // Trim the beginning if needed
1378 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1379 ++pos;
1380 }
1381
1382 const auto the_end = accesses->end();
1383 while ((pos != the_end) && pos->first.intersects(range)) {
1384 if (pos->first.end > range.end) {
1385 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1386 }
1387
1388 pos = action(accesses, pos);
1389 if (pos == the_end) break;
1390
1391 auto next = pos;
1392 ++next;
1393 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1394 // Need to infill if next is disjoint
1395 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001396 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001397 next = action.Infill(accesses, next, new_range);
1398 }
1399 pos = next;
1400 }
1401}
John Zulaufd5115702021-01-18 12:34:33 -07001402
1403// Give a comparable interface for range generators and ranges
1404template <typename Action>
1405inline void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
1406 assert(range);
1407 UpdateMemoryAccessState(accesses, *range, action);
1408}
1409
John Zulauf4a6105a2020-11-17 15:11:05 -07001410template <typename Action, typename RangeGen>
1411void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1412 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001413 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 -07001414 for (; range_gen->non_empty(); ++range_gen) {
1415 UpdateMemoryAccessState(accesses, *range_gen, action);
1416 }
1417}
John Zulauf9cb530d2019-09-30 14:14:10 -06001418
1419struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001420 using Iterator = ResourceAccessRangeMap::iterator;
1421 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001422 // this is only called on gaps, and never returns a gap.
1423 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001424 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001425 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001426 }
John Zulauf5f13a792020-03-10 07:31:21 -06001427
John Zulauf5c5e88d2019-12-26 11:22:02 -07001428 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001429 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001430 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001431 return pos;
1432 }
1433
John Zulauf43cc7462020-12-03 12:33:12 -07001434 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001435 SyncOrdering ordering_rule_, const ResourceUsageTag &tag_)
1436 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001437 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001438 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001439 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001440 const SyncOrdering ordering_rule;
John Zulauf9cb530d2019-09-30 14:14:10 -06001441 const ResourceUsageTag &tag;
1442};
1443
John Zulauf4a6105a2020-11-17 15:11:05 -07001444// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001445struct PipelineBarrierOp {
1446 SyncBarrier barrier;
1447 bool layout_transition;
1448 PipelineBarrierOp(const SyncBarrier &barrier_, bool layout_transition_)
1449 : barrier(barrier_), layout_transition(layout_transition_) {}
1450 PipelineBarrierOp() = default;
John Zulaufd5115702021-01-18 12:34:33 -07001451 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf1e331ec2020-12-04 18:29:38 -07001452 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(barrier, layout_transition); }
1453};
John Zulauf4a6105a2020-11-17 15:11:05 -07001454// The barrier operation for wait events
1455struct WaitEventBarrierOp {
1456 const ResourceUsageTag *scope_tag;
1457 SyncBarrier barrier;
1458 bool layout_transition;
1459 WaitEventBarrierOp(const ResourceUsageTag &scope_tag_, const SyncBarrier &barrier_, bool layout_transition_)
1460 : scope_tag(&scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1461 WaitEventBarrierOp() = default;
1462 void operator()(ResourceAccessState *access_state) const {
1463 assert(scope_tag); // Not valid to have a non-scope op executed, default construct included for std::vector support
1464 access_state->ApplyBarrier(*scope_tag, barrier, layout_transition);
1465 }
1466};
John Zulauf1e331ec2020-12-04 18:29:38 -07001467
John Zulauf4a6105a2020-11-17 15:11:05 -07001468// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1469// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1470// of a collection is known/present.
John Zulauf1e331ec2020-12-04 18:29:38 -07001471template <typename BarrierOp>
John Zulauf89311b42020-09-29 16:28:47 -06001472class ApplyBarrierOpsFunctor {
1473 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001474 using Iterator = ResourceAccessRangeMap::iterator;
1475 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
John Zulauf9cb530d2019-09-30 14:14:10 -06001476
John Zulauf5c5e88d2019-12-26 11:22:02 -07001477 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001478 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001479 for (const auto &op : barrier_ops_) {
1480 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001481 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001482
John Zulauf89311b42020-09-29 16:28:47 -06001483 if (resolve_) {
1484 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1485 // another walk
1486 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001487 }
1488 return pos;
1489 }
1490
John Zulauf89311b42020-09-29 16:28:47 -06001491 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulaufd5115702021-01-18 12:34:33 -07001492 ApplyBarrierOpsFunctor(bool resolve, size_t size_hint, const ResourceUsageTag &tag)
1493 : resolve_(resolve), barrier_ops_(), tag_(tag) {
1494 barrier_ops_.reserve(size_hint);
1495 }
1496 void EmplaceBack(const BarrierOp &op) { barrier_ops_.emplace_back(op); }
John Zulauf89311b42020-09-29 16:28:47 -06001497
1498 private:
1499 bool resolve_;
John Zulaufd5115702021-01-18 12:34:33 -07001500 std::vector<BarrierOp> barrier_ops_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001501 const ResourceUsageTag &tag_;
1502};
1503
John Zulauf4a6105a2020-11-17 15:11:05 -07001504// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1505// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1506template <typename BarrierOp>
1507class ApplyBarrierFunctor {
1508 public:
1509 using Iterator = ResourceAccessRangeMap::iterator;
1510 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1511
1512 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1513 auto &access_state = pos->second;
1514 barrier_op_(&access_state);
1515 return pos;
1516 }
1517
1518 ApplyBarrierFunctor(const BarrierOp &barrier_op) : barrier_op_(barrier_op) {}
1519
1520 private:
John Zulaufd5115702021-01-18 12:34:33 -07001521 BarrierOp barrier_op_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001522};
1523
John Zulauf1e331ec2020-12-04 18:29:38 -07001524// This functor resolves the pendinging state.
1525class ResolvePendingBarrierFunctor {
1526 public:
1527 using Iterator = ResourceAccessRangeMap::iterator;
1528 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1529
1530 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1531 auto &access_state = pos->second;
1532 access_state.ApplyPendingBarriers(tag_);
1533 return pos;
1534 }
1535
1536 ResolvePendingBarrierFunctor(const ResourceUsageTag &tag) : tag_(tag) {}
1537
1538 private:
John Zulauf89311b42020-09-29 16:28:47 -06001539 const ResourceUsageTag &tag_;
John Zulauf9cb530d2019-09-30 14:14:10 -06001540};
1541
John Zulauf8e3c3e92021-01-06 11:19:36 -07001542void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1543 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
1544 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001545 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001546}
1547
John Zulauf8e3c3e92021-01-06 11:19:36 -07001548void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001549 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001550 if (!SimpleBinding(buffer)) return;
1551 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001552 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001553}
John Zulauf355e49b2020-04-24 15:11:15 -06001554
John Zulauf8e3c3e92021-01-06 11:19:36 -07001555void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001556 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf540266b2020-04-06 18:54:53 -06001557 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001558 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001559 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001560 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1561 base_address);
1562 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001563 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf5f13a792020-03-10 07:31:21 -06001564 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001565 UpdateMemoryAccessState(&GetAccessStateMap(address_type), *range_gen, action);
John Zulauf5f13a792020-03-10 07:31:21 -06001566 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001567}
John Zulauf8e3c3e92021-01-06 11:19:36 -07001568void AccessContext::UpdateAccessState(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1569 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask,
1570 const ResourceUsageTag &tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001571 if (view != nullptr) {
1572 const IMAGE_STATE *image = view->image_state.get();
1573 if (image != nullptr) {
1574 auto *update_range = &view->normalized_subresource_range;
1575 VkImageSubresourceRange masked_range;
1576 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1577 masked_range = view->normalized_subresource_range;
1578 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1579 update_range = &masked_range;
1580 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001581 UpdateAccessState(*image, current_usage, ordering_rule, *update_range, offset, extent, tag);
John Zulauf7635de32020-05-29 17:14:15 -06001582 }
1583 }
1584}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001585
John Zulauf8e3c3e92021-01-06 11:19:36 -07001586void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001587 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1588 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001589 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1590 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001591 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001592}
1593
John Zulauf540266b2020-04-06 18:54:53 -06001594template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001595void AccessContext::UpdateResourceAccess(const BUFFER_STATE &buffer, const ResourceAccessRange &range, const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001596 if (!SimpleBinding(buffer)) return;
1597 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf43cc7462020-12-03 12:33:12 -07001598 UpdateMemoryAccessState(&GetAccessStateMap(AccessAddressType::kLinear), (range + base_address), action);
John Zulauf540266b2020-04-06 18:54:53 -06001599}
1600
1601template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001602void AccessContext::UpdateResourceAccess(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1603 const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001604 if (!SimpleBinding(image)) return;
1605 const auto address_type = ImageAddressType(image);
1606 auto *accesses = &GetAccessStateMap(address_type);
John Zulauf540266b2020-04-06 18:54:53 -06001607
John Zulauf16adfc92020-04-08 10:28:33 -06001608 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001609 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, {0, 0, 0},
1610 image.createInfo.extent, base_address);
1611
John Zulauf540266b2020-04-06 18:54:53 -06001612 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001613 UpdateMemoryAccessState(accesses, *range_gen, action);
John Zulauf540266b2020-04-06 18:54:53 -06001614 }
1615}
1616
John Zulauf7635de32020-05-29 17:14:15 -06001617void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1618 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1619 const ResourceUsageTag &tag) {
1620 UpdateStateResolveAction update(*this, tag);
1621 ResolveOperation(update, rp_state, render_area, attachment_views, subpass);
1622}
1623
John Zulaufaff20662020-06-01 14:07:58 -06001624void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1625 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1626 const ResourceUsageTag &tag) {
1627 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1628 VkExtent3D extent = CastTo3D(render_area.extent);
1629 VkOffset3D offset = CastTo3D(render_area.offset);
1630
1631 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1632 if (rp_state.attachment_last_subpass[i] == subpass) {
1633 if (attachment_views[i] == nullptr) continue; // UNUSED
1634 const auto &view = *attachment_views[i];
1635 const IMAGE_STATE *image = view.image_state.get();
1636 if (image == nullptr) continue;
1637
1638 const auto &ci = attachment_ci[i];
1639 const bool has_depth = FormatHasDepth(ci.format);
1640 const bool has_stencil = FormatHasStencil(ci.format);
1641 const bool is_color = !(has_depth || has_stencil);
1642 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1643
1644 if (is_color && store_op_stores) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001645 UpdateAccessState(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1646 view.normalized_subresource_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001647 } else {
1648 auto update_range = view.normalized_subresource_range;
1649 if (has_depth && store_op_stores) {
1650 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001651 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1652 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001653 }
1654 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1655 if (has_stencil && stencil_op_stores) {
1656 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001657 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1658 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001659 }
1660 }
1661 }
1662 }
1663}
1664
John Zulauf540266b2020-04-06 18:54:53 -06001665template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001666void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001667 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001668 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001669 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001670 }
1671}
1672
1673void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001674 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1675 auto &context = contexts[subpass_index];
John Zulaufb02c1eb2020-10-06 16:33:36 -06001676 ApplyTrackbackBarriersAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001677 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001678 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001679 }
1680 }
1681}
1682
John Zulauf355e49b2020-04-24 15:11:15 -06001683// Suitable only for *subpass* access contexts
John Zulauf7635de32020-05-29 17:14:15 -06001684HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const IMAGE_VIEW_STATE *attach_view) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001685 if (!attach_view) return HazardResult();
1686 const auto image_state = attach_view->image_state.get();
1687 if (!image_state) return HazardResult();
1688
John Zulauf355e49b2020-04-24 15:11:15 -06001689 // We should never ask for a transition from a context we don't have
John Zulauf7635de32020-05-29 17:14:15 -06001690 assert(track_back.context);
John Zulauf355e49b2020-04-24 15:11:15 -06001691
1692 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001693 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1694 const auto merged_barrier = MergeBarriers(track_back.barriers);
1695 HazardResult hazard =
1696 track_back.context->DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
1697 attach_view->normalized_subresource_range, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001698 if (!hazard.hazard) {
1699 // The Async hazard check is against the current context's async set.
John Zulaufa0a98292020-09-18 09:30:10 -06001700 hazard = DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001701 attach_view->normalized_subresource_range, kDetectAsync);
1702 }
John Zulaufa0a98292020-09-18 09:30:10 -06001703
John Zulauf355e49b2020-04-24 15:11:15 -06001704 return hazard;
1705}
1706
John Zulaufb02c1eb2020-10-06 16:33:36 -06001707void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
1708 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1709 const ResourceUsageTag &tag) {
1710 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001711 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001712 for (const auto &transition : transitions) {
1713 const auto prev_pass = transition.prev_pass;
1714 const auto attachment_view = attachment_views[transition.attachment];
1715 if (!attachment_view) continue;
1716 const auto *image = attachment_view->image_state.get();
1717 if (!image) continue;
1718 if (!SimpleBinding(*image)) continue;
1719
1720 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1721 assert(trackback);
1722
1723 // Import the attachments into the current context
1724 const auto *prev_context = trackback->context;
1725 assert(prev_context);
1726 const auto address_type = ImageAddressType(*image);
1727 auto &target_map = GetAccessStateMap(address_type);
1728 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
1729 prev_context->ResolveAccessRange(*image, attachment_view->normalized_subresource_range, barrier_action, address_type,
John Zulauf646cc292020-10-23 09:16:45 -06001730 &target_map, &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001731 }
1732
John Zulauf86356ca2020-10-19 11:46:41 -06001733 // If there were no transitions skip this global map walk
1734 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001735 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001736 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001737 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001738}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001739
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001740void CommandBufferAccessContext::ApplyGlobalBarriersToEvents(const SyncExecScope &src, const SyncExecScope &dst) {
1741 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
John Zulauf669dfd52021-01-27 17:15:28 -07001742
1743 auto *events_context = GetCurrentEventsContext();
1744 assert(events_context);
1745 for (auto &event_pair : *events_context) {
John Zulauf4a6105a2020-11-17 15:11:05 -07001746 assert(event_pair.second); // Shouldn't be storing empty
1747 auto &sync_event = *event_pair.second;
1748 // 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 -07001749 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
1750 sync_event.barriers |= dst.exec_scope;
1751 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
John Zulauf4a6105a2020-11-17 15:11:05 -07001752 }
1753 }
1754}
1755
John Zulauf355e49b2020-04-24 15:11:15 -06001756// Class CommandBufferAccessContext: Keep track of resource access state information for a specific command buffer
1757bool CommandBufferAccessContext::ValidateBeginRenderPass(const RENDER_PASS_STATE &rp_state,
1758
1759 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001760 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001761 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
1762 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06001763
John Zulauf86356ca2020-10-19 11:46:41 -06001764 assert(pRenderPassBegin);
1765 if (nullptr == pRenderPassBegin) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06001766
John Zulauf86356ca2020-10-19 11:46:41 -06001767 const uint32_t subpass = 0;
John Zulauf355e49b2020-04-24 15:11:15 -06001768
John Zulauf86356ca2020-10-19 11:46:41 -06001769 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
1770 // hasn't happened yet)
1771 const std::vector<AccessContext> empty_context_vector;
1772 AccessContext temp_context(subpass, queue_flags_, rp_state.subpass_dependencies, empty_context_vector,
1773 const_cast<AccessContext *>(&cb_access_context_));
John Zulauf355e49b2020-04-24 15:11:15 -06001774
John Zulauf86356ca2020-10-19 11:46:41 -06001775 // Create a view list
1776 const auto fb_state = sync_state_->Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
1777 assert(fb_state);
1778 if (nullptr == fb_state) return skip;
1779 // NOTE: Must not use COMMAND_BUFFER_STATE variant of this as RecordCmdBeginRenderPass hasn't run and thus
1780 // the activeRenderPass.* fields haven't been set.
1781 const auto views = sync_state_->GetAttachmentViews(*pRenderPassBegin, *fb_state);
1782
1783 // Validate transitions
John Zulauffaea0ee2021-01-14 14:01:32 -07001784 skip |= temp_context.ValidateLayoutTransitions(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf86356ca2020-10-19 11:46:41 -06001785
1786 // Validate load operations if there were no layout transition hazards
1787 if (!skip) {
1788 temp_context.RecordLayoutTransitions(rp_state, subpass, views, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07001789 skip |= temp_context.ValidateLoadOperation(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06001790 }
John Zulauf86356ca2020-10-19 11:46:41 -06001791
John Zulauf355e49b2020-04-24 15:11:15 -06001792 return skip;
1793}
1794
locke-lunarg61870c22020-06-09 14:51:50 -06001795bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1796 const char *func_name) const {
1797 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001798 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001799 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001800 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1801 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001802 return skip;
1803 }
1804
1805 using DescriptorClass = cvdescriptorset::DescriptorClass;
1806 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1807 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1808 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1809 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1810
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001811 for (const auto &stage_state : pipe->stage_state) {
1812 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1813 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001814 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001815 }
locke-lunarg61870c22020-06-09 14:51:50 -06001816 for (const auto &set_binding : stage_state.descriptor_uses) {
1817 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1818 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1819 set_binding.first.second);
1820 const auto descriptor_type = binding_it.GetType();
1821 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1822 auto array_idx = 0;
1823
1824 if (binding_it.IsVariableDescriptorCount()) {
1825 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1826 }
1827 SyncStageAccessIndex sync_index =
1828 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1829
1830 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1831 uint32_t index = i - index_range.start;
1832 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1833 switch (descriptor->GetClass()) {
1834 case DescriptorClass::ImageSampler:
1835 case DescriptorClass::Image: {
1836 const IMAGE_VIEW_STATE *img_view_state = nullptr;
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001837 VkImageLayout image_layout;
locke-lunarg61870c22020-06-09 14:51:50 -06001838 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001839 const auto image_sampler_descriptor = static_cast<const ImageSamplerDescriptor *>(descriptor);
1840 img_view_state = image_sampler_descriptor->GetImageViewState();
1841 image_layout = image_sampler_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001842 } else {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001843 const auto image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1844 img_view_state = image_descriptor->GetImageViewState();
1845 image_layout = image_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001846 }
1847 if (!img_view_state) continue;
1848 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1849 VkExtent3D extent = {};
1850 VkOffset3D offset = {};
1851 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1852 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1853 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1854 } else {
1855 extent = img_state->createInfo.extent;
1856 }
John Zulauf361fb532020-07-22 10:45:39 -06001857 HazardResult hazard;
1858 const auto &subresource_range = img_view_state->normalized_subresource_range;
1859 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
1860 // Input attachments are subject to raster ordering rules
1861 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001862 SyncOrdering::kRaster, offset, extent);
John Zulauf361fb532020-07-22 10:45:39 -06001863 } else {
1864 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, offset, extent);
1865 }
John Zulauf33fc1d52020-07-17 11:01:10 -06001866 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001867 skip |= sync_state_->LogError(
1868 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001869 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1870 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001871 func_name, string_SyncHazard(hazard.hazard),
1872 sync_state_->report_data->FormatHandle(img_view_state->image_view).c_str(),
1873 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001874 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001875 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1876 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauffaea0ee2021-01-14 14:01:32 -07001877 set_binding.first.second, index, FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001878 }
1879 break;
1880 }
1881 case DescriptorClass::TexelBuffer: {
1882 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1883 if (!buf_view_state) continue;
1884 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06001885 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06001886 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06001887 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001888 skip |= sync_state_->LogError(
1889 buf_view_state->buffer_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001890 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1891 func_name, string_SyncHazard(hazard.hazard),
locke-lunarg88dbb542020-06-23 22:05:42 -06001892 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view).c_str(),
1893 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001894 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001895 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1896 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001897 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001898 }
1899 break;
1900 }
1901 case DescriptorClass::GeneralBuffer: {
1902 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
1903 auto buf_state = buffer_descriptor->GetBufferState();
1904 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06001905 const ResourceAccessRange range =
1906 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06001907 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06001908 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001909 skip |= sync_state_->LogError(
1910 buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001911 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1912 func_name, string_SyncHazard(hazard.hazard),
1913 sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
locke-lunarg88dbb542020-06-23 22:05:42 -06001914 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001915 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001916 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1917 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001918 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001919 }
1920 break;
1921 }
1922 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
1923 default:
1924 break;
1925 }
1926 }
1927 }
1928 }
1929 return skip;
1930}
1931
1932void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1933 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001934 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001935 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001936 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1937 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001938 return;
1939 }
1940
1941 using DescriptorClass = cvdescriptorset::DescriptorClass;
1942 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1943 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1944 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1945 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1946
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001947 for (const auto &stage_state : pipe->stage_state) {
1948 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1949 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001950 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001951 }
locke-lunarg61870c22020-06-09 14:51:50 -06001952 for (const auto &set_binding : stage_state.descriptor_uses) {
1953 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1954 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1955 set_binding.first.second);
1956 const auto descriptor_type = binding_it.GetType();
1957 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1958 auto array_idx = 0;
1959
1960 if (binding_it.IsVariableDescriptorCount()) {
1961 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1962 }
1963 SyncStageAccessIndex sync_index =
1964 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1965
1966 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1967 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1968 switch (descriptor->GetClass()) {
1969 case DescriptorClass::ImageSampler:
1970 case DescriptorClass::Image: {
1971 const IMAGE_VIEW_STATE *img_view_state = nullptr;
1972 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
1973 img_view_state = static_cast<const ImageSamplerDescriptor *>(descriptor)->GetImageViewState();
1974 } else {
1975 img_view_state = static_cast<const ImageDescriptor *>(descriptor)->GetImageViewState();
1976 }
1977 if (!img_view_state) continue;
1978 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1979 VkExtent3D extent = {};
1980 VkOffset3D offset = {};
1981 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1982 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1983 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1984 } else {
1985 extent = img_state->createInfo.extent;
1986 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001987 SyncOrdering ordering_rule = (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)
1988 ? SyncOrdering::kRaster
1989 : SyncOrdering::kNonAttachment;
1990 current_context_->UpdateAccessState(*img_state, sync_index, ordering_rule,
1991 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06001992 break;
1993 }
1994 case DescriptorClass::TexelBuffer: {
1995 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1996 if (!buf_view_state) continue;
1997 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06001998 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001999 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002000 break;
2001 }
2002 case DescriptorClass::GeneralBuffer: {
2003 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
2004 auto buf_state = buffer_descriptor->GetBufferState();
2005 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06002006 const ResourceAccessRange range =
2007 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002008 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002009 break;
2010 }
2011 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2012 default:
2013 break;
2014 }
2015 }
2016 }
2017 }
2018}
2019
2020bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2021 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002022 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2023 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002024 return skip;
2025 }
2026
2027 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2028 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002029 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002030
2031 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002032 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002033 if (binding_description.binding < binding_buffers_size) {
2034 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002035 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002036
locke-lunarg1ae57d62020-11-18 10:49:19 -07002037 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002038 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2039 vertexCount, binding_description.stride);
locke-lunarg61870c22020-06-09 14:51:50 -06002040 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range);
2041 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002042 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002043 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 -06002044 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002045 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002046 }
2047 }
2048 }
2049 return skip;
2050}
2051
2052void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002053 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2054 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002055 return;
2056 }
2057 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2058 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002059 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002060
2061 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002062 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002063 if (binding_description.binding < binding_buffers_size) {
2064 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002065 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002066
locke-lunarg1ae57d62020-11-18 10:49:19 -07002067 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002068 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2069 vertexCount, binding_description.stride);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002070 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, SyncOrdering::kNonAttachment,
2071 range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002072 }
2073 }
2074}
2075
2076bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2077 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002078 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->destroyed) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002079 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002080 }
locke-lunarg61870c22020-06-09 14:51:50 -06002081
locke-lunarg1ae57d62020-11-18 10:49:19 -07002082 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002083 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002084 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2085 firstIndex, indexCount, index_size);
locke-lunarg61870c22020-06-09 14:51:50 -06002086 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range);
2087 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002088 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002089 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 -06002090 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002091 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002092 }
2093
2094 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2095 // We will detect more accurate range in the future.
2096 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2097 return skip;
2098}
2099
2100void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag &tag) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002101 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 -06002102
locke-lunarg1ae57d62020-11-18 10:49:19 -07002103 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002104 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002105 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2106 firstIndex, indexCount, index_size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002107 current_context_->UpdateAccessState(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002108
2109 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2110 // We will detect more accurate range in the future.
2111 RecordDrawVertex(UINT32_MAX, 0, tag);
2112}
2113
2114bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002115 bool skip = false;
2116 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002117 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(*this, *cb_state_.get(),
locke-lunarg7077d502020-06-18 21:37:26 -06002118 cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
2119 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002120}
2121
2122void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002123 if (current_renderpass_context_) {
locke-lunarg7077d502020-06-18 21:37:26 -06002124 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea,
2125 tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002126 }
locke-lunarg61870c22020-06-09 14:51:50 -06002127}
2128
John Zulauf355e49b2020-04-24 15:11:15 -06002129bool CommandBufferAccessContext::ValidateNextSubpass(const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002130 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002131 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002132 skip |= current_renderpass_context_->ValidateNextSubpass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002133
2134 return skip;
2135}
2136
2137bool CommandBufferAccessContext::ValidateEndRenderpass(const char *func_name) const {
2138 // TODO: Things to add here.
John Zulauf7635de32020-05-29 17:14:15 -06002139 // Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002140 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002141 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002142 skip |= current_renderpass_context_->ValidateEndRenderPass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002143
2144 return skip;
2145}
2146
2147void CommandBufferAccessContext::RecordBeginRenderPass(const ResourceUsageTag &tag) {
2148 assert(sync_state_);
2149 if (!cb_state_) return;
2150
2151 // Create an access context the current renderpass.
John Zulauf1a224292020-06-30 14:52:13 -06002152 render_pass_contexts_.emplace_back();
John Zulauf16adfc92020-04-08 10:28:33 -06002153 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf1a224292020-06-30 14:52:13 -06002154 current_renderpass_context_->RecordBeginRenderPass(*sync_state_, *cb_state_, &cb_access_context_, queue_flags_, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002155 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf16adfc92020-04-08 10:28:33 -06002156}
2157
John Zulauffaea0ee2021-01-14 14:01:32 -07002158void CommandBufferAccessContext::RecordNextSubpass(const RENDER_PASS_STATE &rp_state, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002159 assert(current_renderpass_context_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002160 auto prev_tag = NextCommandTag(command);
2161 auto next_tag = NextSubcommandTag(command);
2162 current_renderpass_context_->RecordNextSubpass(cb_state_->activeRenderPassBeginInfo.renderArea, prev_tag, next_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002163 current_context_ = &current_renderpass_context_->CurrentContext();
2164}
2165
John Zulauffaea0ee2021-01-14 14:01:32 -07002166void CommandBufferAccessContext::RecordEndRenderPass(const RENDER_PASS_STATE &render_pass, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002167 assert(current_renderpass_context_);
2168 if (!current_renderpass_context_) return;
2169
John Zulauffaea0ee2021-01-14 14:01:32 -07002170 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, cb_state_->activeRenderPassBeginInfo.renderArea,
2171 NextCommandTag(command));
John Zulauf355e49b2020-04-24 15:11:15 -06002172 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002173 current_renderpass_context_ = nullptr;
2174}
2175
John Zulauf49beb112020-11-04 16:06:31 -07002176bool CommandBufferAccessContext::ValidateSetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2177 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002178 // I'll put this here just in case we need to pass this in for future extension support
2179 const auto cmd = CMD_SETEVENT;
2180 bool skip = false;
John Zulauf669dfd52021-01-27 17:15:28 -07002181 const auto *event_state = sync_state_->Get<EVENT_STATE>(event);
2182 if (!event_state) return skip;
2183
2184 const auto *sync_event = GetCurrentEventsContext()->Get(event_state);
John Zulauf4a6105a2020-11-17 15:11:05 -07002185 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2186
2187 const char *const reset_set =
2188 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2189 "hazards.";
2190 const char *const wait =
2191 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
2192
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002193 const auto exec_scope = sync_utils::WithEarlierPipelineStages(sync_utils::ExpandPipelineStages(stageMask, GetQueueFlags()));
John Zulauf4a6105a2020-11-17 15:11:05 -07002194 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2195 const char *vuid = nullptr;
2196 const char *message = nullptr;
2197 switch (sync_event->last_command) {
2198 case CMD_RESETEVENT:
2199 // Needs a barrier between reset and set
2200 vuid = "SYNC-vkCmdSetEvent-missingbarrier-reset";
2201 message = reset_set;
2202 break;
2203 case CMD_SETEVENT:
2204 // Needs a barrier between set and set
2205 vuid = "SYNC-vkCmdSetEvent-missingbarrier-set";
2206 message = reset_set;
2207 break;
2208 case CMD_WAITEVENTS:
2209 // Needs a barrier or is in second execution scope
2210 vuid = "SYNC-vkCmdSetEvent-missingbarrier-wait";
2211 message = wait;
2212 break;
2213 default:
2214 // The only other valid last command that wasn't one.
2215 assert(sync_event->last_command == CMD_NONE);
2216 break;
2217 }
2218 if (vuid) {
2219 assert(nullptr != message);
2220 const char *const cmd_name = CommandTypeString(cmd);
2221 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2222 cmd_name, CommandTypeString(sync_event->last_command));
2223 }
2224 }
2225
2226 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002227}
2228
John Zulauf4a6105a2020-11-17 15:11:05 -07002229void CommandBufferAccessContext::RecordSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask,
2230 const ResourceUsageTag &tag) {
John Zulauf669dfd52021-01-27 17:15:28 -07002231 auto event_state_shared = sync_state_->GetShared<EVENT_STATE>(event);
2232 if (!event_state_shared.get()) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2233
2234 auto *sync_event = GetCurrentEventsContext()->GetFromShared(event_state_shared);
John Zulauf4a6105a2020-11-17 15:11:05 -07002235 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2236
2237 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
2238 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
2239 // any issues caused by naive scope setting here.
2240
2241 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
2242 // Given:
2243 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
2244 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002245 auto scope = SyncExecScope::MakeSrc(GetQueueFlags(), stageMask);
John Zulauf4a6105a2020-11-17 15:11:05 -07002246
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002247 if (!sync_event->HasBarrier(stageMask, scope.exec_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002248 sync_event->unsynchronized_set = sync_event->last_command;
2249 sync_event->ResetFirstScope();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002250 } else if (sync_event->scope.exec_scope == 0) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002251 // We only set the scope if there isn't one
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002252 sync_event->scope = scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07002253
2254 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
2255 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002256 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002257 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
2258 }
2259 };
2260 GetCurrentAccessContext()->ForAll(set_scope);
2261 sync_event->unsynchronized_set = CMD_NONE;
2262 sync_event->first_scope_tag = tag;
2263 }
2264 sync_event->last_command = CMD_SETEVENT;
2265 sync_event->barriers = 0U;
2266}
John Zulauf49beb112020-11-04 16:06:31 -07002267
2268bool CommandBufferAccessContext::ValidateResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2269 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002270 // I'll put this here just in case we need to pass this in for future extension support
2271 const auto cmd = CMD_RESETEVENT;
2272
2273 bool skip = false;
2274 // TODO: EVENTS:
2275 // 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 -07002276 auto event_state = sync_state_->Get<EVENT_STATE>(event);
2277 if (!event_state) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
2278
2279 const auto *sync_event = GetCurrentEventsContext()->Get(event_state);
John Zulauf4a6105a2020-11-17 15:11:05 -07002280 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2281
2282 const char *const set_wait =
2283 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2284 "hazards.";
2285 const char *message = set_wait; // Only one message this call.
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002286 const auto exec_scope = sync_utils::WithEarlierPipelineStages(sync_utils::ExpandPipelineStages(stageMask, GetQueueFlags()));
John Zulauf4a6105a2020-11-17 15:11:05 -07002287 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2288 const char *vuid = nullptr;
2289 switch (sync_event->last_command) {
2290 case CMD_SETEVENT:
2291 // Needs a barrier between set and reset
2292 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
2293 break;
2294 case CMD_WAITEVENTS: {
2295 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
2296 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
2297 break;
2298 }
2299 default:
2300 // The only other valid last command that wasn't one.
2301 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT));
2302 break;
2303 }
2304 if (vuid) {
2305 const char *const cmd_name = CommandTypeString(cmd);
2306 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2307 cmd_name, CommandTypeString(sync_event->last_command));
2308 }
2309 }
2310 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002311}
2312
John Zulauf4a6105a2020-11-17 15:11:05 -07002313void CommandBufferAccessContext::RecordResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
2314 const auto cmd = CMD_RESETEVENT;
John Zulauf669dfd52021-01-27 17:15:28 -07002315 auto event_state_shared = sync_state_->GetShared<EVENT_STATE>(event);
2316 if (!event_state_shared.get()) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2317
2318 auto *sync_event = GetCurrentEventsContext()->GetFromShared(event_state_shared);
John Zulauf4a6105a2020-11-17 15:11:05 -07002319 if (!sync_event) return;
John Zulauf49beb112020-11-04 16:06:31 -07002320
John Zulauf4a6105a2020-11-17 15:11:05 -07002321 // Clear out the first sync scope, any races vs. wait or set are reported, so we'll keep the bookkeeping simple assuming
2322 // the safe case
2323 for (const auto address_type : kAddressTypes) {
2324 sync_event->first_scope[static_cast<size_t>(address_type)].clear();
2325 }
2326
2327 // Update the event state
2328 sync_event->last_command = cmd;
2329 sync_event->unsynchronized_set = CMD_NONE;
2330 sync_event->ResetFirstScope();
2331 sync_event->barriers = 0U;
2332}
2333
John Zulauf4a6105a2020-11-17 15:11:05 -07002334void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2335 // Erase is okay with the key not being
John Zulauf669dfd52021-01-27 17:15:28 -07002336 const auto *event_state = sync_state_->Get<EVENT_STATE>(event);
2337 if (event_state) {
2338 GetCurrentEventsContext()->Destroy(event_state);
John Zulaufd5115702021-01-18 12:34:33 -07002339 }
2340}
2341
John Zulauffaea0ee2021-01-14 14:01:32 -07002342bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandBufferAccessContext &cb_context,
2343 const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2344 const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002345 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002346 const auto &sync_state = cb_context.GetSyncState();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002347 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2348 if (!pipe ||
2349 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002350 return skip;
2351 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002352 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002353 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2354 VkExtent3D extent = CastTo3D(render_area.extent);
2355 VkOffset3D offset = CastTo3D(render_area.offset);
locke-lunarg37047832020-06-12 13:44:45 -06002356
John Zulauf1a224292020-06-30 14:52:13 -06002357 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002358 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002359 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2360 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002361 if (location >= subpass.colorAttachmentCount ||
2362 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002363 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002364 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002365 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf1a224292020-06-30 14:52:13 -06002366 HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002367 SyncOrdering::kColorAttachment, offset, extent);
locke-lunarg96dc9632020-06-10 17:22:18 -06002368 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002369 skip |= sync_state.LogError(img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002370 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002371 func_name, string_SyncHazard(hazard.hazard),
2372 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2373 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002374 location, cb_context.FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002375 }
2376 }
2377 }
locke-lunarg37047832020-06-12 13:44:45 -06002378
2379 // PHASE1 TODO: Add layout based read/vs. write selection.
2380 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002381 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002382 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002383 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002384 bool depth_write = false, stencil_write = false;
2385
2386 // PHASE1 TODO: These validation should be in core_checks.
2387 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002388 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2389 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002390 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2391 depth_write = true;
2392 }
2393 // PHASE1 TODO: It needs to check if stencil is writable.
2394 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2395 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2396 // PHASE1 TODO: These validation should be in core_checks.
2397 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002398 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002399 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2400 stencil_write = true;
2401 }
2402
2403 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2404 if (depth_write) {
2405 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002406 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002407 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002408 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002409 skip |= sync_state.LogError(
2410 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002411 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002412 func_name, string_SyncHazard(hazard.hazard),
2413 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2414 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002415 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002416 }
2417 }
2418 if (stencil_write) {
2419 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002420 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002421 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002422 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002423 skip |= sync_state.LogError(
2424 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002425 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002426 func_name, string_SyncHazard(hazard.hazard),
2427 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2428 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002429 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002430 }
locke-lunarg61870c22020-06-09 14:51:50 -06002431 }
2432 }
2433 return skip;
2434}
2435
locke-lunarg96dc9632020-06-10 17:22:18 -06002436void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2437 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002438 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2439 if (!pipe ||
2440 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002441 return;
2442 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002443 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002444 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2445 VkExtent3D extent = CastTo3D(render_area.extent);
2446 VkOffset3D offset = CastTo3D(render_area.offset);
2447
John Zulauf1a224292020-06-30 14:52:13 -06002448 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002449 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002450 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2451 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002452 if (location >= subpass.colorAttachmentCount ||
2453 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002454 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002455 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002456 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf8e3c3e92021-01-06 11:19:36 -07002457 current_context.UpdateAccessState(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
2458 SyncOrdering::kColorAttachment, offset, extent, 0, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002459 }
2460 }
locke-lunarg37047832020-06-12 13:44:45 -06002461
2462 // PHASE1 TODO: Add layout based read/vs. write selection.
2463 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002464 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002465 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002466 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002467 bool depth_write = false, stencil_write = false;
2468
2469 // PHASE1 TODO: These validation should be in core_checks.
2470 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002471 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2472 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002473 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2474 depth_write = true;
2475 }
2476 // PHASE1 TODO: It needs to check if stencil is writable.
2477 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2478 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2479 // PHASE1 TODO: These validation should be in core_checks.
2480 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002481 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002482 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2483 stencil_write = true;
2484 }
2485
2486 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2487 if (depth_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002488 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2489 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT,
2490 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002491 }
2492 if (stencil_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002493 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2494 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT,
2495 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002496 }
locke-lunarg61870c22020-06-09 14:51:50 -06002497 }
2498}
2499
John Zulauffaea0ee2021-01-14 14:01:32 -07002500bool RenderPassAccessContext::ValidateNextSubpass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf1507ee42020-05-18 11:33:09 -06002501 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002502 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002503 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002504 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002505 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002506 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002507 func_name);
2508
John Zulauf355e49b2020-04-24 15:11:15 -06002509 const auto next_subpass = current_subpass_ + 1;
John Zulauf1507ee42020-05-18 11:33:09 -06002510 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauffaea0ee2021-01-14 14:01:32 -07002511 skip |= next_context.ValidateLayoutTransitions(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002512 if (!skip) {
2513 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2514 // on a copy of the (empty) next context.
2515 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2516 AccessContext temp_context(next_context);
2517 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07002518 skip |= temp_context.ValidateLoadOperation(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002519 }
John Zulauf7635de32020-05-29 17:14:15 -06002520 return skip;
2521}
John Zulauffaea0ee2021-01-14 14:01:32 -07002522bool RenderPassAccessContext::ValidateEndRenderPass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf7635de32020-05-29 17:14:15 -06002523 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002524 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002525 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002526 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002527 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002528 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002529 func_name);
John Zulauffaea0ee2021-01-14 14:01:32 -07002530 skip |= ValidateFinalSubpassLayoutTransitions(cb_context, render_area, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002531 return skip;
2532}
2533
John Zulauf7635de32020-05-29 17:14:15 -06002534AccessContext *RenderPassAccessContext::CreateStoreResolveProxy(const VkRect2D &render_area) const {
2535 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, render_area, attachment_views_);
2536}
2537
John Zulauffaea0ee2021-01-14 14:01:32 -07002538bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandBufferAccessContext &cb_context,
2539 const VkRect2D &render_area, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002540 bool skip = false;
2541
John Zulauf7635de32020-05-29 17:14:15 -06002542 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2543 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2544 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2545 // to apply and only copy then, if this proves a hot spot.
2546 std::unique_ptr<AccessContext> proxy_for_current;
2547
John Zulauf355e49b2020-04-24 15:11:15 -06002548 // Validate the "finalLayout" transitions to external
2549 // Get them from where there we're hidding in the extra entry.
2550 const auto &final_transitions = rp_state_->subpass_transitions.back();
2551 for (const auto &transition : final_transitions) {
2552 const auto &attach_view = attachment_views_[transition.attachment];
2553 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
2554 assert(trackback.context); // Transitions are given implicit transitions if the StateTracker is working correctly
John Zulauf7635de32020-05-29 17:14:15 -06002555 auto *context = trackback.context;
2556
2557 if (transition.prev_pass == current_subpass_) {
2558 if (!proxy_for_current) {
2559 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
2560 proxy_for_current.reset(CreateStoreResolveProxy(render_area));
2561 }
2562 context = proxy_for_current.get();
2563 }
2564
John Zulaufa0a98292020-09-18 09:30:10 -06002565 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2566 const auto merged_barrier = MergeBarriers(trackback.barriers);
2567 auto hazard = context->DetectImageBarrierHazard(*attach_view->image_state, merged_barrier.src_exec_scope,
2568 merged_barrier.src_access_scope, attach_view->normalized_subresource_range,
2569 AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002570 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -07002571 skip |= cb_context.GetSyncState().LogError(
2572 rp_state_->renderPass, string_SyncHazardVUID(hazard.hazard),
2573 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2574 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2575 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2576 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
2577 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06002578 }
2579 }
2580 return skip;
2581}
2582
2583void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag &tag) {
2584 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002585 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002586}
2587
John Zulauf1507ee42020-05-18 11:33:09 -06002588void RenderPassAccessContext::RecordLoadOperations(const VkRect2D &render_area, const ResourceUsageTag &tag) {
2589 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2590 auto &subpass_context = subpass_contexts_[current_subpass_];
2591 VkExtent3D extent = CastTo3D(render_area.extent);
2592 VkOffset3D offset = CastTo3D(render_area.offset);
2593
2594 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2595 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
2596 if (attachment_views_[i] == nullptr) continue; // UNUSED
2597 const auto &view = *attachment_views_[i];
2598 const IMAGE_STATE *image = view.image_state.get();
2599 if (image == nullptr) continue;
2600
2601 const auto &ci = attachment_ci[i];
2602 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002603 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002604 const bool is_color = !(has_depth || has_stencil);
2605
2606 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002607 subpass_context.UpdateAccessState(*image, ColorLoadUsage(ci.loadOp), SyncOrdering::kColorAttachment,
2608 view.normalized_subresource_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002609 } else {
2610 auto update_range = view.normalized_subresource_range;
2611 if (has_depth) {
2612 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002613 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.loadOp),
2614 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002615 }
2616 if (has_stencil) {
2617 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002618 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.stencilLoadOp),
2619 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002620 }
2621 }
2622 }
2623 }
2624}
2625
John Zulauf355e49b2020-04-24 15:11:15 -06002626void RenderPassAccessContext::RecordBeginRenderPass(const SyncValidator &state, const CMD_BUFFER_STATE &cb_state,
John Zulauf1a224292020-06-30 14:52:13 -06002627 const AccessContext *external_context, VkQueueFlags queue_flags,
2628 const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002629 current_subpass_ = 0;
locke-lunargaecf2152020-05-12 17:15:41 -06002630 rp_state_ = cb_state.activeRenderPass.get();
John Zulauf355e49b2020-04-24 15:11:15 -06002631 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
2632 // Add this for all subpasses here so that they exsist during next subpass validation
2633 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002634 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulauf355e49b2020-04-24 15:11:15 -06002635 }
2636 attachment_views_ = state.GetCurrentAttachmentViews(cb_state);
2637
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002638 subpass_contexts_[current_subpass_].SetStartTag(tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002639 RecordLayoutTransitions(tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002640 RecordLoadOperations(cb_state.activeRenderPassBeginInfo.renderArea, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002641}
John Zulauf1507ee42020-05-18 11:33:09 -06002642
John Zulauffaea0ee2021-01-14 14:01:32 -07002643void RenderPassAccessContext::RecordNextSubpass(const VkRect2D &render_area, const ResourceUsageTag &prev_subpass_tag,
2644 const ResourceUsageTag &next_subpass_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002645 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauffaea0ee2021-01-14 14:01:32 -07002646 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
2647 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002648
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002649 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2650 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002651 current_subpass_++;
2652 assert(current_subpass_ < subpass_contexts_.size());
John Zulauffaea0ee2021-01-14 14:01:32 -07002653 subpass_contexts_[current_subpass_].SetStartTag(next_subpass_tag);
2654 RecordLayoutTransitions(next_subpass_tag);
2655 RecordLoadOperations(render_area, next_subpass_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002656}
2657
John Zulauf1a224292020-06-30 14:52:13 -06002658void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const VkRect2D &render_area,
2659 const ResourceUsageTag &tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002660 // Add the resolve and store accesses
John Zulauf7635de32020-05-29 17:14:15 -06002661 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulaufaff20662020-06-01 14:07:58 -06002662 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulauf7635de32020-05-29 17:14:15 -06002663
John Zulauf355e49b2020-04-24 15:11:15 -06002664 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002665 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002666
2667 // Add the "finalLayout" transitions to external
2668 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002669 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2670 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2671 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002672 const auto &final_transitions = rp_state_->subpass_transitions.back();
2673 for (const auto &transition : final_transitions) {
2674 const auto &attachment = attachment_views_[transition.attachment];
2675 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufaa97d8b2020-07-14 10:58:13 -06002676 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.context);
John Zulaufd5115702021-01-18 12:34:33 -07002677 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002678 for (const auto &barrier : last_trackback.barriers) {
John Zulaufd5115702021-01-18 12:34:33 -07002679 barrier_action.EmplaceBack(PipelineBarrierOp(barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002680 }
John Zulauf1e331ec2020-12-04 18:29:38 -07002681 external_context->UpdateResourceAccess(*attachment->image_state, attachment->normalized_subresource_range, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002682 }
2683}
2684
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002685SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2686 SyncExecScope result;
2687 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002688 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2689 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002690 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2691 return result;
2692}
2693
2694SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2695 SyncExecScope result;
2696 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002697 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2698 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002699 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2700 return result;
2701}
2702
2703SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
2704 src_exec_scope = src.exec_scope;
2705 src_access_scope = 0;
2706 dst_exec_scope = dst.exec_scope;
2707 dst_access_scope = 0;
2708}
2709
2710template <typename Barrier>
2711SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
2712 src_exec_scope = src.exec_scope;
2713 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2714 dst_exec_scope = dst.exec_scope;
2715 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2716}
2717
2718SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
2719 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
2720 src_exec_scope = src.exec_scope;
2721 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2722
2723 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
2724 dst_exec_scope = dst.exec_scope;
2725 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002726}
2727
John Zulaufb02c1eb2020-10-06 16:33:36 -06002728// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2729void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
2730 for (const auto &barrier : barriers) {
2731 ApplyBarrier(barrier, layout_transition);
2732 }
2733}
2734
John Zulauf89311b42020-09-29 16:28:47 -06002735// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2736// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2737// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufb02c1eb2020-10-06 16:33:36 -06002738void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, const ResourceUsageTag &tag) {
2739 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002740 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002741 assert(!pending_write_dep_chain);
John Zulaufa0a98292020-09-18 09:30:10 -06002742 for (const auto &barrier : barriers) {
John Zulauf89311b42020-09-29 16:28:47 -06002743 ApplyBarrier(barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002744 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002745 ApplyPendingBarriers(tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002746}
John Zulauf9cb530d2019-09-30 14:14:10 -06002747HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2748 HazardResult hazard;
2749 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002750 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002751 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002752 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002753 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002754 }
2755 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002756 // Write operation:
2757 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2758 // If reads exists -- test only against them because either:
2759 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2760 // * 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
2761 // the current write happens after the reads, so just test the write against the reades
2762 // Otherwise test against last_write
2763 //
2764 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002765 if (last_reads.size()) {
2766 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002767 if (IsReadHazard(usage_stage, read_access)) {
2768 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2769 break;
2770 }
2771 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002772 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002773 // Write-After-Write check -- if we have a previous write to test against
2774 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002775 }
2776 }
2777 return hazard;
2778}
2779
John Zulauf8e3c3e92021-01-06 11:19:36 -07002780HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering &ordering_rule) const {
2781 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06002782 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2783 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002784 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002785 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002786 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2787 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002788 if (IsRead(usage_bit)) {
2789 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2790 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2791 if (is_raw_hazard) {
2792 // NOTE: we know last_write is non-zero
2793 // See if the ordering rules save us from the simple RAW check above
2794 // First check to see if the current usage is covered by the ordering rules
2795 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2796 const bool usage_is_ordered =
2797 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2798 if (usage_is_ordered) {
2799 // Now see of the most recent write (or a subsequent read) are ordered
2800 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2801 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002802 }
2803 }
John Zulauf4285ee92020-09-23 10:20:52 -06002804 if (is_raw_hazard) {
2805 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
2806 }
John Zulauf361fb532020-07-22 10:45:39 -06002807 } else {
2808 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002809 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07002810 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06002811 // Look for any WAR hazards outside the ordered set of stages
John Zulauf4285ee92020-09-23 10:20:52 -06002812 VkPipelineStageFlags ordered_stages = 0;
2813 if (usage_write_is_ordered) {
2814 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
2815 ordered_stages = GetOrderedStages(ordering);
2816 }
2817 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
2818 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07002819 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06002820 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
2821 if (IsReadHazard(usage_stage, read_access)) {
2822 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2823 break;
2824 }
John Zulaufd14743a2020-07-03 09:42:39 -06002825 }
2826 }
John Zulauf4285ee92020-09-23 10:20:52 -06002827 } else if (!(last_write_is_ordered && usage_write_is_ordered)) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002828 if (last_write.any() && IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002829 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06002830 }
John Zulauf69133422020-05-20 14:55:53 -06002831 }
2832 }
2833 return hazard;
2834}
2835
John Zulauf2f952d22020-02-10 11:34:51 -07002836// Asynchronous Hazards occur between subpasses with no connection through the DAG
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002837HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag &start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07002838 HazardResult hazard;
2839 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002840 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
2841 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
2842 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07002843 if (IsRead(usage)) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002844 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002845 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07002846 }
2847 } else {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002848 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002849 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07002850 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002851 // 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 -07002852 for (const auto &read_access : last_reads) {
2853 if (read_access.tag.index >= start_tag.index) {
2854 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002855 break;
2856 }
2857 }
John Zulauf2f952d22020-02-10 11:34:51 -07002858 }
2859 }
2860 return hazard;
2861}
2862
John Zulauf36bcf6a2020-02-03 15:12:52 -07002863HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002864 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07002865 // Only supporting image layout transitions for now
2866 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2867 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06002868 // only test for WAW if there no intervening read operations.
2869 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07002870 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06002871 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07002872 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002873 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06002874 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07002875 break;
2876 }
2877 }
John Zulauf4a6105a2020-11-17 15:11:05 -07002878 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2879 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2880 }
2881
2882 return hazard;
2883}
2884
2885HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
2886 const SyncStageAccessFlags &src_access_scope,
2887 const ResourceUsageTag &event_tag) const {
2888 // Only supporting image layout transitions for now
2889 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2890 HazardResult hazard;
2891 // only test for WAW if there no intervening read operations.
2892 // See DetectHazard(SyncStagetAccessIndex) above for more details.
2893
John Zulaufab7756b2020-12-29 16:10:16 -07002894 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002895 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
2896 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07002897 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002898 if (read_access.tag.IsBefore(event_tag)) {
2899 // The read is in the events first synchronization scope, so we use a barrier hazard check
2900 // If the read stage is not in the src sync scope
2901 // *AND* not execution chained with an existing sync barrier (that's the or)
2902 // then the barrier access is unsafe (R/W after R)
2903 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
2904 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2905 break;
2906 }
2907 } else {
2908 // The read not in the event first sync scope and so is a hazard vs. the layout transition
2909 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2910 }
2911 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002912 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002913 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
2914 if (write_tag.IsBefore(event_tag)) {
2915 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
2916 // So do a normal barrier hazard check
2917 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2918 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2919 }
2920 } else {
2921 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06002922 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2923 }
John Zulaufd14743a2020-07-03 09:42:39 -06002924 }
John Zulauf361fb532020-07-22 10:45:39 -06002925
John Zulauf0cb5be22020-01-23 12:18:22 -07002926 return hazard;
2927}
2928
John Zulauf5f13a792020-03-10 07:31:21 -06002929// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
2930// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
2931// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
2932void ResourceAccessState::Resolve(const ResourceAccessState &other) {
2933 if (write_tag.IsBefore(other.write_tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002934 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
2935 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06002936 *this = other;
2937 } else if (!other.write_tag.IsBefore(write_tag)) {
2938 // This is the *equals* case for write operations, we merged the write barriers and the read state (but without the
2939 // dependency chaining logic or any stage expansion)
2940 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002941 pending_write_barriers |= other.pending_write_barriers;
2942 pending_layout_transition |= other.pending_layout_transition;
2943 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06002944
John Zulaufd14743a2020-07-03 09:42:39 -06002945 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07002946 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06002947 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07002948 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06002949 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06002950 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06002951 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06002952 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
2953 // but we should wait on profiling data for that.
2954 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06002955 auto &my_read = last_reads[my_read_index];
2956 if (other_read.stage == my_read.stage) {
2957 if (my_read.tag.IsBefore(other_read.tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002958 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06002959 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06002960 my_read.tag = other_read.tag;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002961 my_read.pending_dep_chain = other_read.pending_dep_chain;
2962 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
2963 // May require tracking more than one access per stage.
2964 my_read.barriers = other_read.barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06002965 if (my_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
2966 // Since I'm overwriting the fragement stage read, also update the input attachment info
2967 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06002968 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06002969 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002970 } else if (other_read.tag.IsBefore(my_read.tag)) {
2971 // The read tags match so merge the barriers
2972 my_read.barriers |= other_read.barriers;
2973 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06002974 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002975
John Zulauf5f13a792020-03-10 07:31:21 -06002976 break;
2977 }
2978 }
2979 } else {
2980 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07002981 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06002982 last_read_stages |= other_read.stage;
John Zulauf4285ee92020-09-23 10:20:52 -06002983 if (other_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06002984 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06002985 }
John Zulauf5f13a792020-03-10 07:31:21 -06002986 }
2987 }
John Zulauf361fb532020-07-22 10:45:39 -06002988 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06002989 } // the else clause would be that other write is before this write... in which case we supercede the other state and
2990 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07002991
2992 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
2993 // of the copy and other into this using the update first logic.
2994 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
2995 // of the other first_accesses... )
2996 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
2997 FirstAccesses firsts(std::move(first_accesses_));
2998 first_accesses_.clear();
2999 first_read_stages_ = 0U;
3000 auto a = firsts.begin();
3001 auto a_end = firsts.end();
3002 for (auto &b : other.first_accesses_) {
3003 // TODO: Determine whether "IsBefore" or "IsGloballyBefore" is needed...
3004 while (a != a_end && a->tag.IsBefore(b.tag)) {
3005 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3006 ++a;
3007 }
3008 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3009 }
3010 for (; a != a_end; ++a) {
3011 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3012 }
3013 }
John Zulauf5f13a792020-03-10 07:31:21 -06003014}
3015
John Zulauf8e3c3e92021-01-06 11:19:36 -07003016void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag &tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003017 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3018 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003019 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003020 // Mulitple outstanding reads may be of interest and do dependency chains independently
3021 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3022 const auto usage_stage = PipelineStageBit(usage_index);
3023 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003024 for (auto &read_access : last_reads) {
3025 if (read_access.stage == usage_stage) {
3026 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003027 break;
3028 }
3029 }
3030 } else {
John Zulaufab7756b2020-12-29 16:10:16 -07003031 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003032 last_read_stages |= usage_stage;
3033 }
John Zulauf4285ee92020-09-23 10:20:52 -06003034
3035 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
3036 if (usage_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003037 // TODO Revisit re: multiple reads for a given stage
3038 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003039 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003040 } else {
3041 // Assume write
3042 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003043 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003044 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003045 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003046}
John Zulauf5f13a792020-03-10 07:31:21 -06003047
John Zulauf89311b42020-09-29 16:28:47 -06003048// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3049// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3050// We can overwrite them as *this* write is now after them.
3051//
3052// 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 -07003053void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag &tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003054 last_reads.clear();
John Zulauf89311b42020-09-29 16:28:47 -06003055 last_read_stages = 0;
3056 read_execution_barriers = 0;
John Zulauff51fbb62020-10-02 14:43:24 -06003057 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
John Zulauf89311b42020-09-29 16:28:47 -06003058
3059 write_barriers = 0;
3060 write_dependency_chain = 0;
3061 write_tag = tag;
3062 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003063}
3064
John Zulauf89311b42020-09-29 16:28:47 -06003065// Apply the memory barrier without updating the existing barriers. The execution barrier
3066// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3067// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3068// replace the current write barriers or add to them, so accumulate to pending as well.
3069void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) {
3070 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3071 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003072 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
3073 // transistion, under the theory of "most recent access". If the read/write *isn't* safe
3074 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3075 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulauf4a6105a2020-11-17 15:11:05 -07003076 if (layout_transition || WriteInSourceScopeOrChain(barrier.src_exec_scope, barrier.src_access_scope)) {
John Zulauf89311b42020-09-29 16:28:47 -06003077 pending_write_barriers |= barrier.dst_access_scope;
3078 pending_write_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003079 }
John Zulauf89311b42020-09-29 16:28:47 -06003080 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3081 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003082
John Zulauf89311b42020-09-29 16:28:47 -06003083 if (!pending_layout_transition) {
3084 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3085 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003086 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003087 // 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 -07003088 if (barrier.src_exec_scope & (read_access.stage | read_access.barriers)) {
3089 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003090 }
3091 }
John Zulaufa0a98292020-09-18 09:30:10 -06003092 }
John Zulaufa0a98292020-09-18 09:30:10 -06003093}
3094
John Zulauf4a6105a2020-11-17 15:11:05 -07003095// Apply the tag scoped memory barrier without updating the existing barriers. The execution barrier
3096// changes the "chaining" state, but to keep barriers independent. See discussion above.
3097void ResourceAccessState::ApplyBarrier(const ResourceUsageTag &scope_tag, const SyncBarrier &barrier, bool layout_transition) {
3098 // The scope logic for events is, if we're here, the resource usage was flagged as "in the first execution scope" at
3099 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3100 // in order to know if it's in the excecution scope
3101 // Notice that the layout transition sets the pending barriers *regardless*, as any lack of src_access_scope to
3102 // guard against the layout transition should be reported in the detect barrier hazard phase, and we only report
3103 // errors w.r.t. "most recent" accesses.
3104 if (layout_transition || ((write_tag.IsBefore(scope_tag)) && (barrier.src_access_scope & last_write).any())) {
3105 pending_write_barriers |= barrier.dst_access_scope;
3106 pending_write_dep_chain |= barrier.dst_exec_scope;
3107 }
3108 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3109 pending_layout_transition |= layout_transition;
3110
3111 if (!pending_layout_transition) {
3112 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3113 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003114 for (auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003115 // If this read is the same one we included in the set event and in scope, then apply the execution barrier...
3116 // NOTE: That's not really correct... this read stage might *not* have been included in the setevent, and the barriers
3117 // representing the chain might have changed since then (that would be an odd usage), so as a first approximation
3118 // we'll assume the barriers *haven't* been changed since (if the tag hasn't), and while this could be a false
3119 // positive in the case of Set; SomeBarrier; Wait; we'll live with it until we can add more state to the first scope
3120 // capture (the specific write and read stages that *were* in scope at the moment of SetEvents.
3121 // TODO: eliminate the false positive by including write/read-stages "in scope" information in SetEvents first_scope
John Zulaufab7756b2020-12-29 16:10:16 -07003122 if (read_access.tag.IsBefore(scope_tag) && (barrier.src_exec_scope & (read_access.stage | read_access.barriers))) {
3123 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07003124 }
3125 }
3126 }
3127}
John Zulauf89311b42020-09-29 16:28:47 -06003128void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag &tag) {
3129 if (pending_layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003130 // SetWrite clobbers the read count, and thus we don't have to clear the read_state out.
3131 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003132 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf89311b42020-09-29 16:28:47 -06003133 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003134 }
John Zulauf89311b42020-09-29 16:28:47 -06003135
3136 // Apply the accumulate execution barriers (and thus update chaining information)
3137 // for layout transition, read count is zeroed by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003138 for (auto &read_access : last_reads) {
3139 read_access.barriers |= read_access.pending_dep_chain;
3140 read_execution_barriers |= read_access.barriers;
3141 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003142 }
3143
3144 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3145 write_dependency_chain |= pending_write_dep_chain;
3146 write_barriers |= pending_write_barriers;
3147 pending_write_dep_chain = 0;
3148 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003149}
3150
John Zulauf59e25072020-07-17 10:55:21 -06003151// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003152VkPipelineStageFlags ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
John Zulauf59e25072020-07-17 10:55:21 -06003153 VkPipelineStageFlags barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003154
John Zulaufab7756b2020-12-29 16:10:16 -07003155 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003156 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003157 barriers = read_access.barriers;
3158 break;
John Zulauf59e25072020-07-17 10:55:21 -06003159 }
3160 }
John Zulauf4285ee92020-09-23 10:20:52 -06003161
John Zulauf59e25072020-07-17 10:55:21 -06003162 return barriers;
3163}
3164
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003165inline bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlagBits usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003166 assert(IsRead(usage));
3167 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3168 // * the previous reads are not hazards, and thus last_write must be visible and available to
3169 // any reads that happen after.
3170 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3171 // 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 -07003172 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003173}
3174
John Zulauf8e3c3e92021-01-06 11:19:36 -07003175VkPipelineStageFlags ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003176 // Whether the stage are in the ordering scope only matters if the current write is ordered
3177 VkPipelineStageFlags ordered_stages = last_read_stages & ordering.exec_scope;
3178 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003179 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003180 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003181 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
3182 ordered_stages |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
3183 }
3184
3185 return ordered_stages;
3186}
3187
John Zulauffaea0ee2021-01-14 14:01:32 -07003188void ResourceAccessState::UpdateFirst(const ResourceUsageTag &tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
3189 // Only record until we record a write.
3190 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003191 const VkPipelineStageFlags usage_stage =
3192 IsRead(usage_index) ? static_cast<VkPipelineStageFlags>(PipelineStageBit(usage_index)) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003193 if (0 == (usage_stage & first_read_stages_)) {
3194 // If this is a read we haven't seen or a write, record.
3195 first_read_stages_ |= usage_stage;
3196 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3197 }
3198 }
3199}
3200
John Zulaufd1f85d42020-04-15 12:23:15 -06003201void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003202 auto *access_context = GetAccessContextNoInsert(command_buffer);
3203 if (access_context) {
3204 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003205 }
3206}
3207
John Zulaufd1f85d42020-04-15 12:23:15 -06003208void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3209 auto access_found = cb_access_state.find(command_buffer);
3210 if (access_found != cb_access_state.end()) {
3211 access_found->second->Reset();
3212 cb_access_state.erase(access_found);
3213 }
3214}
3215
John Zulauf9cb530d2019-09-30 14:14:10 -06003216bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3217 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3218 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003219 const auto *cb_context = GetAccessContext(commandBuffer);
3220 assert(cb_context);
3221 if (!cb_context) return skip;
3222 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003223
John Zulauf3d84f1b2020-03-09 13:33:25 -06003224 // If we have no previous accesses, we have no hazards
John Zulauf3d84f1b2020-03-09 13:33:25 -06003225 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003226 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003227
3228 for (uint32_t region = 0; region < regionCount; region++) {
3229 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003230 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003231 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003232 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003233 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003234 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003235 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003236 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003237 cb_context->FormatUsage(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003238 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003239 }
John Zulauf16adfc92020-04-08 10:28:33 -06003240 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003241 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf355e49b2020-04-24 15:11:15 -06003242 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003243 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003244 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003245 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003246 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003247 cb_context->FormatUsage(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003248 }
3249 }
3250 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003251 }
3252 return skip;
3253}
3254
3255void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3256 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003257 auto *cb_context = GetAccessContext(commandBuffer);
3258 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003259 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003260 auto *context = cb_context->GetCurrentAccessContext();
3261
John Zulauf9cb530d2019-09-30 14:14:10 -06003262 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003263 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003264
3265 for (uint32_t region = 0; region < regionCount; region++) {
3266 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003267 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003268 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003269 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003270 }
John Zulauf16adfc92020-04-08 10:28:33 -06003271 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003272 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003273 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003274 }
3275 }
3276}
3277
John Zulauf4a6105a2020-11-17 15:11:05 -07003278void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3279 // Clear out events from the command buffer contexts
3280 for (auto &cb_context : cb_access_state) {
3281 cb_context.second->RecordDestroyEvent(event);
3282 }
3283}
3284
Jeff Leger178b1e52020-10-05 12:22:23 -04003285bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3286 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3287 bool skip = false;
3288 const auto *cb_context = GetAccessContext(commandBuffer);
3289 assert(cb_context);
3290 if (!cb_context) return skip;
3291 const auto *context = cb_context->GetCurrentAccessContext();
3292
3293 // If we have no previous accesses, we have no hazards
3294 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3295 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3296
3297 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3298 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3299 if (src_buffer) {
3300 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
3301 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3302 if (hazard.hazard) {
3303 // TODO -- add tag information to log msg when useful.
3304 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
3305 "vkCmdCopyBuffer2KHR(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
3306 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003307 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003308 }
3309 }
3310 if (dst_buffer && !skip) {
3311 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
3312 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3313 if (hazard.hazard) {
3314 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
3315 "vkCmdCopyBuffer2KHR(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
3316 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003317 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003318 }
3319 }
3320 if (skip) break;
3321 }
3322 return skip;
3323}
3324
3325void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3326 auto *cb_context = GetAccessContext(commandBuffer);
3327 assert(cb_context);
3328 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER2KHR);
3329 auto *context = cb_context->GetCurrentAccessContext();
3330
3331 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3332 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3333
3334 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3335 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3336 if (src_buffer) {
3337 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003338 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003339 }
3340 if (dst_buffer) {
3341 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003342 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003343 }
3344 }
3345}
3346
John Zulauf5c5e88d2019-12-26 11:22:02 -07003347bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3348 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3349 const VkImageCopy *pRegions) const {
3350 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003351 const auto *cb_access_context = GetAccessContext(commandBuffer);
3352 assert(cb_access_context);
3353 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003354
John Zulauf3d84f1b2020-03-09 13:33:25 -06003355 const auto *context = cb_access_context->GetCurrentAccessContext();
3356 assert(context);
3357 if (!context) return skip;
3358
3359 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3360 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003361 for (uint32_t region = 0; region < regionCount; region++) {
3362 const auto &copy_region = pRegions[region];
3363 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003364 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003365 copy_region.srcOffset, copy_region.extent);
3366 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003367 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003368 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003369 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003370 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003371 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003372 }
3373
3374 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003375 VkExtent3D dst_copy_extent =
3376 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf540266b2020-04-06 18:54:53 -06003377 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
locke-lunarg1df1f882020-03-02 16:42:08 -07003378 copy_region.dstOffset, dst_copy_extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003379 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003380 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003381 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003382 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003383 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003384 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07003385 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003386 }
3387 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003388
John Zulauf5c5e88d2019-12-26 11:22:02 -07003389 return skip;
3390}
3391
3392void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3393 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3394 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003395 auto *cb_access_context = GetAccessContext(commandBuffer);
3396 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003397 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003398 auto *context = cb_access_context->GetCurrentAccessContext();
3399 assert(context);
3400
John Zulauf5c5e88d2019-12-26 11:22:02 -07003401 auto *src_image = Get<IMAGE_STATE>(srcImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003402 auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003403
3404 for (uint32_t region = 0; region < regionCount; region++) {
3405 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06003406 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003407 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3408 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003409 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003410 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003411 VkExtent3D dst_copy_extent =
3412 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003413 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3414 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003415 }
3416 }
3417}
3418
Jeff Leger178b1e52020-10-05 12:22:23 -04003419bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
3420 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
3421 bool skip = false;
3422 const auto *cb_access_context = GetAccessContext(commandBuffer);
3423 assert(cb_access_context);
3424 if (!cb_access_context) return skip;
3425
3426 const auto *context = cb_access_context->GetCurrentAccessContext();
3427 assert(context);
3428 if (!context) return skip;
3429
3430 const auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3431 const auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3432 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3433 const auto &copy_region = pCopyImageInfo->pRegions[region];
3434 if (src_image) {
3435 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
3436 copy_region.srcOffset, copy_region.extent);
3437 if (hazard.hazard) {
3438 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
3439 "vkCmdCopyImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
3440 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003441 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003442 }
3443 }
3444
3445 if (dst_image) {
3446 VkExtent3D dst_copy_extent =
3447 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
3448 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
3449 copy_region.dstOffset, dst_copy_extent);
3450 if (hazard.hazard) {
3451 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
3452 "vkCmdCopyImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
3453 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003454 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003455 }
3456 if (skip) break;
3457 }
3458 }
3459
3460 return skip;
3461}
3462
3463void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
3464 auto *cb_access_context = GetAccessContext(commandBuffer);
3465 assert(cb_access_context);
3466 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE2KHR);
3467 auto *context = cb_access_context->GetCurrentAccessContext();
3468 assert(context);
3469
3470 auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3471 auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3472
3473 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3474 const auto &copy_region = pCopyImageInfo->pRegions[region];
3475 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003476 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3477 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003478 }
3479 if (dst_image) {
3480 VkExtent3D dst_copy_extent =
3481 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003482 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3483 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003484 }
3485 }
3486}
3487
John Zulauf9cb530d2019-09-30 14:14:10 -06003488bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3489 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3490 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3491 uint32_t bufferMemoryBarrierCount,
3492 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3493 uint32_t imageMemoryBarrierCount,
3494 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
3495 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003496 const auto *cb_access_context = GetAccessContext(commandBuffer);
3497 assert(cb_access_context);
3498 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07003499
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003500 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3501 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3502 imageMemoryBarrierCount, pImageMemoryBarriers);
3503 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06003504 return skip;
3505}
3506
3507void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3508 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3509 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3510 uint32_t bufferMemoryBarrierCount,
3511 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3512 uint32_t imageMemoryBarrierCount,
3513 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003514 auto *cb_access_context = GetAccessContext(commandBuffer);
3515 assert(cb_access_context);
3516 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06003517
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003518 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3519 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3520 imageMemoryBarrierCount, pImageMemoryBarriers);
3521 pipeline_barrier.Record(cb_access_context, cb_access_context->NextCommandTag(CMD_PIPELINEBARRIER));
John Zulauf9cb530d2019-09-30 14:14:10 -06003522}
3523
3524void SyncValidator::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
3525 const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
3526 // The state tracker sets up the device state
3527 StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result);
3528
John Zulauf5f13a792020-03-10 07:31:21 -06003529 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
3530 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06003531 // TODO: Find a good way to do this hooklessly.
3532 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
3533 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeSyncValidation);
3534 SyncValidator *sync_device_state = static_cast<SyncValidator *>(validation_data);
3535
John Zulaufd1f85d42020-04-15 12:23:15 -06003536 sync_device_state->SetCommandBufferResetCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3537 sync_device_state->ResetCommandBufferCallback(command_buffer);
3538 });
3539 sync_device_state->SetCommandBufferFreeCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3540 sync_device_state->FreeCommandBufferCallback(command_buffer);
3541 });
John Zulauf9cb530d2019-09-30 14:14:10 -06003542}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003543
John Zulauf355e49b2020-04-24 15:11:15 -06003544bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003545 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003546 bool skip = false;
3547 const auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
3548 auto cb_context = GetAccessContext(commandBuffer);
3549
3550 if (rp_state && cb_context) {
3551 skip |= cb_context->ValidateBeginRenderPass(*rp_state, pRenderPassBegin, pSubpassBeginInfo, func_name);
3552 }
3553
3554 return skip;
3555}
3556
3557bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3558 VkSubpassContents contents) const {
3559 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003560 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003561 subpass_begin_info.contents = contents;
3562 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, "vkCmdBeginRenderPass");
3563 return skip;
3564}
3565
3566bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003567 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003568 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3569 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2");
3570 return skip;
3571}
3572
3573bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3574 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003575 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003576 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3577 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2KHR");
3578 return skip;
3579}
3580
John Zulauf3d84f1b2020-03-09 13:33:25 -06003581void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
3582 VkResult result) {
3583 // The state tracker sets up the command buffer state
3584 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
3585
3586 // Create/initialize the structure that trackers accesses at the command buffer scope.
3587 auto cb_access_context = GetAccessContext(commandBuffer);
3588 assert(cb_access_context);
3589 cb_access_context->Reset();
3590}
3591
3592void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
John Zulauf355e49b2020-04-24 15:11:15 -06003593 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003594 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06003595 if (cb_context) {
3596 cb_context->RecordBeginRenderPass(cb_context->NextCommandTag(command));
John Zulauf3d84f1b2020-03-09 13:33:25 -06003597 }
3598}
3599
3600void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3601 VkSubpassContents contents) {
3602 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003603 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003604 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003605 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003606}
3607
3608void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3609 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3610 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003611 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003612}
3613
3614void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3615 const VkRenderPassBeginInfo *pRenderPassBegin,
3616 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3617 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003618 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
3619}
3620
Mike Schuchardt2df08912020-12-15 16:28:09 -08003621bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3622 const VkSubpassEndInfo *pSubpassEndInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003623 bool skip = false;
3624
3625 auto cb_context = GetAccessContext(commandBuffer);
3626 assert(cb_context);
3627 auto cb_state = cb_context->GetCommandBufferState();
3628 if (!cb_state) return skip;
3629
3630 auto rp_state = cb_state->activeRenderPass;
3631 if (!rp_state) return skip;
3632
3633 skip |= cb_context->ValidateNextSubpass(func_name);
3634
3635 return skip;
3636}
3637
3638bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
3639 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003640 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003641 subpass_begin_info.contents = contents;
3642 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, "vkCmdNextSubpass");
3643 return skip;
3644}
3645
Mike Schuchardt2df08912020-12-15 16:28:09 -08003646bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3647 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003648 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3649 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2KHR");
3650 return skip;
3651}
3652
3653bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3654 const VkSubpassEndInfo *pSubpassEndInfo) const {
3655 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3656 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2");
3657 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003658}
3659
3660void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003661 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003662 auto cb_context = GetAccessContext(commandBuffer);
3663 assert(cb_context);
3664 auto cb_state = cb_context->GetCommandBufferState();
3665 if (!cb_state) return;
3666
3667 auto rp_state = cb_state->activeRenderPass;
3668 if (!rp_state) return;
3669
John Zulauffaea0ee2021-01-14 14:01:32 -07003670 cb_context->RecordNextSubpass(*rp_state, command);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003671}
3672
3673void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
3674 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003675 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003676 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003677 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003678}
3679
3680void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3681 const VkSubpassEndInfo *pSubpassEndInfo) {
3682 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003683 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003684}
3685
3686void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3687 const VkSubpassEndInfo *pSubpassEndInfo) {
3688 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003689 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003690}
3691
Mike Schuchardt2df08912020-12-15 16:28:09 -08003692bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003693 const char *func_name) const {
3694 bool skip = false;
3695
3696 auto cb_context = GetAccessContext(commandBuffer);
3697 assert(cb_context);
3698 auto cb_state = cb_context->GetCommandBufferState();
3699 if (!cb_state) return skip;
3700
3701 auto rp_state = cb_state->activeRenderPass;
3702 if (!rp_state) return skip;
3703
3704 skip |= cb_context->ValidateEndRenderpass(func_name);
3705 return skip;
3706}
3707
3708bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3709 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
3710 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, "vkEndRenderPass");
3711 return skip;
3712}
3713
Mike Schuchardt2df08912020-12-15 16:28:09 -08003714bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003715 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3716 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2");
3717 return skip;
3718}
3719
3720bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003721 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003722 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3723 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2KHR");
3724 return skip;
3725}
3726
3727void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
3728 CMD_TYPE command) {
John Zulaufe5da6e52020-03-18 15:32:18 -06003729 // Resolve the all subpass contexts to the command buffer contexts
3730 auto cb_context = GetAccessContext(commandBuffer);
3731 assert(cb_context);
3732 auto cb_state = cb_context->GetCommandBufferState();
3733 if (!cb_state) return;
3734
locke-lunargaecf2152020-05-12 17:15:41 -06003735 const auto *rp_state = cb_state->activeRenderPass.get();
John Zulaufe5da6e52020-03-18 15:32:18 -06003736 if (!rp_state) return;
3737
John Zulauffaea0ee2021-01-14 14:01:32 -07003738 cb_context->RecordEndRenderPass(*rp_state, command);
John Zulaufe5da6e52020-03-18 15:32:18 -06003739}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003740
John Zulauf33fc1d52020-07-17 11:01:10 -06003741// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
3742// updates to a resource which do not conflict at the byte level.
3743// TODO: Revisit this rule to see if it needs to be tighter or looser
3744// TODO: Add programatic control over suppression heuristics
3745bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
3746 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
3747}
3748
John Zulauf3d84f1b2020-03-09 13:33:25 -06003749void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06003750 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06003751 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003752}
3753
3754void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003755 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003756 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003757}
3758
3759void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003760 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003761 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003762}
locke-lunarga19c71d2020-03-02 18:17:04 -07003763
Jeff Leger178b1e52020-10-05 12:22:23 -04003764template <typename BufferImageCopyRegionType>
3765bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3766 VkImageLayout dstImageLayout, uint32_t regionCount,
3767 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003768 bool skip = false;
3769 const auto *cb_access_context = GetAccessContext(commandBuffer);
3770 assert(cb_access_context);
3771 if (!cb_access_context) return skip;
3772
Jeff Leger178b1e52020-10-05 12:22:23 -04003773 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3774 const char *func_name = is_2khr ? "vkCmdCopyBufferToImage2KHR()" : "vkCmdCopyBufferToImage()";
3775
locke-lunarga19c71d2020-03-02 18:17:04 -07003776 const auto *context = cb_access_context->GetCurrentAccessContext();
3777 assert(context);
3778 if (!context) return skip;
3779
3780 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
locke-lunarga19c71d2020-03-02 18:17:04 -07003781 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
3782
3783 for (uint32_t region = 0; region < regionCount; region++) {
3784 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07003785 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07003786 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003787 if (src_buffer) {
3788 ResourceAccessRange src_range =
3789 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3790 hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3791 if (hazard.hazard) {
3792 // PHASE1 TODO -- add tag information to log msg when useful.
3793 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
3794 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3795 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003796 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003797 }
3798 }
3799
3800 hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource,
3801 copy_region.imageOffset, copy_region.imageExtent);
locke-lunarga19c71d2020-03-02 18:17:04 -07003802 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003803 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003804 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003805 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003806 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003807 }
3808 if (skip) break;
3809 }
3810 if (skip) break;
3811 }
3812 return skip;
3813}
3814
Jeff Leger178b1e52020-10-05 12:22:23 -04003815bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3816 VkImageLayout dstImageLayout, uint32_t regionCount,
3817 const VkBufferImageCopy *pRegions) const {
3818 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
3819 COPY_COMMAND_VERSION_1);
3820}
3821
3822bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3823 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
3824 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3825 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3826 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3827}
3828
3829template <typename BufferImageCopyRegionType>
3830void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3831 VkImageLayout dstImageLayout, uint32_t regionCount,
3832 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003833 auto *cb_access_context = GetAccessContext(commandBuffer);
3834 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003835
3836 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3837 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYBUFFERTOIMAGE2KHR : CMD_COPYBUFFERTOIMAGE;
3838
3839 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003840 auto *context = cb_access_context->GetCurrentAccessContext();
3841 assert(context);
3842
3843 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf16adfc92020-04-08 10:28:33 -06003844 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003845
3846 for (uint32_t region = 0; region < regionCount; region++) {
3847 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07003848 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003849 if (src_buffer) {
3850 ResourceAccessRange src_range =
3851 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3852 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
3853 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07003854 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3855 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07003856 }
3857 }
3858}
3859
Jeff Leger178b1e52020-10-05 12:22:23 -04003860void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3861 VkImageLayout dstImageLayout, uint32_t regionCount,
3862 const VkBufferImageCopy *pRegions) {
3863 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
3864 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1);
3865}
3866
3867void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3868 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
3869 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
3870 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3871 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3872 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3873}
3874
3875template <typename BufferImageCopyRegionType>
3876bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3877 VkBuffer dstBuffer, uint32_t regionCount,
3878 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003879 bool skip = false;
3880 const auto *cb_access_context = GetAccessContext(commandBuffer);
3881 assert(cb_access_context);
3882 if (!cb_access_context) return skip;
3883
Jeff Leger178b1e52020-10-05 12:22:23 -04003884 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3885 const char *func_name = is_2khr ? "vkCmdCopyImageToBuffer2KHR()" : "vkCmdCopyImageToBuffer()";
3886
locke-lunarga19c71d2020-03-02 18:17:04 -07003887 const auto *context = cb_access_context->GetCurrentAccessContext();
3888 assert(context);
3889 if (!context) return skip;
3890
3891 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3892 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3893 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
3894 for (uint32_t region = 0; region < regionCount; region++) {
3895 const auto &copy_region = pRegions[region];
3896 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003897 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07003898 copy_region.imageOffset, copy_region.imageExtent);
3899 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003900 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003901 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003902 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003903 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003904 }
John Zulauf477700e2021-01-06 11:41:49 -07003905 if (dst_mem) {
3906 ResourceAccessRange dst_range =
3907 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
3908 hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3909 if (hazard.hazard) {
3910 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
3911 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3912 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003913 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003914 }
locke-lunarga19c71d2020-03-02 18:17:04 -07003915 }
3916 }
3917 if (skip) break;
3918 }
3919 return skip;
3920}
3921
Jeff Leger178b1e52020-10-05 12:22:23 -04003922bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
3923 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
3924 const VkBufferImageCopy *pRegions) const {
3925 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
3926 COPY_COMMAND_VERSION_1);
3927}
3928
3929bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
3930 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
3931 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
3932 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
3933 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
3934}
3935
3936template <typename BufferImageCopyRegionType>
3937void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3938 VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions,
3939 CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003940 auto *cb_access_context = GetAccessContext(commandBuffer);
3941 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003942
3943 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3944 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYIMAGETOBUFFER2KHR : CMD_COPYIMAGETOBUFFER;
3945
3946 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003947 auto *context = cb_access_context->GetCurrentAccessContext();
3948 assert(context);
3949
3950 const auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003951 auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3952 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 -06003953 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07003954
3955 for (uint32_t region = 0; region < regionCount; region++) {
3956 const auto &copy_region = pRegions[region];
3957 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003958 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3959 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07003960 if (dst_buffer) {
3961 ResourceAccessRange dst_range =
3962 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
3963 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
3964 }
locke-lunarga19c71d2020-03-02 18:17:04 -07003965 }
3966 }
3967}
3968
Jeff Leger178b1e52020-10-05 12:22:23 -04003969void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3970 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
3971 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
3972 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1);
3973}
3974
3975void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
3976 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
3977 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
3978 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
3979 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
3980 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
3981}
3982
3983template <typename RegionType>
3984bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3985 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3986 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003987 bool skip = false;
3988 const auto *cb_access_context = GetAccessContext(commandBuffer);
3989 assert(cb_access_context);
3990 if (!cb_access_context) return skip;
3991
3992 const auto *context = cb_access_context->GetCurrentAccessContext();
3993 assert(context);
3994 if (!context) return skip;
3995
3996 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3997 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
3998
3999 for (uint32_t region = 0; region < regionCount; region++) {
4000 const auto &blit_region = pRegions[region];
4001 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004002 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4003 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4004 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4005 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4006 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4007 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
4008 auto hazard =
4009 context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004010 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004011 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004012 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004013 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004014 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004015 }
4016 }
4017
4018 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004019 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4020 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4021 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4022 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4023 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4024 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
4025 auto hazard =
4026 context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004027 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004028 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004029 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004030 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004031 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004032 }
4033 if (skip) break;
4034 }
4035 }
4036
4037 return skip;
4038}
4039
Jeff Leger178b1e52020-10-05 12:22:23 -04004040bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4041 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4042 const VkImageBlit *pRegions, VkFilter filter) const {
4043 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4044 "vkCmdBlitImage");
4045}
4046
4047bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4048 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4049 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4050 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4051 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4052}
4053
4054template <typename RegionType>
4055void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4056 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4057 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004058 auto *cb_access_context = GetAccessContext(commandBuffer);
4059 assert(cb_access_context);
4060 auto *context = cb_access_context->GetCurrentAccessContext();
4061 assert(context);
4062
4063 auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004064 auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004065
4066 for (uint32_t region = 0; region < regionCount; region++) {
4067 const auto &blit_region = pRegions[region];
4068 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004069 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4070 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4071 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4072 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4073 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4074 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004075 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4076 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004077 }
4078 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004079 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4080 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4081 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4082 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4083 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4084 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004085 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4086 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004087 }
4088 }
4089}
locke-lunarg36ba2592020-04-03 09:42:04 -06004090
Jeff Leger178b1e52020-10-05 12:22:23 -04004091void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4092 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4093 const VkImageBlit *pRegions, VkFilter filter) {
4094 auto *cb_access_context = GetAccessContext(commandBuffer);
4095 assert(cb_access_context);
4096 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4097 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4098 pRegions, filter);
4099 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4100}
4101
4102void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4103 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4104 auto *cb_access_context = GetAccessContext(commandBuffer);
4105 assert(cb_access_context);
4106 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4107 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4108 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4109 pBlitImageInfo->filter, tag);
4110}
4111
John Zulauffaea0ee2021-01-14 14:01:32 -07004112bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4113 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4114 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4115 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004116 bool skip = false;
4117 if (drawCount == 0) return skip;
4118
4119 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4120 VkDeviceSize size = struct_size;
4121 if (drawCount == 1 || stride == size) {
4122 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004123 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004124 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4125 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004126 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004127 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004128 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004129 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004130 }
4131 } else {
4132 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004133 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004134 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4135 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004136 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004137 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4138 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004139 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004140 break;
4141 }
4142 }
4143 }
4144 return skip;
4145}
4146
locke-lunarg61870c22020-06-09 14:51:50 -06004147void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag &tag, const VkDeviceSize struct_size,
4148 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4149 uint32_t stride) {
locke-lunargff255f92020-05-13 18:53:52 -06004150 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4151 VkDeviceSize size = struct_size;
4152 if (drawCount == 1 || stride == size) {
4153 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004154 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004155 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004156 } else {
4157 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004158 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004159 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4160 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004161 }
4162 }
4163}
4164
John Zulauffaea0ee2021-01-14 14:01:32 -07004165bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4166 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4167 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004168 bool skip = false;
4169
4170 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004171 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004172 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4173 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004174 skip |= LogError(count_buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004175 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004176 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004177 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004178 }
4179 return skip;
4180}
4181
locke-lunarg61870c22020-06-09 14:51:50 -06004182void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag &tag, VkBuffer buffer, VkDeviceSize offset) {
locke-lunargff255f92020-05-13 18:53:52 -06004183 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004184 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004185 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004186}
4187
locke-lunarg36ba2592020-04-03 09:42:04 -06004188bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004189 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004190 const auto *cb_access_context = GetAccessContext(commandBuffer);
4191 assert(cb_access_context);
4192 if (!cb_access_context) return skip;
4193
locke-lunarg61870c22020-06-09 14:51:50 -06004194 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004195 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004196}
4197
4198void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004199 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004200 auto *cb_access_context = GetAccessContext(commandBuffer);
4201 assert(cb_access_context);
4202 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004203
locke-lunarg61870c22020-06-09 14:51:50 -06004204 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004205}
locke-lunarge1a67022020-04-29 00:15:36 -06004206
4207bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004208 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004209 const auto *cb_access_context = GetAccessContext(commandBuffer);
4210 assert(cb_access_context);
4211 if (!cb_access_context) return skip;
4212
4213 const auto *context = cb_access_context->GetCurrentAccessContext();
4214 assert(context);
4215 if (!context) return skip;
4216
locke-lunarg61870c22020-06-09 14:51:50 -06004217 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004218 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4219 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004220 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004221}
4222
4223void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004224 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004225 auto *cb_access_context = GetAccessContext(commandBuffer);
4226 assert(cb_access_context);
4227 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4228 auto *context = cb_access_context->GetCurrentAccessContext();
4229 assert(context);
4230
locke-lunarg61870c22020-06-09 14:51:50 -06004231 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4232 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004233}
4234
4235bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4236 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004237 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004238 const auto *cb_access_context = GetAccessContext(commandBuffer);
4239 assert(cb_access_context);
4240 if (!cb_access_context) return skip;
4241
locke-lunarg61870c22020-06-09 14:51:50 -06004242 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4243 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4244 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004245 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004246}
4247
4248void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4249 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004250 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004251 auto *cb_access_context = GetAccessContext(commandBuffer);
4252 assert(cb_access_context);
4253 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004254
locke-lunarg61870c22020-06-09 14:51:50 -06004255 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4256 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4257 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004258}
4259
4260bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4261 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004262 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004263 const auto *cb_access_context = GetAccessContext(commandBuffer);
4264 assert(cb_access_context);
4265 if (!cb_access_context) return skip;
4266
locke-lunarg61870c22020-06-09 14:51:50 -06004267 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4268 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4269 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004270 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004271}
4272
4273void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4274 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004275 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004276 auto *cb_access_context = GetAccessContext(commandBuffer);
4277 assert(cb_access_context);
4278 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004279
locke-lunarg61870c22020-06-09 14:51:50 -06004280 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4281 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4282 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004283}
4284
4285bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4286 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004287 bool skip = false;
4288 if (drawCount == 0) return skip;
4289
locke-lunargff255f92020-05-13 18:53:52 -06004290 const auto *cb_access_context = GetAccessContext(commandBuffer);
4291 assert(cb_access_context);
4292 if (!cb_access_context) return skip;
4293
4294 const auto *context = cb_access_context->GetCurrentAccessContext();
4295 assert(context);
4296 if (!context) return skip;
4297
locke-lunarg61870c22020-06-09 14:51:50 -06004298 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4299 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004300 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4301 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004302
4303 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4304 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4305 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004306 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004307 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004308}
4309
4310void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4311 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004312 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004313 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06004314 auto *cb_access_context = GetAccessContext(commandBuffer);
4315 assert(cb_access_context);
4316 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
4317 auto *context = cb_access_context->GetCurrentAccessContext();
4318 assert(context);
4319
locke-lunarg61870c22020-06-09 14:51:50 -06004320 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4321 cb_access_context->RecordDrawSubpassAttachment(tag);
4322 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004323
4324 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4325 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4326 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004327 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004328}
4329
4330bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4331 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004332 bool skip = false;
4333 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06004334 const auto *cb_access_context = GetAccessContext(commandBuffer);
4335 assert(cb_access_context);
4336 if (!cb_access_context) return skip;
4337
4338 const auto *context = cb_access_context->GetCurrentAccessContext();
4339 assert(context);
4340 if (!context) return skip;
4341
locke-lunarg61870c22020-06-09 14:51:50 -06004342 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
4343 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004344 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4345 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004346
4347 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4348 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4349 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004350 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004351 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004352}
4353
4354void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4355 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004356 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004357 auto *cb_access_context = GetAccessContext(commandBuffer);
4358 assert(cb_access_context);
4359 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
4360 auto *context = cb_access_context->GetCurrentAccessContext();
4361 assert(context);
4362
locke-lunarg61870c22020-06-09 14:51:50 -06004363 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4364 cb_access_context->RecordDrawSubpassAttachment(tag);
4365 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004366
4367 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4368 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4369 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004370 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004371}
4372
4373bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4374 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4375 uint32_t stride, const char *function) const {
4376 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004377 const auto *cb_access_context = GetAccessContext(commandBuffer);
4378 assert(cb_access_context);
4379 if (!cb_access_context) return skip;
4380
4381 const auto *context = cb_access_context->GetCurrentAccessContext();
4382 assert(context);
4383 if (!context) return skip;
4384
locke-lunarg61870c22020-06-09 14:51:50 -06004385 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4386 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004387 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4388 maxDrawCount, stride, function);
4389 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004390
4391 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4392 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4393 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004394 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004395 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004396}
4397
4398bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4399 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4400 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004401 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4402 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004403}
4404
4405void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4406 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4407 uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004408 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4409 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004410 auto *cb_access_context = GetAccessContext(commandBuffer);
4411 assert(cb_access_context);
4412 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECTCOUNT);
4413 auto *context = cb_access_context->GetCurrentAccessContext();
4414 assert(context);
4415
locke-lunarg61870c22020-06-09 14:51:50 -06004416 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4417 cb_access_context->RecordDrawSubpassAttachment(tag);
4418 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
4419 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004420
4421 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4422 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4423 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004424 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004425}
4426
4427bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4428 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4429 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004430 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4431 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004432}
4433
4434void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4435 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4436 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004437 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4438 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004439 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004440}
4441
4442bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4443 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4444 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004445 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4446 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004447}
4448
4449void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4450 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4451 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004452 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4453 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004454 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4455}
4456
4457bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4458 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4459 uint32_t stride, const char *function) const {
4460 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004461 const auto *cb_access_context = GetAccessContext(commandBuffer);
4462 assert(cb_access_context);
4463 if (!cb_access_context) return skip;
4464
4465 const auto *context = cb_access_context->GetCurrentAccessContext();
4466 assert(context);
4467 if (!context) return skip;
4468
locke-lunarg61870c22020-06-09 14:51:50 -06004469 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4470 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004471 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4472 offset, maxDrawCount, stride, function);
4473 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004474
4475 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4476 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4477 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004478 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004479 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004480}
4481
4482bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4483 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4484 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004485 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4486 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004487}
4488
4489void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4490 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4491 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004492 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4493 maxDrawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004494 auto *cb_access_context = GetAccessContext(commandBuffer);
4495 assert(cb_access_context);
4496 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECTCOUNT);
4497 auto *context = cb_access_context->GetCurrentAccessContext();
4498 assert(context);
4499
locke-lunarg61870c22020-06-09 14:51:50 -06004500 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4501 cb_access_context->RecordDrawSubpassAttachment(tag);
4502 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
4503 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004504
4505 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4506 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06004507 // We will update the index and vertex buffer in SubmitQueue in the future.
4508 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004509}
4510
4511bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
4512 VkDeviceSize offset, VkBuffer countBuffer,
4513 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4514 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004515 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4516 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004517}
4518
4519void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4520 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4521 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004522 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4523 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004524 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4525}
4526
4527bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
4528 VkDeviceSize offset, VkBuffer countBuffer,
4529 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4530 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004531 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4532 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004533}
4534
4535void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4536 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4537 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004538 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4539 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004540 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4541}
4542
4543bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4544 const VkClearColorValue *pColor, uint32_t rangeCount,
4545 const VkImageSubresourceRange *pRanges) const {
4546 bool skip = false;
4547 const auto *cb_access_context = GetAccessContext(commandBuffer);
4548 assert(cb_access_context);
4549 if (!cb_access_context) return skip;
4550
4551 const auto *context = cb_access_context->GetCurrentAccessContext();
4552 assert(context);
4553 if (!context) return skip;
4554
4555 const auto *image_state = Get<IMAGE_STATE>(image);
4556
4557 for (uint32_t index = 0; index < rangeCount; index++) {
4558 const auto &range = pRanges[index];
4559 if (image_state) {
4560 auto hazard =
4561 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4562 if (hazard.hazard) {
4563 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004564 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004565 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004566 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004567 }
4568 }
4569 }
4570 return skip;
4571}
4572
4573void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4574 const VkClearColorValue *pColor, uint32_t rangeCount,
4575 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004576 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004577 auto *cb_access_context = GetAccessContext(commandBuffer);
4578 assert(cb_access_context);
4579 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
4580 auto *context = cb_access_context->GetCurrentAccessContext();
4581 assert(context);
4582
4583 const auto *image_state = Get<IMAGE_STATE>(image);
4584
4585 for (uint32_t index = 0; index < rangeCount; index++) {
4586 const auto &range = pRanges[index];
4587 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004588 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4589 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004590 }
4591 }
4592}
4593
4594bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4595 VkImageLayout imageLayout,
4596 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4597 const VkImageSubresourceRange *pRanges) const {
4598 bool skip = false;
4599 const auto *cb_access_context = GetAccessContext(commandBuffer);
4600 assert(cb_access_context);
4601 if (!cb_access_context) return skip;
4602
4603 const auto *context = cb_access_context->GetCurrentAccessContext();
4604 assert(context);
4605 if (!context) return skip;
4606
4607 const auto *image_state = Get<IMAGE_STATE>(image);
4608
4609 for (uint32_t index = 0; index < rangeCount; index++) {
4610 const auto &range = pRanges[index];
4611 if (image_state) {
4612 auto hazard =
4613 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4614 if (hazard.hazard) {
4615 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004616 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004617 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004618 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004619 }
4620 }
4621 }
4622 return skip;
4623}
4624
4625void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4626 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4627 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004628 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004629 auto *cb_access_context = GetAccessContext(commandBuffer);
4630 assert(cb_access_context);
4631 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
4632 auto *context = cb_access_context->GetCurrentAccessContext();
4633 assert(context);
4634
4635 const auto *image_state = Get<IMAGE_STATE>(image);
4636
4637 for (uint32_t index = 0; index < rangeCount; index++) {
4638 const auto &range = pRanges[index];
4639 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004640 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4641 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004642 }
4643 }
4644}
4645
4646bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
4647 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
4648 VkDeviceSize dstOffset, VkDeviceSize stride,
4649 VkQueryResultFlags flags) const {
4650 bool skip = false;
4651 const auto *cb_access_context = GetAccessContext(commandBuffer);
4652 assert(cb_access_context);
4653 if (!cb_access_context) return skip;
4654
4655 const auto *context = cb_access_context->GetCurrentAccessContext();
4656 assert(context);
4657 if (!context) return skip;
4658
4659 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4660
4661 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004662 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
locke-lunarge1a67022020-04-29 00:15:36 -06004663 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4664 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004665 skip |=
4666 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4667 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004668 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004669 }
4670 }
locke-lunargff255f92020-05-13 18:53:52 -06004671
4672 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004673 return skip;
4674}
4675
4676void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
4677 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4678 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004679 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
4680 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06004681 auto *cb_access_context = GetAccessContext(commandBuffer);
4682 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06004683 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06004684 auto *context = cb_access_context->GetCurrentAccessContext();
4685 assert(context);
4686
4687 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4688
4689 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004690 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004691 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004692 }
locke-lunargff255f92020-05-13 18:53:52 -06004693
4694 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004695}
4696
4697bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4698 VkDeviceSize size, uint32_t data) const {
4699 bool skip = false;
4700 const auto *cb_access_context = GetAccessContext(commandBuffer);
4701 assert(cb_access_context);
4702 if (!cb_access_context) return skip;
4703
4704 const auto *context = cb_access_context->GetCurrentAccessContext();
4705 assert(context);
4706 if (!context) return skip;
4707
4708 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4709
4710 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004711 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
locke-lunarge1a67022020-04-29 00:15:36 -06004712 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4713 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004714 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004715 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004716 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004717 }
4718 }
4719 return skip;
4720}
4721
4722void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4723 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004724 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06004725 auto *cb_access_context = GetAccessContext(commandBuffer);
4726 assert(cb_access_context);
4727 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
4728 auto *context = cb_access_context->GetCurrentAccessContext();
4729 assert(context);
4730
4731 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4732
4733 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004734 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004735 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004736 }
4737}
4738
4739bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4740 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4741 const VkImageResolve *pRegions) const {
4742 bool skip = false;
4743 const auto *cb_access_context = GetAccessContext(commandBuffer);
4744 assert(cb_access_context);
4745 if (!cb_access_context) return skip;
4746
4747 const auto *context = cb_access_context->GetCurrentAccessContext();
4748 assert(context);
4749 if (!context) return skip;
4750
4751 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4752 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4753
4754 for (uint32_t region = 0; region < regionCount; region++) {
4755 const auto &resolve_region = pRegions[region];
4756 if (src_image) {
4757 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4758 resolve_region.srcOffset, resolve_region.extent);
4759 if (hazard.hazard) {
4760 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004761 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004762 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004763 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004764 }
4765 }
4766
4767 if (dst_image) {
4768 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4769 resolve_region.dstOffset, resolve_region.extent);
4770 if (hazard.hazard) {
4771 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004772 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004773 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004774 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004775 }
4776 if (skip) break;
4777 }
4778 }
4779
4780 return skip;
4781}
4782
4783void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4784 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4785 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004786 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4787 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06004788 auto *cb_access_context = GetAccessContext(commandBuffer);
4789 assert(cb_access_context);
4790 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
4791 auto *context = cb_access_context->GetCurrentAccessContext();
4792 assert(context);
4793
4794 auto *src_image = Get<IMAGE_STATE>(srcImage);
4795 auto *dst_image = Get<IMAGE_STATE>(dstImage);
4796
4797 for (uint32_t region = 0; region < regionCount; region++) {
4798 const auto &resolve_region = pRegions[region];
4799 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004800 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4801 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004802 }
4803 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004804 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4805 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004806 }
4807 }
4808}
4809
Jeff Leger178b1e52020-10-05 12:22:23 -04004810bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4811 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
4812 bool skip = false;
4813 const auto *cb_access_context = GetAccessContext(commandBuffer);
4814 assert(cb_access_context);
4815 if (!cb_access_context) return skip;
4816
4817 const auto *context = cb_access_context->GetCurrentAccessContext();
4818 assert(context);
4819 if (!context) return skip;
4820
4821 const auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4822 const auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4823
4824 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4825 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4826 if (src_image) {
4827 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4828 resolve_region.srcOffset, resolve_region.extent);
4829 if (hazard.hazard) {
4830 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
4831 "vkCmdResolveImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
4832 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004833 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004834 }
4835 }
4836
4837 if (dst_image) {
4838 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4839 resolve_region.dstOffset, resolve_region.extent);
4840 if (hazard.hazard) {
4841 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
4842 "vkCmdResolveImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
4843 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004844 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004845 }
4846 if (skip) break;
4847 }
4848 }
4849
4850 return skip;
4851}
4852
4853void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4854 const VkResolveImageInfo2KHR *pResolveImageInfo) {
4855 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
4856 auto *cb_access_context = GetAccessContext(commandBuffer);
4857 assert(cb_access_context);
4858 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE2KHR);
4859 auto *context = cb_access_context->GetCurrentAccessContext();
4860 assert(context);
4861
4862 auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4863 auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4864
4865 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4866 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4867 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004868 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4869 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004870 }
4871 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004872 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4873 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004874 }
4875 }
4876}
4877
locke-lunarge1a67022020-04-29 00:15:36 -06004878bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4879 VkDeviceSize dataSize, const void *pData) const {
4880 bool skip = false;
4881 const auto *cb_access_context = GetAccessContext(commandBuffer);
4882 assert(cb_access_context);
4883 if (!cb_access_context) return skip;
4884
4885 const auto *context = cb_access_context->GetCurrentAccessContext();
4886 assert(context);
4887 if (!context) return skip;
4888
4889 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4890
4891 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004892 // VK_WHOLE_SIZE not allowed
4893 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
locke-lunarge1a67022020-04-29 00:15:36 -06004894 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4895 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004896 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004897 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004898 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004899 }
4900 }
4901 return skip;
4902}
4903
4904void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4905 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004906 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06004907 auto *cb_access_context = GetAccessContext(commandBuffer);
4908 assert(cb_access_context);
4909 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
4910 auto *context = cb_access_context->GetCurrentAccessContext();
4911 assert(context);
4912
4913 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4914
4915 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004916 // VK_WHOLE_SIZE not allowed
4917 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004918 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004919 }
4920}
locke-lunargff255f92020-05-13 18:53:52 -06004921
4922bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4923 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
4924 bool skip = false;
4925 const auto *cb_access_context = GetAccessContext(commandBuffer);
4926 assert(cb_access_context);
4927 if (!cb_access_context) return skip;
4928
4929 const auto *context = cb_access_context->GetCurrentAccessContext();
4930 assert(context);
4931 if (!context) return skip;
4932
4933 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4934
4935 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004936 const ResourceAccessRange range = MakeRange(dstOffset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004937 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4938 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004939 skip |=
4940 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4941 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004942 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004943 }
4944 }
4945 return skip;
4946}
4947
4948void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4949 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004950 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06004951 auto *cb_access_context = GetAccessContext(commandBuffer);
4952 assert(cb_access_context);
4953 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
4954 auto *context = cb_access_context->GetCurrentAccessContext();
4955 assert(context);
4956
4957 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4958
4959 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004960 const ResourceAccessRange range = MakeRange(dstOffset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004961 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004962 }
4963}
John Zulauf49beb112020-11-04 16:06:31 -07004964
4965bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
4966 bool skip = false;
4967 const auto *cb_context = GetAccessContext(commandBuffer);
4968 assert(cb_context);
4969 if (!cb_context) return skip;
4970
4971 return cb_context->ValidateSetEvent(commandBuffer, event, stageMask);
4972}
4973
4974void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
4975 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
4976 auto *cb_context = GetAccessContext(commandBuffer);
4977 assert(cb_context);
4978 if (!cb_context) return;
John Zulauf4a6105a2020-11-17 15:11:05 -07004979 const auto tag = cb_context->NextCommandTag(CMD_SETEVENT);
4980 cb_context->RecordSetEvent(commandBuffer, event, stageMask, tag);
John Zulauf49beb112020-11-04 16:06:31 -07004981}
4982
4983bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
4984 VkPipelineStageFlags stageMask) const {
4985 bool skip = false;
4986 const auto *cb_context = GetAccessContext(commandBuffer);
4987 assert(cb_context);
4988 if (!cb_context) return skip;
4989
4990 return cb_context->ValidateResetEvent(commandBuffer, event, stageMask);
4991}
4992
4993void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
4994 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
4995 auto *cb_context = GetAccessContext(commandBuffer);
4996 assert(cb_context);
4997 if (!cb_context) return;
4998
4999 cb_context->RecordResetEvent(commandBuffer, event, stageMask);
5000}
5001
5002bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5003 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5004 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5005 uint32_t bufferMemoryBarrierCount,
5006 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5007 uint32_t imageMemoryBarrierCount,
5008 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5009 bool skip = false;
5010 const auto *cb_context = GetAccessContext(commandBuffer);
5011 assert(cb_context);
5012 if (!cb_context) return skip;
5013
John Zulauf669dfd52021-01-27 17:15:28 -07005014 SyncOpWaitEvents wait_events_op(*this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
John Zulaufd5115702021-01-18 12:34:33 -07005015 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5016 imageMemoryBarrierCount, pImageMemoryBarriers);
5017 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005018}
5019
5020void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5021 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5022 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5023 uint32_t bufferMemoryBarrierCount,
5024 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5025 uint32_t imageMemoryBarrierCount,
5026 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5027 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5028 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5029 imageMemoryBarrierCount, pImageMemoryBarriers);
5030
5031 auto *cb_context = GetAccessContext(commandBuffer);
5032 assert(cb_context);
5033 if (!cb_context) return;
5034
John Zulauf4a6105a2020-11-17 15:11:05 -07005035 const auto tag = cb_context->NextCommandTag(CMD_WAITEVENTS);
John Zulauf669dfd52021-01-27 17:15:28 -07005036 SyncOpWaitEvents wait_events_op(*this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
John Zulaufd5115702021-01-18 12:34:33 -07005037 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5038 imageMemoryBarrierCount, pImageMemoryBarriers);
5039 return wait_events_op.Record(cb_context, tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07005040}
5041
5042void SyncEventState::ResetFirstScope() {
5043 for (const auto address_type : kAddressTypes) {
5044 first_scope[static_cast<size_t>(address_type)].clear();
5045 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005046 scope = SyncExecScope();
John Zulauf4a6105a2020-11-17 15:11:05 -07005047}
5048
5049// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
5050SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(VkPipelineStageFlags srcStageMask) const {
5051 IgnoreReason reason = NotIgnored;
5052
5053 if (last_command == CMD_RESETEVENT && !HasBarrier(0U, 0U)) {
5054 reason = ResetWaitRace;
5055 } else if (unsynchronized_set) {
5056 reason = SetRace;
5057 } else {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005058 const VkPipelineStageFlags missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005059 if (missing_bits) reason = MissingStageBits;
5060 }
5061
5062 return reason;
5063}
5064
5065bool SyncEventState::HasBarrier(VkPipelineStageFlags stageMask, VkPipelineStageFlags exec_scope_arg) const {
5066 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5067 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5068 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005069}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005070
John Zulaufd5115702021-01-18 12:34:33 -07005071SyncOpBarriers::SyncOpBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags, VkPipelineStageFlags srcStageMask,
5072 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5073 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5074 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5075 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005076 : dependency_flags_(dependencyFlags),
5077 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, srcStageMask)),
5078 dst_exec_scope_(SyncExecScope::MakeDst(queue_flags, dstStageMask)) {
5079 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5080 MakeMemoryBarriers(src_exec_scope_, dst_exec_scope_, dependencyFlags, memoryBarrierCount, pMemoryBarriers);
5081 MakeBufferMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, bufferMemoryBarrierCount,
5082 pBufferMemoryBarriers);
5083 MakeImageMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, imageMemoryBarrierCount,
5084 pImageMemoryBarriers);
5085}
5086
John Zulaufd5115702021-01-18 12:34:33 -07005087SyncOpPipelineBarrier::SyncOpPipelineBarrier(const SyncValidator &sync_state, VkQueueFlags queue_flags,
5088 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5089 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5090 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5091 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5092 const VkImageMemoryBarrier *pImageMemoryBarriers)
5093 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
5094 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5095
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005096bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
5097 bool skip = false;
5098 const auto *context = cb_context.GetCurrentAccessContext();
5099 assert(context);
5100 if (!context) return skip;
5101 // Validate Image Layout transitions
Nathaniel Cesarioe3025c62021-02-03 16:36:22 -07005102 for (const auto &image_barrier : image_memory_barriers_) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005103 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
5104 const auto *image_state = image_barrier.image.get();
5105 if (!image_state) continue;
5106 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
5107 if (hazard.hazard) {
5108 // PHASE1 TODO -- add tag information to log msg when useful.
5109 const auto &sync_state = cb_context.GetSyncState();
5110 const auto image_handle = image_state->image;
5111 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
5112 "vkCmdPipelineBarrier: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.",
5113 string_SyncHazard(hazard.hazard), image_barrier.index,
5114 sync_state.report_data->FormatHandle(image_handle).c_str(),
5115 cb_context.FormatUsage(hazard).c_str());
5116 }
5117 }
5118
5119 return skip;
5120}
5121
John Zulaufd5115702021-01-18 12:34:33 -07005122struct SyncOpPipelineBarrierFunctorFactory {
5123 using BarrierOpFunctor = PipelineBarrierOp;
5124 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5125 using GlobalBarrierOpFunctor = PipelineBarrierOp;
5126 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5127 using BufferRange = ResourceAccessRange;
5128 using ImageRange = subresource_adapter::ImageRangeGenerator;
5129 using GlobalRange = ResourceAccessRange;
5130
5131 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier, bool layout_transition) const {
5132 return ApplyFunctor(BarrierOpFunctor(barrier, layout_transition));
5133 }
5134 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5135 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
5136 }
5137 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier) const {
5138 return GlobalBarrierOpFunctor(barrier, false);
5139 }
5140
5141 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
5142 if (!SimpleBinding(buffer)) return ResourceAccessRange();
5143 const auto base_address = ResourceBaseAddress(buffer);
5144 return (range + base_address);
5145 }
5146 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5147 if (!SimpleBinding(image)) subresource_adapter::ImageRangeGenerator();
5148
5149 const auto base_address = ResourceBaseAddress(image);
5150 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), range.subresource_range, range.offset,
5151 range.extent, base_address);
5152 return range_gen;
5153 }
5154 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
5155};
5156
5157template <typename Barriers, typename FunctorFactory>
5158void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5159 AccessContext *context) {
5160 for (const auto &barrier : barriers) {
5161 const auto *state = barrier.GetState();
5162 if (state) {
5163 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
5164 auto update_action = factory.MakeApplyFunctor(barrier.barrier, barrier.IsLayoutTransition());
5165 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
5166 UpdateMemoryAccessState(accesses, update_action, &range_gen);
5167 }
5168 }
5169}
5170
5171template <typename Barriers, typename FunctorFactory>
5172void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5173 AccessContext *access_context) {
5174 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
5175 for (const auto &barrier : barriers) {
5176 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(barrier));
5177 }
5178 for (const auto address_type : kAddressTypes) {
5179 auto range_gen = factory.MakeGlobalRangeGen(address_type);
5180 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
5181 }
5182}
5183
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005184void SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07005185 SyncOpPipelineBarrierFunctorFactory factory;
5186 auto *access_context = cb_context->GetCurrentAccessContext();
5187 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5188 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5189 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005190
5191 cb_context->ApplyGlobalBarriersToEvents(src_exec_scope_, dst_exec_scope_);
5192}
5193
John Zulaufd5115702021-01-18 12:34:33 -07005194void SyncOpBarriers::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst, VkDependencyFlags dependency_flags,
5195 uint32_t memory_barrier_count, const VkMemoryBarrier *memory_barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005196 memory_barriers_.reserve(std::min<uint32_t>(1, memory_barrier_count));
5197 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
5198 const auto &barrier = memory_barriers[barrier_index];
5199 SyncBarrier sync_barrier(barrier, src, dst);
5200 memory_barriers_.emplace_back(sync_barrier);
5201 }
5202 if (0 == memory_barrier_count) {
5203 // If there are no global memory barriers, force an exec barrier
5204 memory_barriers_.emplace_back(SyncBarrier(src, dst));
5205 }
5206}
5207
John Zulaufd5115702021-01-18 12:34:33 -07005208void SyncOpBarriers::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5209 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5210 const VkBufferMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005211 buffer_memory_barriers_.reserve(barrier_count);
5212 for (uint32_t index = 0; index < barrier_count; index++) {
5213 const auto &barrier = barriers[index];
5214 auto buffer = sync_state.GetShared<BUFFER_STATE>(barrier.buffer);
5215 if (buffer) {
5216 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
5217 const auto range = MakeRange(barrier.offset, barrier_size);
5218 const SyncBarrier sync_barrier(barrier, src, dst);
5219 buffer_memory_barriers_.emplace_back(buffer, sync_barrier, range);
5220 } else {
5221 buffer_memory_barriers_.emplace_back();
5222 }
5223 }
5224}
5225
John Zulaufd5115702021-01-18 12:34:33 -07005226void SyncOpBarriers::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5227 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5228 const VkImageMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005229 image_memory_barriers_.reserve(barrier_count);
5230 for (uint32_t index = 0; index < barrier_count; index++) {
5231 const auto &barrier = barriers[index];
5232 const auto image = sync_state.GetShared<IMAGE_STATE>(barrier.image);
5233 if (image) {
5234 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
5235 const SyncBarrier sync_barrier(barrier, src, dst);
5236 image_memory_barriers_.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout,
5237 subresource_range);
5238 } else {
5239 image_memory_barriers_.emplace_back();
5240 image_memory_barriers_.back().index = index; // Just in case we're interested in the ones we skipped.
5241 }
5242 }
5243}
John Zulaufd5115702021-01-18 12:34:33 -07005244
John Zulauf669dfd52021-01-27 17:15:28 -07005245SyncOpWaitEvents::SyncOpWaitEvents(const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
John Zulaufd5115702021-01-18 12:34:33 -07005246 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5247 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5248 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5249 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf669dfd52021-01-27 17:15:28 -07005250 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005251 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
5252 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07005253 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07005254}
5255
5256bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
5257 const auto cmd = CMD_WAITEVENTS;
5258 const char *const ignored = "Wait operation is ignored for this event.";
5259 bool skip = false;
5260 const auto &sync_state = cb_context.GetSyncState();
5261 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer;
5262
5263 if (src_exec_scope_.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
5264 const char *const cmd_name = CommandTypeString(cmd);
5265 const char *const vuid = "SYNC-vkCmdWaitEvents-hostevent-unsupported";
5266 skip = sync_state.LogInfo(command_buffer_handle, vuid,
5267 "%s, srcStageMask includes %s, unsupported by synchronization validaton.", cmd_name,
5268 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT), ignored);
5269 }
5270
5271 VkPipelineStageFlags event_stage_masks = 0U;
5272 bool events_not_found = false;
John Zulauf669dfd52021-01-27 17:15:28 -07005273 const auto *events_context = cb_context.GetCurrentEventsContext();
5274 assert(events_context);
5275 for (const auto &sync_event_pair : *events_context) {
5276 const auto *sync_event = sync_event_pair.second.get();
John Zulaufd5115702021-01-18 12:34:33 -07005277 if (!sync_event) {
5278 // 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 -07005279 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
5280 // new validation error... wait without previously submitted set event...
5281 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 -07005282
5283 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
5284 }
5285 const auto event = sync_event->event->event;
5286 // TODO add "destroyed" checks
5287
5288 event_stage_masks |= sync_event->scope.mask_param;
5289 const auto ignore_reason = sync_event->IsIgnoredByWait(src_exec_scope_.mask_param);
5290 if (ignore_reason) {
5291 switch (ignore_reason) {
5292 case SyncEventState::ResetWaitRace: {
5293 const char *const cmd_name = CommandTypeString(cmd);
5294 const char *const vuid = "SYNC-vkCmdWaitEvents-missingbarrier-reset";
5295 const char *const message =
5296 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
5297 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5298 cmd_name, CommandTypeString(sync_event->last_command), ignored);
5299 break;
5300 }
5301 case SyncEventState::SetRace: {
5302 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for this
5303 // event
5304 const char *const cmd_name = CommandTypeString(cmd);
5305 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
5306 const char *const message =
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07005307 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
John Zulaufd5115702021-01-18 12:34:33 -07005308 const char *const reason = "First synchronization scope is undefined.";
5309 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5310 CommandTypeString(sync_event->last_command), reason, ignored);
5311 break;
5312 }
5313 case SyncEventState::MissingStageBits: {
5314 const VkPipelineStageFlags missing_bits = sync_event->scope.mask_param & ~src_exec_scope_.mask_param;
5315 // Issue error message that event waited for is not in wait events scope
5316 const char *const cmd_name = CommandTypeString(cmd);
5317 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5318 const char *const message =
5319 "%s: %s stageMask 0x%" PRIx32 " includes bits not present in srcStageMask 0x%" PRIx32
5320 ". Bits missing from srcStageMask %s. %s";
5321 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5322 sync_event->scope.mask_param, src_exec_scope_.mask_param,
5323 string_VkPipelineStageFlags(missing_bits).c_str(), ignored);
5324 break;
5325 }
5326 default:
5327 assert(ignore_reason == SyncEventState::NotIgnored);
5328 }
5329 } else if (image_memory_barriers_.size()) {
5330 const auto *context = cb_context.GetCurrentAccessContext();
5331 assert(context);
5332 for (const auto &image_memory_barrier : image_memory_barriers_) {
5333 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
5334 const auto *image_state = image_memory_barrier.image.get();
5335 if (!image_state) continue;
5336 const auto &subresource_range = image_memory_barrier.range.subresource_range;
5337 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
5338 const auto hazard =
5339 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
5340 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
5341 if (hazard.hazard) {
5342 const char *const cmd_name = CommandTypeString(cmd);
5343 skip |= sync_state.LogError(image_state->image, string_SyncHazardVUID(hazard.hazard),
5344 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", cmd_name,
5345 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
5346 sync_state.report_data->FormatHandle(image_state->image).c_str(),
5347 cb_context.FormatUsage(hazard).c_str());
5348 break;
5349 }
5350 }
5351 }
5352 }
5353
5354 // Note that we can't check for HOST in pEvents as we don't track that set event type
5355 const auto extra_stage_bits = (src_exec_scope_.mask_param & ~VK_PIPELINE_STAGE_HOST_BIT) & ~event_stage_masks;
5356 if (extra_stage_bits) {
5357 // Issue error message that event waited for is not in wait events scope
5358 const char *const cmd_name = CommandTypeString(cmd);
5359 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5360 const char *const message =
5361 "%s: srcStageMask 0x%" PRIx32 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
5362 if (events_not_found) {
5363 skip |= sync_state.LogInfo(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5364 string_VkPipelineStageFlags(extra_stage_bits).c_str(),
5365 " vkCmdSetEvent may be in previously submitted command buffer.");
5366 } else {
5367 skip |= sync_state.LogError(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5368 string_VkPipelineStageFlags(extra_stage_bits).c_str(), "");
5369 }
5370 }
5371 return skip;
5372}
5373
5374struct SyncOpWaitEventsFunctorFactory {
5375 using BarrierOpFunctor = WaitEventBarrierOp;
5376 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5377 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
5378 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5379 using BufferRange = EventSimpleRangeGenerator;
5380 using ImageRange = EventImageRangeGenerator;
5381 using GlobalRange = EventSimpleRangeGenerator;
5382
5383 // Need to restrict to only valid exec and access scope for this event
5384 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
5385 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
5386 barrier.src_exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope;
5387 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
5388 return barrier;
5389 }
5390 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier_arg, bool layout_transition) const {
5391 auto barrier = RestrictToEvent(barrier_arg);
5392 return ApplyFunctor(BarrierOpFunctor(sync_event->first_scope_tag, barrier, layout_transition));
5393 }
5394 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5395 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
5396 }
5397 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier_arg) const {
5398 auto barrier = RestrictToEvent(barrier_arg);
5399 return GlobalBarrierOpFunctor(sync_event->first_scope_tag, barrier, false);
5400 }
5401
5402 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
5403 const AccessAddressType address_type = GetAccessAddressType(buffer);
5404 const auto base_address = ResourceBaseAddress(buffer);
5405 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
5406 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
5407 return filtered_range_gen;
5408 }
5409 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5410 if (!SimpleBinding(image)) return ImageRange();
5411 const auto address_type = GetAccessAddressType(image);
5412 const auto base_address = ResourceBaseAddress(image);
5413 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), range.subresource_range,
5414 range.offset, range.extent, base_address);
5415 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
5416
5417 return filtered_range_gen;
5418 }
5419 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
5420 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
5421 }
5422 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
5423 SyncEventState *sync_event;
5424};
5425
5426void SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
5427 auto *access_context = cb_context->GetCurrentAccessContext();
5428 assert(access_context);
5429 if (!access_context) return;
John Zulauf669dfd52021-01-27 17:15:28 -07005430 auto *events_context = cb_context->GetCurrentEventsContext();
5431 assert(events_context);
5432 if (!events_context) return;
John Zulaufd5115702021-01-18 12:34:33 -07005433
5434 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
5435 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
5436 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
5437 access_context->ResolvePreviousAccesses();
5438
5439 const auto &dst = dst_exec_scope_;
5440 // TODO... this needs change the SyncEventContext it's using depending on whether this is replay... the recorded
5441 // 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 -07005442 for (auto &event_shared : events_) {
5443 if (!event_shared.get()) continue;
5444 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07005445
5446 sync_event->last_command = CMD_WAITEVENTS;
5447
5448 if (!sync_event->IsIgnoredByWait(src_exec_scope_.mask_param)) {
5449 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
5450 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
5451 // of the barriers is maintained.
5452 SyncOpWaitEventsFunctorFactory factory(sync_event);
5453 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5454 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5455 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
5456
5457 // Apply the global barrier to the event itself (for race condition tracking)
5458 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
5459 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
5460 sync_event->barriers |= dst.exec_scope;
5461 } else {
5462 // We ignored this wait, so we don't have any effective synchronization barriers for it.
5463 sync_event->barriers = 0U;
5464 }
5465 }
5466
5467 // Apply the pending barriers
5468 ResolvePendingBarrierFunctor apply_pending_action(tag);
5469 access_context->ApplyToContext(apply_pending_action);
5470}
5471
John Zulauf669dfd52021-01-27 17:15:28 -07005472void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07005473 events_.reserve(event_count);
5474 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
John Zulauf669dfd52021-01-27 17:15:28 -07005475 events_.emplace_back(sync_state.GetShared<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07005476 }
5477}