blob: e51c7edbd37f13cc0e286facffe392c9a73a13ff [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"
27
John Zulauf43cc7462020-12-03 12:33:12 -070028const static std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
29 AccessAddressType::kLinear, AccessAddressType::kIdealized};
30
John Zulaufd5115702021-01-18 12:34:33 -070031static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
32static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) { return AccessContext::ImageAddressType(image); }
33
John Zulauf9cb530d2019-09-30 14:14:10 -060034static const char *string_SyncHazardVUID(SyncHazard hazard) {
35 switch (hazard) {
36 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070037 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060038 break;
39 case SyncHazard::READ_AFTER_WRITE:
40 return "SYNC-HAZARD-READ_AFTER_WRITE";
41 break;
42 case SyncHazard::WRITE_AFTER_READ:
43 return "SYNC-HAZARD-WRITE_AFTER_READ";
44 break;
45 case SyncHazard::WRITE_AFTER_WRITE:
46 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
47 break;
John Zulauf2f952d22020-02-10 11:34:51 -070048 case SyncHazard::READ_RACING_WRITE:
49 return "SYNC-HAZARD-READ-RACING-WRITE";
50 break;
51 case SyncHazard::WRITE_RACING_WRITE:
52 return "SYNC-HAZARD-WRITE-RACING-WRITE";
53 break;
54 case SyncHazard::WRITE_RACING_READ:
55 return "SYNC-HAZARD-WRITE-RACING-READ";
56 break;
John Zulauf9cb530d2019-09-30 14:14:10 -060057 default:
58 assert(0);
59 }
60 return "SYNC-HAZARD-INVALID";
61}
62
John Zulauf59e25072020-07-17 10:55:21 -060063static bool IsHazardVsRead(SyncHazard hazard) {
64 switch (hazard) {
65 case SyncHazard::NONE:
66 return false;
67 break;
68 case SyncHazard::READ_AFTER_WRITE:
69 return false;
70 break;
71 case SyncHazard::WRITE_AFTER_READ:
72 return true;
73 break;
74 case SyncHazard::WRITE_AFTER_WRITE:
75 return false;
76 break;
77 case SyncHazard::READ_RACING_WRITE:
78 return false;
79 break;
80 case SyncHazard::WRITE_RACING_WRITE:
81 return false;
82 break;
83 case SyncHazard::WRITE_RACING_READ:
84 return true;
85 break;
86 default:
87 assert(0);
88 }
89 return false;
90}
91
John Zulauf9cb530d2019-09-30 14:14:10 -060092static const char *string_SyncHazard(SyncHazard hazard) {
93 switch (hazard) {
94 case SyncHazard::NONE:
95 return "NONR";
96 break;
97 case SyncHazard::READ_AFTER_WRITE:
98 return "READ_AFTER_WRITE";
99 break;
100 case SyncHazard::WRITE_AFTER_READ:
101 return "WRITE_AFTER_READ";
102 break;
103 case SyncHazard::WRITE_AFTER_WRITE:
104 return "WRITE_AFTER_WRITE";
105 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700106 case SyncHazard::READ_RACING_WRITE:
107 return "READ_RACING_WRITE";
108 break;
109 case SyncHazard::WRITE_RACING_WRITE:
110 return "WRITE_RACING_WRITE";
111 break;
112 case SyncHazard::WRITE_RACING_READ:
113 return "WRITE_RACING_READ";
114 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600115 default:
116 assert(0);
117 }
118 return "INVALID HAZARD";
119}
120
John Zulauf37ceaed2020-07-03 16:18:15 -0600121static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
122 // Return the info for the first bit found
123 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700124 for (size_t i = 0; i < flags.size(); i++) {
125 if (flags.test(i)) {
126 info = &syncStageAccessInfoByStageAccessIndex[i];
127 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600128 }
129 }
130 return info;
131}
132
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700133static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600134 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700135 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600136 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700137 } else {
138 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
139 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
140 if ((flags & info.stage_access_bit).any()) {
141 if (!out_str.empty()) {
142 out_str.append(sep);
143 }
144 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600145 }
John Zulauf59e25072020-07-17 10:55:21 -0600146 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700147 if (out_str.length() == 0) {
148 out_str.append("Unhandled SyncStageAccess");
149 }
John Zulauf59e25072020-07-17 10:55:21 -0600150 }
151 return out_str;
152}
153
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700154static std::string string_UsageTag(const ResourceUsageTag &tag) {
155 std::stringstream out;
156
John Zulauffaea0ee2021-01-14 14:01:32 -0700157 out << "command: " << CommandTypeString(tag.command);
158 out << ", seq_no: " << tag.seq_num;
159 if (tag.sub_command != 0) {
160 out << ", subcmd: " << tag.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700161 }
162 return out.str();
163}
164
John Zulauffaea0ee2021-01-14 14:01:32 -0700165std::string CommandBufferAccessContext::FormatUsage(const HazardResult &hazard) const {
John Zulauf37ceaed2020-07-03 16:18:15 -0600166 const auto &tag = hazard.tag;
John Zulauf59e25072020-07-17 10:55:21 -0600167 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
168 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
John Zulauf1dae9192020-06-16 15:46:44 -0600169 std::stringstream out;
John Zulauf37ceaed2020-07-03 16:18:15 -0600170 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
171 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
John Zulauf59e25072020-07-17 10:55:21 -0600172 out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name;
173 if (IsHazardVsRead(hazard.hazard)) {
174 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
175 out << ", read_barriers: " << string_VkPipelineStageFlags(barriers);
176 } else {
177 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
178 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
179 }
180
John Zulauffaea0ee2021-01-14 14:01:32 -0700181 // PHASE2 TODO -- add comand buffer and reset from secondary if applicable
182 out << ", " << string_UsageTag(tag) << ", reset_no: " << reset_count_;
John Zulauf1dae9192020-06-16 15:46:44 -0600183 return out.str();
184}
185
John Zulaufd14743a2020-07-03 09:42:39 -0600186// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
187// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
188// also reflects this special case for read hazard detection (using access instead of exec scope)
John Zulaufb027cdb2020-05-21 14:25:22 -0600189static constexpr VkPipelineStageFlags kColorAttachmentExecScope = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700190static const SyncStageAccessFlags kColorAttachmentAccessScope =
191 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
192 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
193 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
194 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulaufb027cdb2020-05-21 14:25:22 -0600195static constexpr VkPipelineStageFlags kDepthStencilAttachmentExecScope =
196 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700197static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
198 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
199 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
200 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulauf8e3c3e92021-01-06 11:19:36 -0700201static constexpr VkPipelineStageFlags kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
202static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600203
John Zulauf8e3c3e92021-01-06 11:19:36 -0700204ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
205 {{0U, SyncStageAccessFlags()},
206 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
207 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
208 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
209
John Zulauf7635de32020-05-29 17:14:15 -0600210// 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 -0700211static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, ResourceUsageTag::kMaxCount,
212 ResourceUsageTag::kMaxCount, CMD_NONE);
John Zulaufb027cdb2020-05-21 14:25:22 -0600213
John Zulaufb02c1eb2020-10-06 16:33:36 -0600214static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) {
215 return bindable.binding.offset + bindable.binding.mem_state->fake_base_address;
216}
217
218static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; }
219
locke-lunarg3c038002020-04-30 23:08:08 -0600220inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
221 if (size == VK_WHOLE_SIZE) {
222 return (whole_size - offset);
223 }
224 return size;
225}
226
John Zulauf3e86bf02020-09-12 10:47:57 -0600227static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
228 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
229}
230
John Zulauf16adfc92020-04-08 10:28:33 -0600231template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600232static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600233 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
234}
235
John Zulauf355e49b2020-04-24 15:11:15 -0600236static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600237
John Zulauf3e86bf02020-09-12 10:47:57 -0600238static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
239 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
240}
241
242static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
243 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
244}
245
John Zulauf4a6105a2020-11-17 15:11:05 -0700246// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
247//
John Zulauf10f1f522020-12-18 12:00:35 -0700248// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
249//
John Zulauf4a6105a2020-11-17 15:11:05 -0700250// Usage:
251// Constructor() -- initializes the generator to point to the begin of the space declared.
252// * -- the current range of the generator empty signfies end
253// ++ -- advance to the next non-empty range (or end)
254
255// A wrapper for a single range with the same semantics as the actual generators below
256template <typename KeyType>
257class SingleRangeGenerator {
258 public:
259 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700260 const KeyType &operator*() const { return current_; }
261 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700262 SingleRangeGenerator &operator++() {
263 current_ = KeyType(); // just one real range
264 return *this;
265 }
266
267 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
268
269 private:
270 SingleRangeGenerator() = default;
271 const KeyType range_;
272 KeyType current_;
273};
274
275// Generate the ranges that are the intersection of range and the entries in the FilterMap
276template <typename FilterMap, typename KeyType = typename FilterMap::key_type>
277class FilteredRangeGenerator {
278 public:
John Zulaufd5115702021-01-18 12:34:33 -0700279 // Default constructed is safe to dereference for "empty" test, but for no other operation.
280 FilteredRangeGenerator() : range_(), filter_(nullptr), filter_pos_(), current_() {
281 // Default construction for KeyType *must* be empty range
282 assert(current_.empty());
283 }
John Zulauf4a6105a2020-11-17 15:11:05 -0700284 FilteredRangeGenerator(const FilterMap &filter, const KeyType &range)
285 : range_(range), filter_(&filter), filter_pos_(), current_() {
286 SeekBegin();
287 }
John Zulaufd5115702021-01-18 12:34:33 -0700288 FilteredRangeGenerator(const FilteredRangeGenerator &from) = default;
289
John Zulauf4a6105a2020-11-17 15:11:05 -0700290 const KeyType &operator*() const { return current_; }
291 const KeyType *operator->() const { return &current_; }
292 FilteredRangeGenerator &operator++() {
293 ++filter_pos_;
294 UpdateCurrent();
295 return *this;
296 }
297
298 bool operator==(const FilteredRangeGenerator &other) const { return current_ == other.current_; }
299
300 private:
John Zulauf4a6105a2020-11-17 15:11:05 -0700301 void UpdateCurrent() {
302 if (filter_pos_ != filter_->cend()) {
303 current_ = range_ & filter_pos_->first;
304 } else {
305 current_ = KeyType();
306 }
307 }
308 void SeekBegin() {
309 filter_pos_ = filter_->lower_bound(range_);
310 UpdateCurrent();
311 }
312 const KeyType range_;
313 const FilterMap *filter_;
314 typename FilterMap::const_iterator filter_pos_;
315 KeyType current_;
316};
John Zulaufd5115702021-01-18 12:34:33 -0700317using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700318using EventSimpleRangeGenerator = FilteredRangeGenerator<SyncEventState::ScopeMap>;
319
320// Templated to allow for different Range generators or map sources...
321
322// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulauf4a6105a2020-11-17 15:11:05 -0700323template <typename FilterMap, typename RangeGen, typename KeyType = typename FilterMap::key_type>
324class FilteredGeneratorGenerator {
325 public:
John Zulaufd5115702021-01-18 12:34:33 -0700326 // Default constructed is safe to dereference for "empty" test, but for no other operation.
327 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
328 // Default construction for KeyType *must* be empty range
329 assert(current_.empty());
330 }
331 FilteredGeneratorGenerator(const FilterMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700332 SeekBegin();
333 }
John Zulaufd5115702021-01-18 12:34:33 -0700334 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700335 const KeyType &operator*() const { return current_; }
336 const KeyType *operator->() const { return &current_; }
337 FilteredGeneratorGenerator &operator++() {
338 KeyType gen_range = GenRange();
339 KeyType filter_range = FilterRange();
340 current_ = KeyType();
341 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
342 if (gen_range.end > filter_range.end) {
343 // if the generated range is beyond the filter_range, advance the filter range
344 filter_range = AdvanceFilter();
345 } else {
346 gen_range = AdvanceGen();
347 }
348 current_ = gen_range & filter_range;
349 }
350 return *this;
351 }
352
353 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
354
355 private:
356 KeyType AdvanceFilter() {
357 ++filter_pos_;
358 auto filter_range = FilterRange();
359 if (filter_range.valid()) {
360 FastForwardGen(filter_range);
361 }
362 return filter_range;
363 }
364 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700365 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700366 auto gen_range = GenRange();
367 if (gen_range.valid()) {
368 FastForwardFilter(gen_range);
369 }
370 return gen_range;
371 }
372
373 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700374 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700375
376 KeyType FastForwardFilter(const KeyType &range) {
377 auto filter_range = FilterRange();
378 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700379 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700380 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
381 if (retry_count < kRetryLimit) {
382 ++filter_pos_;
383 filter_range = FilterRange();
384 retry_count++;
385 } else {
386 // Okay we've tried walking, do a seek.
387 filter_pos_ = filter_->lower_bound(range);
388 break;
389 }
390 }
391 return FilterRange();
392 }
393
394 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
395 // faster.
396 KeyType FastForwardGen(const KeyType &range) {
397 auto gen_range = GenRange();
398 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700399 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700400 gen_range = GenRange();
401 }
402 return gen_range;
403 }
404
405 void SeekBegin() {
406 auto gen_range = GenRange();
407 if (gen_range.empty()) {
408 current_ = KeyType();
409 filter_pos_ = filter_->cend();
410 } else {
411 filter_pos_ = filter_->lower_bound(gen_range);
412 current_ = gen_range & FilterRange();
413 }
414 }
415
John Zulauf4a6105a2020-11-17 15:11:05 -0700416 const FilterMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700417 RangeGen gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700418 typename FilterMap::const_iterator filter_pos_;
419 KeyType current_;
420};
421
422using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
423
John Zulauf0cb5be22020-01-23 12:18:22 -0700424// Expand the pipeline stage without regard to whether the are valid w.r.t. queue or extension
425VkPipelineStageFlags ExpandPipelineStages(VkQueueFlags queue_flags, VkPipelineStageFlags stage_mask) {
426 VkPipelineStageFlags expanded = stage_mask;
427 if (VK_PIPELINE_STAGE_ALL_COMMANDS_BIT & stage_mask) {
428 expanded = expanded & ~VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
429 for (const auto &all_commands : syncAllCommandStagesByQueueFlags) {
430 if (all_commands.first & queue_flags) {
431 expanded |= all_commands.second;
432 }
433 }
434 }
435 if (VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT & stage_mask) {
436 expanded = expanded & ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
437 expanded |= syncAllCommandStagesByQueueFlags.at(VK_QUEUE_GRAPHICS_BIT) & ~VK_PIPELINE_STAGE_HOST_BIT;
438 }
439 return expanded;
440}
441
John Zulauf36bcf6a2020-02-03 15:12:52 -0700442VkPipelineStageFlags RelatedPipelineStages(VkPipelineStageFlags stage_mask,
Jeremy Gebben91c36902020-11-09 08:17:08 -0700443 const std::map<VkPipelineStageFlagBits, VkPipelineStageFlags> &map) {
John Zulauf36bcf6a2020-02-03 15:12:52 -0700444 VkPipelineStageFlags unscanned = stage_mask;
445 VkPipelineStageFlags related = 0;
Jonah Ryan-Davis185189c2020-07-14 10:28:52 -0400446 for (const auto &entry : map) {
447 const auto &stage = entry.first;
John Zulauf36bcf6a2020-02-03 15:12:52 -0700448 if (stage & unscanned) {
449 related = related | entry.second;
450 unscanned = unscanned & ~stage;
451 if (!unscanned) break;
452 }
453 }
454 return related;
455}
456
457VkPipelineStageFlags WithEarlierPipelineStages(VkPipelineStageFlags stage_mask) {
458 return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyEarlierStages);
459}
460
461VkPipelineStageFlags WithLaterPipelineStages(VkPipelineStageFlags stage_mask) {
462 return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyLaterStages);
463}
464
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700465static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
John Zulauf5c5e88d2019-12-26 11:22:02 -0700466
John Zulauf3e86bf02020-09-12 10:47:57 -0600467ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
468 VkDeviceSize stride) {
469 VkDeviceSize range_start = offset + first_index * stride;
470 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600471 if (count == UINT32_MAX) {
472 range_size = buf_whole_size - range_start;
473 } else {
474 range_size = count * stride;
475 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600476 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600477}
478
locke-lunarg654e3692020-06-04 17:19:15 -0600479SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
480 VkShaderStageFlagBits stage_flag) {
481 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
482 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
483 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
484 }
485 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
486 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
487 assert(0);
488 }
489 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
490 return stage_access->second.uniform_read;
491 }
492
493 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
494 // Because if write hazard happens, read hazard might or might not happen.
495 // But if write hazard doesn't happen, read hazard is impossible to happen.
496 if (descriptor_data.is_writable) {
497 return stage_access->second.shader_write;
498 }
499 return stage_access->second.shader_read;
500}
501
locke-lunarg37047832020-06-12 13:44:45 -0600502bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
503 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
504 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
505 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
506 ? true
507 : false;
508}
509
510bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
511 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
512 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
513 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
514 ? true
515 : false;
516}
517
John Zulauf355e49b2020-04-24 15:11:15 -0600518// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600519template <typename Action>
520static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
521 Action &action) {
522 // At this point the "apply over range" logic only supports a single memory binding
523 if (!SimpleBinding(image_state)) return;
524 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600525 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700526 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
527 image_state.createInfo.extent, base_address);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600528 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700529 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600530 }
531}
532
John Zulauf7635de32020-05-29 17:14:15 -0600533// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
534// Used by both validation and record operations
535//
536// The signature for Action() reflect the needs of both uses.
537template <typename Action>
538void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
539 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) {
540 VkExtent3D extent = CastTo3D(render_area.extent);
541 VkOffset3D offset = CastTo3D(render_area.offset);
542 const auto &rp_ci = rp_state.createInfo;
543 const auto *attachment_ci = rp_ci.pAttachments;
544 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
545
546 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
547 const auto *color_attachments = subpass_ci.pColorAttachments;
548 const auto *color_resolve = subpass_ci.pResolveAttachments;
549 if (color_resolve && color_attachments) {
550 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
551 const auto &color_attach = color_attachments[i].attachment;
552 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
553 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
554 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700555 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600556 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700557 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment, offset, extent, 0);
John Zulauf7635de32020-05-29 17:14:15 -0600558 }
559 }
560 }
561
562 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700563 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600564 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
565 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
566 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
567 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
568 const auto src_ci = attachment_ci[src_at];
569 // The formats are required to match so we can pick either
570 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
571 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
572 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
573 VkImageAspectFlags aspect_mask = 0u;
574
575 // Figure out which aspects are actually touched during resolve operations
576 const char *aspect_string = nullptr;
577 if (resolve_depth && resolve_stencil) {
578 // Validate all aspects together
579 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
580 aspect_string = "depth/stencil";
581 } else if (resolve_depth) {
582 // Validate depth only
583 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
584 aspect_string = "depth";
585 } else if (resolve_stencil) {
586 // Validate all stencil only
587 aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT;
588 aspect_string = "stencil";
589 }
590
591 if (aspect_mask) {
592 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700593 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600594 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at],
John Zulauf8e3c3e92021-01-06 11:19:36 -0700595 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600596 }
597 }
598}
599
600// Action for validating resolve operations
601class ValidateResolveAction {
602 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700603 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
604 const CommandBufferAccessContext &cb_context, const char *func_name)
John Zulauf7635de32020-05-29 17:14:15 -0600605 : render_pass_(render_pass),
606 subpass_(subpass),
607 context_(context),
John Zulauffaea0ee2021-01-14 14:01:32 -0700608 cb_context_(cb_context),
John Zulauf7635de32020-05-29 17:14:15 -0600609 func_name_(func_name),
610 skip_(false) {}
611 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 -0700612 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600613 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
614 HazardResult hazard;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700615 hazard = context_.DetectHazard(view, current_usage, ordering_rule, offset, extent, aspect_mask);
John Zulauf7635de32020-05-29 17:14:15 -0600616 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700617 skip_ |=
618 cb_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
619 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
620 " to resolve attachment %" PRIu32 ". Access info %s.",
621 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
622 attachment_name, src_at, dst_at, cb_context_.FormatUsage(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600623 }
624 }
625 // Providing a mechanism for the constructing caller to get the result of the validation
626 bool GetSkip() const { return skip_; }
627
628 private:
629 VkRenderPass render_pass_;
630 const uint32_t subpass_;
631 const AccessContext &context_;
John Zulauffaea0ee2021-01-14 14:01:32 -0700632 const CommandBufferAccessContext &cb_context_;
John Zulauf7635de32020-05-29 17:14:15 -0600633 const char *func_name_;
634 bool skip_;
635};
636
637// Update action for resolve operations
638class UpdateStateResolveAction {
639 public:
640 UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {}
641 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 -0700642 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf7635de32020-05-29 17:14:15 -0600643 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
644 // Ignores validation only arguments...
John Zulauf8e3c3e92021-01-06 11:19:36 -0700645 context_.UpdateAccessState(view, current_usage, ordering_rule, offset, extent, aspect_mask, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600646 }
647
648 private:
649 AccessContext &context_;
650 const ResourceUsageTag &tag_;
651};
652
John Zulauf59e25072020-07-17 10:55:21 -0600653void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700654 const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) {
John Zulauf59e25072020-07-17 10:55:21 -0600655 access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_));
656 usage_index = usage_index_;
657 hazard = hazard_;
658 prior_access = prior_;
659 tag = tag_;
660}
661
John Zulauf540266b2020-04-06 18:54:53 -0600662AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
663 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600664 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600665 Reset();
666 const auto &subpass_dep = dependencies[subpass];
667 prev_.reserve(subpass_dep.prev.size());
John Zulauf355e49b2020-04-24 15:11:15 -0600668 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600669 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600670 const auto prev_pass = prev_dep.first->pass;
671 const auto &prev_barriers = prev_dep.second;
672 assert(prev_dep.second.size());
673 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
674 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700675 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600676
677 async_.reserve(subpass_dep.async.size());
678 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700679 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600680 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600681 if (subpass_dep.barrier_from_external.size()) {
682 src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external);
John Zulaufe5da6e52020-03-18 15:32:18 -0600683 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600684 if (subpass_dep.barrier_to_external.size()) {
685 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600686 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700687}
688
John Zulauf5f13a792020-03-10 07:31:21 -0600689template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700690HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600691 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600692 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600693 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600694
695 HazardResult hazard;
696 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
697 hazard = detector.Detect(prev);
698 }
699 return hazard;
700}
701
John Zulauf4a6105a2020-11-17 15:11:05 -0700702template <typename Action>
703void AccessContext::ForAll(Action &&action) {
704 for (const auto address_type : kAddressTypes) {
705 auto &accesses = GetAccessStateMap(address_type);
706 for (const auto &access : accesses) {
707 action(address_type, access);
708 }
709 }
710}
711
John Zulauf3d84f1b2020-03-09 13:33:25 -0600712// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
713// the DAG of the contexts (for example subpasses)
714template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700715HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600716 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600717 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600718
John Zulauf1a224292020-06-30 14:52:13 -0600719 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600720 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
721 // so we'll check these first
722 for (const auto &async_context : async_) {
723 hazard = async_context->DetectAsyncHazard(type, detector, range);
724 if (hazard.hazard) return hazard;
725 }
John Zulauf5f13a792020-03-10 07:31:21 -0600726 }
727
John Zulauf1a224292020-06-30 14:52:13 -0600728 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600729
John Zulauf69133422020-05-20 14:55:53 -0600730 const auto &accesses = GetAccessStateMap(type);
731 const auto from = accesses.lower_bound(range);
732 const auto to = accesses.upper_bound(range);
733 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600734
John Zulauf69133422020-05-20 14:55:53 -0600735 for (auto pos = from; pos != to; ++pos) {
736 // Cover any leading gap, or gap between entries
737 if (detect_prev) {
738 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
739 // Cover any leading gap, or gap between entries
740 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600741 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600742 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600743 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600744 if (hazard.hazard) return hazard;
745 }
John Zulauf69133422020-05-20 14:55:53 -0600746 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
747 gap.begin = pos->first.end;
748 }
749
750 hazard = detector.Detect(pos);
751 if (hazard.hazard) return hazard;
752 }
753
754 if (detect_prev) {
755 // Detect in the trailing empty as needed
756 gap.end = range.end;
757 if (gap.non_empty()) {
758 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600759 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600760 }
761
762 return hazard;
763}
764
765// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
766template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700767HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
768 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600769 auto &accesses = GetAccessStateMap(type);
770 const auto from = accesses.lower_bound(range);
771 const auto to = accesses.upper_bound(range);
772
John Zulauf3d84f1b2020-03-09 13:33:25 -0600773 HazardResult hazard;
John Zulauf16adfc92020-04-08 10:28:33 -0600774 for (auto pos = from; pos != to && !hazard.hazard; ++pos) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700775 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600776 }
John Zulauf16adfc92020-04-08 10:28:33 -0600777
John Zulauf3d84f1b2020-03-09 13:33:25 -0600778 return hazard;
779}
780
John Zulaufb02c1eb2020-10-06 16:33:36 -0600781struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700782 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600783 void operator()(ResourceAccessState *access) const {
784 assert(access);
785 access->ApplyBarriers(barriers, true);
786 }
787 const std::vector<SyncBarrier> &barriers;
788};
789
790struct ApplyTrackbackBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700791 explicit ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600792 void operator()(ResourceAccessState *access) const {
793 assert(access);
794 assert(!access->HasPendingState());
795 access->ApplyBarriers(barriers, false);
796 access->ApplyPendingBarriers(kCurrentCommandTag);
797 }
798 const std::vector<SyncBarrier> &barriers;
799};
800
801// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
802// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
803// *different* map from dest.
804// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
805// range [first, last)
806template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600807static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
808 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600809 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600810 auto at = entry;
811 for (auto pos = first; pos != last; ++pos) {
812 // Every member of the input iterator range must fit within the remaining portion of entry
813 assert(at->first.includes(pos->first));
814 assert(at != dest->end());
815 // Trim up at to the same size as the entry to resolve
816 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600817 auto access = pos->second; // intentional copy
818 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600819 at->second.Resolve(access);
820 ++at; // Go to the remaining unused section of entry
821 }
822}
823
John Zulaufa0a98292020-09-18 09:30:10 -0600824static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
825 SyncBarrier merged = {};
826 for (const auto &barrier : barriers) {
827 merged.Merge(barrier);
828 }
829 return merged;
830}
831
John Zulaufb02c1eb2020-10-06 16:33:36 -0600832template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700833void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600834 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
835 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600836 if (!range.non_empty()) return;
837
John Zulauf355e49b2020-04-24 15:11:15 -0600838 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
839 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600840 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600841 if (current->pos_B->valid) {
842 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600843 auto access = src_pos->second; // intentional copy
844 barrier_action(&access);
845
John Zulauf16adfc92020-04-08 10:28:33 -0600846 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600847 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
848 trimmed->second.Resolve(access);
849 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600850 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600851 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600852 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600853 }
John Zulauf16adfc92020-04-08 10:28:33 -0600854 } else {
855 // we have to descend to fill this gap
856 if (recur_to_infill) {
John Zulauf355e49b2020-04-24 15:11:15 -0600857 if (current->pos_A->valid) {
858 // Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation
859 ResourceAccessRangeMap gap_map;
John Zulauf3bcab5e2020-06-19 14:42:32 -0600860 ResolvePreviousAccess(type, current_range, &gap_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600861 ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -0600862 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600863 // There isn't anything in dest in current)range, so we can accumulate directly into it.
864 ResolvePreviousAccess(type, current_range, resolve_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600865 // Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current
866 for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) {
867 barrier_action(&pos->second);
John Zulauf355e49b2020-04-24 15:11:15 -0600868 }
869 }
870 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
871 // iterator of the outer while.
872
873 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
874 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
875 // we stepped on the dest map
locke-lunarg88dbb542020-06-23 22:05:42 -0600876 const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
877 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -0600878 current.seek(seek_to);
879 } else if (!current->pos_A->valid && infill_state) {
880 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
881 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
882 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -0600883 }
John Zulauf5f13a792020-03-10 07:31:21 -0600884 }
John Zulauf16adfc92020-04-08 10:28:33 -0600885 ++current;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600886 }
John Zulauf1a224292020-06-30 14:52:13 -0600887
888 // Infill if range goes passed both the current and resolve map prior contents
889 if (recur_to_infill && (current->range.end < range.end)) {
890 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
891 ResourceAccessRangeMap gap_map;
892 const auto the_end = resolve_map->end();
893 ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state);
894 for (auto &access : gap_map) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600895 barrier_action(&access.second);
John Zulauf1a224292020-06-30 14:52:13 -0600896 resolve_map->insert(the_end, access);
897 }
898 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600899}
900
John Zulauf43cc7462020-12-03 12:33:12 -0700901void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
902 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufe5da6e52020-03-18 15:32:18 -0600903 if ((prev_.size() == 0) && (src_external_.context == nullptr)) {
John Zulauf5f13a792020-03-10 07:31:21 -0600904 if (range.non_empty() && infill_state) {
905 descent_map->insert(std::make_pair(range, *infill_state));
906 }
907 } else {
908 // Look for something to fill the gap further along.
909 for (const auto &prev_dep : prev_) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600910 const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers);
911 prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600912 }
913
John Zulaufe5da6e52020-03-18 15:32:18 -0600914 if (src_external_.context) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600915 const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers);
916 src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600917 }
918 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600919}
920
John Zulauf4a6105a2020-11-17 15:11:05 -0700921// Non-lazy import of all accesses, WaitEvents needs this.
922void AccessContext::ResolvePreviousAccesses() {
923 ResourceAccessState default_state;
924 for (const auto address_type : kAddressTypes) {
925 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
926 }
927}
928
John Zulauf43cc7462020-12-03 12:33:12 -0700929AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
930 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -0600931}
932
John Zulauf1507ee42020-05-18 11:33:09 -0600933static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
934 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
935 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE;
936 return stage_access;
937}
938static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
939 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
940 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE;
941 return stage_access;
942}
943
John Zulauf7635de32020-05-29 17:14:15 -0600944// Caller must manage returned pointer
945static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
946 uint32_t subpass, const VkRect2D &render_area,
947 std::vector<const IMAGE_VIEW_STATE *> attachment_views) {
948 auto *proxy = new AccessContext(context);
949 proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulaufaff20662020-06-01 14:07:58 -0600950 proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulauf7635de32020-05-29 17:14:15 -0600951 return proxy;
952}
953
John Zulaufb02c1eb2020-10-06 16:33:36 -0600954template <typename BarrierAction>
John Zulauf52446eb2020-10-22 16:40:08 -0600955class ResolveAccessRangeFunctor {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600956 public:
John Zulauf43cc7462020-12-03 12:33:12 -0700957 ResolveAccessRangeFunctor(const AccessContext &context, AccessAddressType address_type, ResourceAccessRangeMap *descent_map,
958 const ResourceAccessState *infill_state, BarrierAction &barrier_action)
John Zulauf52446eb2020-10-22 16:40:08 -0600959 : context_(context),
960 address_type_(address_type),
961 descent_map_(descent_map),
962 infill_state_(infill_state),
963 barrier_action_(barrier_action) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600964 ResolveAccessRangeFunctor() = delete;
965 void operator()(const ResourceAccessRange &range) const {
966 context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_);
967 }
968
969 private:
John Zulauf52446eb2020-10-22 16:40:08 -0600970 const AccessContext &context_;
John Zulauf43cc7462020-12-03 12:33:12 -0700971 const AccessAddressType address_type_;
John Zulauf52446eb2020-10-22 16:40:08 -0600972 ResourceAccessRangeMap *const descent_map_;
973 const ResourceAccessState *infill_state_;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600974 BarrierAction &barrier_action_;
975};
976
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977template <typename BarrierAction>
978void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -0700979 BarrierAction &barrier_action, AccessAddressType address_type,
980 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600981 const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action);
982 ApplyOverImageRange(image_state, subresource_range, action);
John Zulauf62f10592020-04-03 12:20:02 -0600983}
984
John Zulauf7635de32020-05-29 17:14:15 -0600985// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulauffaea0ee2021-01-14 14:01:32 -0700986bool AccessContext::ValidateLayoutTransitions(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600987 const VkRect2D &render_area, uint32_t subpass,
988 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
989 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -0600990 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -0600991 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
992 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
993 // those affects have not been recorded yet.
994 //
995 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
996 // to apply and only copy then, if this proves a hot spot.
997 std::unique_ptr<AccessContext> proxy_for_prev;
998 TrackBack proxy_track_back;
999
John Zulauf355e49b2020-04-24 15:11:15 -06001000 const auto &transitions = rp_state.subpass_transitions[subpass];
1001 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001002 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1003
1004 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
1005 if (prev_needs_proxy) {
1006 if (!proxy_for_prev) {
1007 proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass,
1008 render_area, attachment_views));
1009 proxy_track_back = *track_back;
1010 proxy_track_back.context = proxy_for_prev.get();
1011 }
1012 track_back = &proxy_track_back;
1013 }
1014 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001015 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -07001016 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1017 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1018 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1019 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1020 string_VkImageLayout(transition.old_layout),
1021 string_VkImageLayout(transition.new_layout),
1022 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06001023 }
1024 }
1025 return skip;
1026}
1027
John Zulauffaea0ee2021-01-14 14:01:32 -07001028bool AccessContext::ValidateLoadOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001029 const VkRect2D &render_area, uint32_t subpass,
1030 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1031 const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001032 bool skip = false;
1033 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1034 VkExtent3D extent = CastTo3D(render_area.extent);
1035 VkOffset3D offset = CastTo3D(render_area.offset);
John Zulaufa0a98292020-09-18 09:30:10 -06001036
John Zulauf1507ee42020-05-18 11:33:09 -06001037 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1038 if (subpass == rp_state.attachment_first_subpass[i]) {
1039 if (attachment_views[i] == nullptr) continue;
1040 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1041 const IMAGE_STATE *image = view.image_state.get();
1042 if (image == nullptr) continue;
1043 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001044
1045 // Need check in the following way
1046 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1047 // vs. transition
1048 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1049 // for each aspect loaded.
1050
1051 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001052 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001053 const bool is_color = !(has_depth || has_stencil);
1054
1055 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001056 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001057
John Zulaufaff20662020-06-01 14:07:58 -06001058 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001059 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001060
John Zulaufb02c1eb2020-10-06 16:33:36 -06001061 auto hazard_range = view.normalized_subresource_range;
1062 bool checked_stencil = false;
1063 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001064 hazard = DetectHazard(*image, load_index, view.normalized_subresource_range, SyncOrdering::kColorAttachment, offset,
John Zulauf859089b2020-10-29 17:37:03 -06001065 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001066 aspect = "color";
1067 } else {
1068 if (has_depth) {
1069 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001070 hazard = DetectHazard(*image, load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset, extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001071 aspect = "depth";
1072 }
1073 if (!hazard.hazard && has_stencil) {
1074 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001075 hazard = DetectHazard(*image, stencil_load_index, hazard_range, SyncOrdering::kDepthStencilAttachment, offset,
1076 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001077 aspect = "stencil";
1078 checked_stencil = true;
1079 }
1080 }
1081
1082 if (hazard.hazard) {
1083 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001084 const auto &sync_state = cb_context.GetSyncState();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001085 if (hazard.tag == kCurrentCommandTag) {
1086 // Hazard vs. ILT
1087 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1088 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1089 " aspect %s during load with loadOp %s.",
1090 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1091 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06001092 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1093 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001094 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001095 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauffaea0ee2021-01-14 14:01:32 -07001096 cb_context.FormatUsage(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001097 }
1098 }
1099 }
1100 }
1101 return skip;
1102}
1103
John Zulaufaff20662020-06-01 14:07:58 -06001104// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1105// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1106// store is part of the same Next/End operation.
1107// The latter is handled in layout transistion validation directly
John Zulauffaea0ee2021-01-14 14:01:32 -07001108bool AccessContext::ValidateStoreOperation(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001109 const VkRect2D &render_area, uint32_t subpass,
1110 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1111 const char *func_name) const {
1112 bool skip = false;
1113 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1114 VkExtent3D extent = CastTo3D(render_area.extent);
1115 VkOffset3D offset = CastTo3D(render_area.offset);
1116
1117 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1118 if (subpass == rp_state.attachment_last_subpass[i]) {
1119 if (attachment_views[i] == nullptr) continue;
1120 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1121 const IMAGE_STATE *image = view.image_state.get();
1122 if (image == nullptr) continue;
1123 const auto &ci = attachment_ci[i];
1124
1125 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1126 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1127 // sake, we treat DONT_CARE as writing.
1128 const bool has_depth = FormatHasDepth(ci.format);
1129 const bool has_stencil = FormatHasStencil(ci.format);
1130 const bool is_color = !(has_depth || has_stencil);
1131 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1132 if (!has_stencil && !store_op_stores) continue;
1133
1134 HazardResult hazard;
1135 const char *aspect = nullptr;
1136 bool checked_stencil = false;
1137 if (is_color) {
1138 hazard = DetectHazard(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001139 view.normalized_subresource_range, SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001140 aspect = "color";
1141 } else {
1142 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1143 auto hazard_range = view.normalized_subresource_range;
1144 if (has_depth && store_op_stores) {
1145 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1146 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001147 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001148 aspect = "depth";
1149 }
1150 if (!hazard.hazard && has_stencil && stencil_op_stores) {
1151 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1152 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001153 SyncOrdering::kRaster, offset, extent);
John Zulaufaff20662020-06-01 14:07:58 -06001154 aspect = "stencil";
1155 checked_stencil = true;
1156 }
1157 }
1158
1159 if (hazard.hazard) {
1160 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1161 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauffaea0ee2021-01-14 14:01:32 -07001162 skip |= cb_context.GetSyncState().LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1163 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1164 " %s aspect during store with %s %s. Access info %s",
1165 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect,
1166 op_type_string, store_op_string, cb_context.FormatUsage(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001167 }
1168 }
1169 }
1170 return skip;
1171}
1172
John Zulauffaea0ee2021-01-14 14:01:32 -07001173bool AccessContext::ValidateResolveOperations(const CommandBufferAccessContext &cb_context, const RENDER_PASS_STATE &rp_state,
John Zulaufb027cdb2020-05-21 14:25:22 -06001174 const VkRect2D &render_area,
1175 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name,
1176 uint32_t subpass) const {
John Zulauffaea0ee2021-01-14 14:01:32 -07001177 ValidateResolveAction validate_action(rp_state.renderPass, subpass, *this, cb_context, func_name);
John Zulauf7635de32020-05-29 17:14:15 -06001178 ResolveOperation(validate_action, rp_state, render_area, attachment_views, subpass);
1179 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001180}
1181
John Zulauf3d84f1b2020-03-09 13:33:25 -06001182class HazardDetector {
1183 SyncStageAccessIndex usage_index_;
1184
1185 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001186 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001187 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1188 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001189 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001190 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001191};
1192
John Zulauf69133422020-05-20 14:55:53 -06001193class HazardDetectorWithOrdering {
1194 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001195 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001196
1197 public:
1198 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001199 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001200 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001201 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1202 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001203 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001204 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001205};
1206
John Zulauf16adfc92020-04-08 10:28:33 -06001207HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001208 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001209 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001210 const auto base_address = ResourceBaseAddress(buffer);
1211 HazardDetector detector(usage_index);
1212 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001213}
1214
John Zulauf69133422020-05-20 14:55:53 -06001215template <typename Detector>
1216HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1217 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1218 const VkExtent3D &extent, DetectOptions options) const {
1219 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001220 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001221 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1222 base_address);
1223 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001224 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001225 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001226 if (hazard.hazard) return hazard;
1227 }
1228 return HazardResult();
1229}
1230
John Zulauf540266b2020-04-06 18:54:53 -06001231HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1232 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1233 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001234 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1235 subresource.layerCount};
John Zulauf1507ee42020-05-18 11:33:09 -06001236 return DetectHazard(image, current_usage, subresource_range, offset, extent);
1237}
1238
1239HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1240 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1241 const VkExtent3D &extent) const {
John Zulauf69133422020-05-20 14:55:53 -06001242 HazardDetector detector(current_usage);
1243 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
1244}
1245
1246HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001247 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
John Zulauf69133422020-05-20 14:55:53 -06001248 const VkOffset3D &offset, const VkExtent3D &extent) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001249 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06001250 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001251}
1252
John Zulaufb027cdb2020-05-21 14:25:22 -06001253// Some common code for looking at attachments, if there's anything wrong, we return no hazard, core validation
1254// should have reported the issue regarding an invalid attachment entry
1255HazardResult AccessContext::DetectHazard(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001256 SyncOrdering ordering_rule, const VkOffset3D &offset, const VkExtent3D &extent,
John Zulaufb027cdb2020-05-21 14:25:22 -06001257 VkImageAspectFlags aspect_mask) const {
1258 if (view != nullptr) {
1259 const IMAGE_STATE *image = view->image_state.get();
1260 if (image != nullptr) {
1261 auto *detect_range = &view->normalized_subresource_range;
1262 VkImageSubresourceRange masked_range;
1263 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1264 masked_range = view->normalized_subresource_range;
1265 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1266 detect_range = &masked_range;
1267 }
1268
1269 // NOTE: The range encoding code is not robust to invalid ranges, so we protect it from our change
1270 if (detect_range->aspectMask) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001271 return DetectHazard(*image, current_usage, *detect_range, ordering_rule, offset, extent);
John Zulaufb027cdb2020-05-21 14:25:22 -06001272 }
1273 }
1274 }
1275 return HazardResult();
1276}
John Zulauf43cc7462020-12-03 12:33:12 -07001277
John Zulauf3d84f1b2020-03-09 13:33:25 -06001278class BarrierHazardDetector {
1279 public:
1280 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1281 SyncStageAccessFlags src_access_scope)
1282 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1283
John Zulauf5f13a792020-03-10 07:31:21 -06001284 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1285 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001286 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001287 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001288 // 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 -07001289 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001290 }
1291
1292 private:
1293 SyncStageAccessIndex usage_index_;
1294 VkPipelineStageFlags src_exec_scope_;
1295 SyncStageAccessFlags src_access_scope_;
1296};
1297
John Zulauf4a6105a2020-11-17 15:11:05 -07001298class EventBarrierHazardDetector {
1299 public:
1300 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1301 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
1302 const ResourceUsageTag &scope_tag)
1303 : usage_index_(usage_index),
1304 src_exec_scope_(src_exec_scope),
1305 src_access_scope_(src_access_scope),
1306 event_scope_(event_scope),
1307 scope_pos_(event_scope.cbegin()),
1308 scope_end_(event_scope.cend()),
1309 scope_tag_(scope_tag) {}
1310
1311 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1312 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1313 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1314 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1315 if (scope_pos_ == scope_end_) return HazardResult();
1316 if (!scope_pos_->first.intersects(pos->first)) {
1317 event_scope_.lower_bound(pos->first);
1318 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1319 }
1320
1321 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1322 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1323 }
1324 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1325 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1326 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1327 }
1328
1329 private:
1330 SyncStageAccessIndex usage_index_;
1331 VkPipelineStageFlags src_exec_scope_;
1332 SyncStageAccessFlags src_access_scope_;
1333 const SyncEventState::ScopeMap &event_scope_;
1334 SyncEventState::ScopeMap::const_iterator scope_pos_;
1335 SyncEventState::ScopeMap::const_iterator scope_end_;
1336 const ResourceUsageTag &scope_tag_;
1337};
1338
1339HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
1340 const SyncStageAccessFlags &src_access_scope,
1341 const VkImageSubresourceRange &subresource_range,
1342 const SyncEventState &sync_event, DetectOptions options) const {
1343 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1344 // first access scope map to use, and there's no easy way to plumb it in below.
1345 const auto address_type = ImageAddressType(image);
1346 const auto &event_scope = sync_event.FirstScope(address_type);
1347
1348 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1349 event_scope, sync_event.first_scope_tag);
1350 VkOffset3D zero_offset = {0, 0, 0};
1351 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
1352}
1353
John Zulauf16adfc92020-04-08 10:28:33 -06001354HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001355 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001356 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001357 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001358 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
1359 VkOffset3D zero_offset = {0, 0, 0};
1360 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001361}
1362
John Zulauf355e49b2020-04-24 15:11:15 -06001363HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001364 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001365 const VkImageMemoryBarrier &barrier) const {
1366 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1367 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1368 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1369}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001370HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
1371 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope,
John Zulaufd5115702021-01-18 12:34:33 -07001372 image_barrier.barrier.src_access_scope, image_barrier.range.subresource_range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001373}
John Zulauf355e49b2020-04-24 15:11:15 -06001374
John Zulauf9cb530d2019-09-30 14:14:10 -06001375template <typename Flags, typename Map>
1376SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1377 SyncStageAccessFlags scope = 0;
1378 for (const auto &bit_scope : map) {
1379 if (flag_mask < bit_scope.first) break;
1380
1381 if (flag_mask & bit_scope.first) {
1382 scope |= bit_scope.second;
1383 }
1384 }
1385 return scope;
1386}
1387
1388SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags stages) {
1389 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1390}
1391
1392SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags accesses) {
1393 return AccessScopeImpl(accesses, syncStageAccessMaskByAccessBit);
1394}
1395
1396// Getting from stage mask and access mask to stage/acess masks is something we need to be good at...
1397SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags stages, VkAccessFlags accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001398 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1399 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1400 // 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 -06001401 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1402}
1403
1404template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001405void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001406 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1407 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001408 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001409 auto pos = accesses->lower_bound(range);
1410 if (pos == accesses->end() || !pos->first.intersects(range)) {
1411 // The range is empty, fill it with a default value.
1412 pos = action.Infill(accesses, pos, range);
1413 } else if (range.begin < pos->first.begin) {
1414 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001415 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001416 } else if (pos->first.begin < range.begin) {
1417 // Trim the beginning if needed
1418 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1419 ++pos;
1420 }
1421
1422 const auto the_end = accesses->end();
1423 while ((pos != the_end) && pos->first.intersects(range)) {
1424 if (pos->first.end > range.end) {
1425 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1426 }
1427
1428 pos = action(accesses, pos);
1429 if (pos == the_end) break;
1430
1431 auto next = pos;
1432 ++next;
1433 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1434 // Need to infill if next is disjoint
1435 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001436 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001437 next = action.Infill(accesses, next, new_range);
1438 }
1439 pos = next;
1440 }
1441}
John Zulaufd5115702021-01-18 12:34:33 -07001442
1443// Give a comparable interface for range generators and ranges
1444template <typename Action>
1445inline void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
1446 assert(range);
1447 UpdateMemoryAccessState(accesses, *range, action);
1448}
1449
John Zulauf4a6105a2020-11-17 15:11:05 -07001450template <typename Action, typename RangeGen>
1451void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1452 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001453 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 -07001454 for (; range_gen->non_empty(); ++range_gen) {
1455 UpdateMemoryAccessState(accesses, *range_gen, action);
1456 }
1457}
John Zulauf9cb530d2019-09-30 14:14:10 -06001458
1459struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001460 using Iterator = ResourceAccessRangeMap::iterator;
1461 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001462 // this is only called on gaps, and never returns a gap.
1463 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001464 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001465 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001466 }
John Zulauf5f13a792020-03-10 07:31:21 -06001467
John Zulauf5c5e88d2019-12-26 11:22:02 -07001468 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001469 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001470 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001471 return pos;
1472 }
1473
John Zulauf43cc7462020-12-03 12:33:12 -07001474 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001475 SyncOrdering ordering_rule_, const ResourceUsageTag &tag_)
1476 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001477 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001478 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001479 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001480 const SyncOrdering ordering_rule;
John Zulauf9cb530d2019-09-30 14:14:10 -06001481 const ResourceUsageTag &tag;
1482};
1483
John Zulauf4a6105a2020-11-17 15:11:05 -07001484// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001485struct PipelineBarrierOp {
1486 SyncBarrier barrier;
1487 bool layout_transition;
1488 PipelineBarrierOp(const SyncBarrier &barrier_, bool layout_transition_)
1489 : barrier(barrier_), layout_transition(layout_transition_) {}
1490 PipelineBarrierOp() = default;
John Zulaufd5115702021-01-18 12:34:33 -07001491 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf1e331ec2020-12-04 18:29:38 -07001492 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(barrier, layout_transition); }
1493};
John Zulauf4a6105a2020-11-17 15:11:05 -07001494// The barrier operation for wait events
1495struct WaitEventBarrierOp {
1496 const ResourceUsageTag *scope_tag;
1497 SyncBarrier barrier;
1498 bool layout_transition;
1499 WaitEventBarrierOp(const ResourceUsageTag &scope_tag_, const SyncBarrier &barrier_, bool layout_transition_)
1500 : scope_tag(&scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1501 WaitEventBarrierOp() = default;
1502 void operator()(ResourceAccessState *access_state) const {
1503 assert(scope_tag); // Not valid to have a non-scope op executed, default construct included for std::vector support
1504 access_state->ApplyBarrier(*scope_tag, barrier, layout_transition);
1505 }
1506};
John Zulauf1e331ec2020-12-04 18:29:38 -07001507
John Zulauf4a6105a2020-11-17 15:11:05 -07001508// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1509// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1510// of a collection is known/present.
John Zulauf1e331ec2020-12-04 18:29:38 -07001511template <typename BarrierOp>
John Zulauf89311b42020-09-29 16:28:47 -06001512class ApplyBarrierOpsFunctor {
1513 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001514 using Iterator = ResourceAccessRangeMap::iterator;
1515 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
John Zulauf9cb530d2019-09-30 14:14:10 -06001516
John Zulauf5c5e88d2019-12-26 11:22:02 -07001517 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001518 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001519 for (const auto &op : barrier_ops_) {
1520 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001521 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001522
John Zulauf89311b42020-09-29 16:28:47 -06001523 if (resolve_) {
1524 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1525 // another walk
1526 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001527 }
1528 return pos;
1529 }
1530
John Zulauf89311b42020-09-29 16:28:47 -06001531 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulaufd5115702021-01-18 12:34:33 -07001532 ApplyBarrierOpsFunctor(bool resolve, size_t size_hint, const ResourceUsageTag &tag)
1533 : resolve_(resolve), barrier_ops_(), tag_(tag) {
1534 barrier_ops_.reserve(size_hint);
1535 }
1536 void EmplaceBack(const BarrierOp &op) { barrier_ops_.emplace_back(op); }
John Zulauf89311b42020-09-29 16:28:47 -06001537
1538 private:
1539 bool resolve_;
John Zulaufd5115702021-01-18 12:34:33 -07001540 std::vector<BarrierOp> barrier_ops_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001541 const ResourceUsageTag &tag_;
1542};
1543
John Zulauf4a6105a2020-11-17 15:11:05 -07001544// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1545// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1546template <typename BarrierOp>
1547class ApplyBarrierFunctor {
1548 public:
1549 using Iterator = ResourceAccessRangeMap::iterator;
1550 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1551
1552 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1553 auto &access_state = pos->second;
1554 barrier_op_(&access_state);
1555 return pos;
1556 }
1557
1558 ApplyBarrierFunctor(const BarrierOp &barrier_op) : barrier_op_(barrier_op) {}
1559
1560 private:
John Zulaufd5115702021-01-18 12:34:33 -07001561 BarrierOp barrier_op_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001562};
1563
John Zulauf1e331ec2020-12-04 18:29:38 -07001564// This functor resolves the pendinging state.
1565class ResolvePendingBarrierFunctor {
1566 public:
1567 using Iterator = ResourceAccessRangeMap::iterator;
1568 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1569
1570 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1571 auto &access_state = pos->second;
1572 access_state.ApplyPendingBarriers(tag_);
1573 return pos;
1574 }
1575
1576 ResolvePendingBarrierFunctor(const ResourceUsageTag &tag) : tag_(tag) {}
1577
1578 private:
John Zulauf89311b42020-09-29 16:28:47 -06001579 const ResourceUsageTag &tag_;
John Zulauf9cb530d2019-09-30 14:14:10 -06001580};
1581
John Zulauf8e3c3e92021-01-06 11:19:36 -07001582void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1583 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
1584 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001585 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001586}
1587
John Zulauf8e3c3e92021-01-06 11:19:36 -07001588void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001589 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001590 if (!SimpleBinding(buffer)) return;
1591 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001592 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001593}
John Zulauf355e49b2020-04-24 15:11:15 -06001594
John Zulauf8e3c3e92021-01-06 11:19:36 -07001595void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001596 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf540266b2020-04-06 18:54:53 -06001597 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001598 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001599 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001600 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1601 base_address);
1602 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001603 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf5f13a792020-03-10 07:31:21 -06001604 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001605 UpdateMemoryAccessState(&GetAccessStateMap(address_type), *range_gen, action);
John Zulauf5f13a792020-03-10 07:31:21 -06001606 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001607}
John Zulauf8e3c3e92021-01-06 11:19:36 -07001608void AccessContext::UpdateAccessState(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
1609 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask,
1610 const ResourceUsageTag &tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001611 if (view != nullptr) {
1612 const IMAGE_STATE *image = view->image_state.get();
1613 if (image != nullptr) {
1614 auto *update_range = &view->normalized_subresource_range;
1615 VkImageSubresourceRange masked_range;
1616 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1617 masked_range = view->normalized_subresource_range;
1618 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1619 update_range = &masked_range;
1620 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001621 UpdateAccessState(*image, current_usage, ordering_rule, *update_range, offset, extent, tag);
John Zulauf7635de32020-05-29 17:14:15 -06001622 }
1623 }
1624}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001625
John Zulauf8e3c3e92021-01-06 11:19:36 -07001626void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001627 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1628 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001629 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1630 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001631 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001632}
1633
John Zulauf540266b2020-04-06 18:54:53 -06001634template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001635void AccessContext::UpdateResourceAccess(const BUFFER_STATE &buffer, const ResourceAccessRange &range, const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001636 if (!SimpleBinding(buffer)) return;
1637 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf43cc7462020-12-03 12:33:12 -07001638 UpdateMemoryAccessState(&GetAccessStateMap(AccessAddressType::kLinear), (range + base_address), action);
John Zulauf540266b2020-04-06 18:54:53 -06001639}
1640
1641template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001642void AccessContext::UpdateResourceAccess(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1643 const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001644 if (!SimpleBinding(image)) return;
1645 const auto address_type = ImageAddressType(image);
1646 auto *accesses = &GetAccessStateMap(address_type);
John Zulauf540266b2020-04-06 18:54:53 -06001647
John Zulauf16adfc92020-04-08 10:28:33 -06001648 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001649 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, {0, 0, 0},
1650 image.createInfo.extent, base_address);
1651
John Zulauf540266b2020-04-06 18:54:53 -06001652 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001653 UpdateMemoryAccessState(accesses, *range_gen, action);
John Zulauf540266b2020-04-06 18:54:53 -06001654 }
1655}
1656
John Zulauf7635de32020-05-29 17:14:15 -06001657void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1658 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1659 const ResourceUsageTag &tag) {
1660 UpdateStateResolveAction update(*this, tag);
1661 ResolveOperation(update, rp_state, render_area, attachment_views, subpass);
1662}
1663
John Zulaufaff20662020-06-01 14:07:58 -06001664void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1665 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1666 const ResourceUsageTag &tag) {
1667 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1668 VkExtent3D extent = CastTo3D(render_area.extent);
1669 VkOffset3D offset = CastTo3D(render_area.offset);
1670
1671 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1672 if (rp_state.attachment_last_subpass[i] == subpass) {
1673 if (attachment_views[i] == nullptr) continue; // UNUSED
1674 const auto &view = *attachment_views[i];
1675 const IMAGE_STATE *image = view.image_state.get();
1676 if (image == nullptr) continue;
1677
1678 const auto &ci = attachment_ci[i];
1679 const bool has_depth = FormatHasDepth(ci.format);
1680 const bool has_stencil = FormatHasStencil(ci.format);
1681 const bool is_color = !(has_depth || has_stencil);
1682 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1683
1684 if (is_color && store_op_stores) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001685 UpdateAccessState(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1686 view.normalized_subresource_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001687 } else {
1688 auto update_range = view.normalized_subresource_range;
1689 if (has_depth && store_op_stores) {
1690 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001691 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1692 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001693 }
1694 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1695 if (has_stencil && stencil_op_stores) {
1696 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001697 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster,
1698 update_range, offset, extent, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001699 }
1700 }
1701 }
1702 }
1703}
1704
John Zulauf540266b2020-04-06 18:54:53 -06001705template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001706void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001707 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001708 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001709 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001710 }
1711}
1712
1713void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001714 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1715 auto &context = contexts[subpass_index];
John Zulaufb02c1eb2020-10-06 16:33:36 -06001716 ApplyTrackbackBarriersAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001717 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001718 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001719 }
1720 }
1721}
1722
John Zulauf355e49b2020-04-24 15:11:15 -06001723// Suitable only for *subpass* access contexts
John Zulauf7635de32020-05-29 17:14:15 -06001724HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const IMAGE_VIEW_STATE *attach_view) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001725 if (!attach_view) return HazardResult();
1726 const auto image_state = attach_view->image_state.get();
1727 if (!image_state) return HazardResult();
1728
John Zulauf355e49b2020-04-24 15:11:15 -06001729 // We should never ask for a transition from a context we don't have
John Zulauf7635de32020-05-29 17:14:15 -06001730 assert(track_back.context);
John Zulauf355e49b2020-04-24 15:11:15 -06001731
1732 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001733 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1734 const auto merged_barrier = MergeBarriers(track_back.barriers);
1735 HazardResult hazard =
1736 track_back.context->DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
1737 attach_view->normalized_subresource_range, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001738 if (!hazard.hazard) {
1739 // The Async hazard check is against the current context's async set.
John Zulaufa0a98292020-09-18 09:30:10 -06001740 hazard = DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001741 attach_view->normalized_subresource_range, kDetectAsync);
1742 }
John Zulaufa0a98292020-09-18 09:30:10 -06001743
John Zulauf355e49b2020-04-24 15:11:15 -06001744 return hazard;
1745}
1746
John Zulaufb02c1eb2020-10-06 16:33:36 -06001747void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
1748 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1749 const ResourceUsageTag &tag) {
1750 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001751 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001752 for (const auto &transition : transitions) {
1753 const auto prev_pass = transition.prev_pass;
1754 const auto attachment_view = attachment_views[transition.attachment];
1755 if (!attachment_view) continue;
1756 const auto *image = attachment_view->image_state.get();
1757 if (!image) continue;
1758 if (!SimpleBinding(*image)) continue;
1759
1760 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1761 assert(trackback);
1762
1763 // Import the attachments into the current context
1764 const auto *prev_context = trackback->context;
1765 assert(prev_context);
1766 const auto address_type = ImageAddressType(*image);
1767 auto &target_map = GetAccessStateMap(address_type);
1768 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
1769 prev_context->ResolveAccessRange(*image, attachment_view->normalized_subresource_range, barrier_action, address_type,
John Zulauf646cc292020-10-23 09:16:45 -06001770 &target_map, &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001771 }
1772
John Zulauf86356ca2020-10-19 11:46:41 -06001773 // If there were no transitions skip this global map walk
1774 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001775 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001776 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001777 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001778}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001779
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001780void CommandBufferAccessContext::ApplyGlobalBarriersToEvents(const SyncExecScope &src, const SyncExecScope &dst) {
1781 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
John Zulauf4a6105a2020-11-17 15:11:05 -07001782 for (auto &event_pair : event_state_) {
1783 assert(event_pair.second); // Shouldn't be storing empty
1784 auto &sync_event = *event_pair.second;
1785 // 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 -07001786 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
1787 sync_event.barriers |= dst.exec_scope;
1788 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
John Zulauf4a6105a2020-11-17 15:11:05 -07001789 }
1790 }
1791}
1792
John Zulauf355e49b2020-04-24 15:11:15 -06001793// Class CommandBufferAccessContext: Keep track of resource access state information for a specific command buffer
1794bool CommandBufferAccessContext::ValidateBeginRenderPass(const RENDER_PASS_STATE &rp_state,
1795
1796 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001797 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001798 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
1799 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06001800
John Zulauf86356ca2020-10-19 11:46:41 -06001801 assert(pRenderPassBegin);
1802 if (nullptr == pRenderPassBegin) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06001803
John Zulauf86356ca2020-10-19 11:46:41 -06001804 const uint32_t subpass = 0;
John Zulauf355e49b2020-04-24 15:11:15 -06001805
John Zulauf86356ca2020-10-19 11:46:41 -06001806 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
1807 // hasn't happened yet)
1808 const std::vector<AccessContext> empty_context_vector;
1809 AccessContext temp_context(subpass, queue_flags_, rp_state.subpass_dependencies, empty_context_vector,
1810 const_cast<AccessContext *>(&cb_access_context_));
John Zulauf355e49b2020-04-24 15:11:15 -06001811
John Zulauf86356ca2020-10-19 11:46:41 -06001812 // Create a view list
1813 const auto fb_state = sync_state_->Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
1814 assert(fb_state);
1815 if (nullptr == fb_state) return skip;
1816 // NOTE: Must not use COMMAND_BUFFER_STATE variant of this as RecordCmdBeginRenderPass hasn't run and thus
1817 // the activeRenderPass.* fields haven't been set.
1818 const auto views = sync_state_->GetAttachmentViews(*pRenderPassBegin, *fb_state);
1819
1820 // Validate transitions
John Zulauffaea0ee2021-01-14 14:01:32 -07001821 skip |= temp_context.ValidateLayoutTransitions(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf86356ca2020-10-19 11:46:41 -06001822
1823 // Validate load operations if there were no layout transition hazards
1824 if (!skip) {
1825 temp_context.RecordLayoutTransitions(rp_state, subpass, views, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07001826 skip |= temp_context.ValidateLoadOperation(*this, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06001827 }
John Zulauf86356ca2020-10-19 11:46:41 -06001828
John Zulauf355e49b2020-04-24 15:11:15 -06001829 return skip;
1830}
1831
locke-lunarg61870c22020-06-09 14:51:50 -06001832bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1833 const char *func_name) const {
1834 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001835 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001836 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001837 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1838 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001839 return skip;
1840 }
1841
1842 using DescriptorClass = cvdescriptorset::DescriptorClass;
1843 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1844 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1845 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1846 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1847
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001848 for (const auto &stage_state : pipe->stage_state) {
1849 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1850 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001851 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001852 }
locke-lunarg61870c22020-06-09 14:51:50 -06001853 for (const auto &set_binding : stage_state.descriptor_uses) {
1854 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1855 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1856 set_binding.first.second);
1857 const auto descriptor_type = binding_it.GetType();
1858 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1859 auto array_idx = 0;
1860
1861 if (binding_it.IsVariableDescriptorCount()) {
1862 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1863 }
1864 SyncStageAccessIndex sync_index =
1865 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1866
1867 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1868 uint32_t index = i - index_range.start;
1869 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1870 switch (descriptor->GetClass()) {
1871 case DescriptorClass::ImageSampler:
1872 case DescriptorClass::Image: {
1873 const IMAGE_VIEW_STATE *img_view_state = nullptr;
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001874 VkImageLayout image_layout;
locke-lunarg61870c22020-06-09 14:51:50 -06001875 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001876 const auto image_sampler_descriptor = static_cast<const ImageSamplerDescriptor *>(descriptor);
1877 img_view_state = image_sampler_descriptor->GetImageViewState();
1878 image_layout = image_sampler_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001879 } else {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001880 const auto image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1881 img_view_state = image_descriptor->GetImageViewState();
1882 image_layout = image_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001883 }
1884 if (!img_view_state) continue;
1885 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1886 VkExtent3D extent = {};
1887 VkOffset3D offset = {};
1888 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1889 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1890 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1891 } else {
1892 extent = img_state->createInfo.extent;
1893 }
John Zulauf361fb532020-07-22 10:45:39 -06001894 HazardResult hazard;
1895 const auto &subresource_range = img_view_state->normalized_subresource_range;
1896 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
1897 // Input attachments are subject to raster ordering rules
1898 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001899 SyncOrdering::kRaster, offset, extent);
John Zulauf361fb532020-07-22 10:45:39 -06001900 } else {
1901 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, offset, extent);
1902 }
John Zulauf33fc1d52020-07-17 11:01:10 -06001903 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001904 skip |= sync_state_->LogError(
1905 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001906 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1907 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001908 func_name, string_SyncHazard(hazard.hazard),
1909 sync_state_->report_data->FormatHandle(img_view_state->image_view).c_str(),
1910 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001911 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001912 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1913 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauffaea0ee2021-01-14 14:01:32 -07001914 set_binding.first.second, index, FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001915 }
1916 break;
1917 }
1918 case DescriptorClass::TexelBuffer: {
1919 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1920 if (!buf_view_state) continue;
1921 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06001922 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06001923 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06001924 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001925 skip |= sync_state_->LogError(
1926 buf_view_state->buffer_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001927 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1928 func_name, string_SyncHazard(hazard.hazard),
locke-lunarg88dbb542020-06-23 22:05:42 -06001929 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view).c_str(),
1930 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001931 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001932 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1933 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001934 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001935 }
1936 break;
1937 }
1938 case DescriptorClass::GeneralBuffer: {
1939 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
1940 auto buf_state = buffer_descriptor->GetBufferState();
1941 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06001942 const ResourceAccessRange range =
1943 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06001944 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06001945 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001946 skip |= sync_state_->LogError(
1947 buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001948 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1949 func_name, string_SyncHazard(hazard.hazard),
1950 sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
locke-lunarg88dbb542020-06-23 22:05:42 -06001951 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001952 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001953 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1954 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
John Zulauffaea0ee2021-01-14 14:01:32 -07001955 FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001956 }
1957 break;
1958 }
1959 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
1960 default:
1961 break;
1962 }
1963 }
1964 }
1965 }
1966 return skip;
1967}
1968
1969void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1970 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001971 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001972 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001973 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1974 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001975 return;
1976 }
1977
1978 using DescriptorClass = cvdescriptorset::DescriptorClass;
1979 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1980 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1981 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1982 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1983
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001984 for (const auto &stage_state : pipe->stage_state) {
1985 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1986 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001987 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001988 }
locke-lunarg61870c22020-06-09 14:51:50 -06001989 for (const auto &set_binding : stage_state.descriptor_uses) {
1990 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1991 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1992 set_binding.first.second);
1993 const auto descriptor_type = binding_it.GetType();
1994 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1995 auto array_idx = 0;
1996
1997 if (binding_it.IsVariableDescriptorCount()) {
1998 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1999 }
2000 SyncStageAccessIndex sync_index =
2001 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2002
2003 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2004 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2005 switch (descriptor->GetClass()) {
2006 case DescriptorClass::ImageSampler:
2007 case DescriptorClass::Image: {
2008 const IMAGE_VIEW_STATE *img_view_state = nullptr;
2009 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
2010 img_view_state = static_cast<const ImageSamplerDescriptor *>(descriptor)->GetImageViewState();
2011 } else {
2012 img_view_state = static_cast<const ImageDescriptor *>(descriptor)->GetImageViewState();
2013 }
2014 if (!img_view_state) continue;
2015 const IMAGE_STATE *img_state = img_view_state->image_state.get();
2016 VkExtent3D extent = {};
2017 VkOffset3D offset = {};
2018 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2019 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2020 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2021 } else {
2022 extent = img_state->createInfo.extent;
2023 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07002024 SyncOrdering ordering_rule = (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)
2025 ? SyncOrdering::kRaster
2026 : SyncOrdering::kNonAttachment;
2027 current_context_->UpdateAccessState(*img_state, sync_index, ordering_rule,
2028 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002029 break;
2030 }
2031 case DescriptorClass::TexelBuffer: {
2032 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
2033 if (!buf_view_state) continue;
2034 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002035 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002036 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002037 break;
2038 }
2039 case DescriptorClass::GeneralBuffer: {
2040 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
2041 auto buf_state = buffer_descriptor->GetBufferState();
2042 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06002043 const ResourceAccessRange range =
2044 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002045 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002046 break;
2047 }
2048 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2049 default:
2050 break;
2051 }
2052 }
2053 }
2054 }
2055}
2056
2057bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2058 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002059 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2060 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002061 return skip;
2062 }
2063
2064 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2065 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002066 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002067
2068 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002069 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002070 if (binding_description.binding < binding_buffers_size) {
2071 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002072 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002073
locke-lunarg1ae57d62020-11-18 10:49:19 -07002074 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002075 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2076 vertexCount, binding_description.stride);
locke-lunarg61870c22020-06-09 14:51:50 -06002077 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range);
2078 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002079 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002080 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 -06002081 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002082 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002083 }
2084 }
2085 }
2086 return skip;
2087}
2088
2089void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002090 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2091 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002092 return;
2093 }
2094 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2095 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002096 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002097
2098 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002099 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002100 if (binding_description.binding < binding_buffers_size) {
2101 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002102 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002103
locke-lunarg1ae57d62020-11-18 10:49:19 -07002104 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002105 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2106 vertexCount, binding_description.stride);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002107 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, SyncOrdering::kNonAttachment,
2108 range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002109 }
2110 }
2111}
2112
2113bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2114 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002115 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->destroyed) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002116 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002117 }
locke-lunarg61870c22020-06-09 14:51:50 -06002118
locke-lunarg1ae57d62020-11-18 10:49:19 -07002119 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002120 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002121 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2122 firstIndex, indexCount, index_size);
locke-lunarg61870c22020-06-09 14:51:50 -06002123 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range);
2124 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002125 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002126 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 -06002127 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07002128 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002129 }
2130
2131 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2132 // We will detect more accurate range in the future.
2133 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2134 return skip;
2135}
2136
2137void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag &tag) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002138 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 -06002139
locke-lunarg1ae57d62020-11-18 10:49:19 -07002140 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002141 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002142 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2143 firstIndex, indexCount, index_size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002144 current_context_->UpdateAccessState(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002145
2146 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2147 // We will detect more accurate range in the future.
2148 RecordDrawVertex(UINT32_MAX, 0, tag);
2149}
2150
2151bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002152 bool skip = false;
2153 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002154 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(*this, *cb_state_.get(),
locke-lunarg7077d502020-06-18 21:37:26 -06002155 cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
2156 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002157}
2158
2159void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002160 if (current_renderpass_context_) {
locke-lunarg7077d502020-06-18 21:37:26 -06002161 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea,
2162 tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002163 }
locke-lunarg61870c22020-06-09 14:51:50 -06002164}
2165
John Zulauf355e49b2020-04-24 15:11:15 -06002166bool CommandBufferAccessContext::ValidateNextSubpass(const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002167 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002168 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002169 skip |= current_renderpass_context_->ValidateNextSubpass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002170
2171 return skip;
2172}
2173
2174bool CommandBufferAccessContext::ValidateEndRenderpass(const char *func_name) const {
2175 // TODO: Things to add here.
John Zulauf7635de32020-05-29 17:14:15 -06002176 // Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002177 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002178 if (!current_renderpass_context_) return skip;
John Zulauffaea0ee2021-01-14 14:01:32 -07002179 skip |= current_renderpass_context_->ValidateEndRenderPass(*this, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002180
2181 return skip;
2182}
2183
2184void CommandBufferAccessContext::RecordBeginRenderPass(const ResourceUsageTag &tag) {
2185 assert(sync_state_);
2186 if (!cb_state_) return;
2187
2188 // Create an access context the current renderpass.
John Zulauf1a224292020-06-30 14:52:13 -06002189 render_pass_contexts_.emplace_back();
John Zulauf16adfc92020-04-08 10:28:33 -06002190 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf1a224292020-06-30 14:52:13 -06002191 current_renderpass_context_->RecordBeginRenderPass(*sync_state_, *cb_state_, &cb_access_context_, queue_flags_, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002192 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf16adfc92020-04-08 10:28:33 -06002193}
2194
John Zulauffaea0ee2021-01-14 14:01:32 -07002195void CommandBufferAccessContext::RecordNextSubpass(const RENDER_PASS_STATE &rp_state, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002196 assert(current_renderpass_context_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002197 auto prev_tag = NextCommandTag(command);
2198 auto next_tag = NextSubcommandTag(command);
2199 current_renderpass_context_->RecordNextSubpass(cb_state_->activeRenderPassBeginInfo.renderArea, prev_tag, next_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002200 current_context_ = &current_renderpass_context_->CurrentContext();
2201}
2202
John Zulauffaea0ee2021-01-14 14:01:32 -07002203void CommandBufferAccessContext::RecordEndRenderPass(const RENDER_PASS_STATE &render_pass, CMD_TYPE command) {
John Zulauf16adfc92020-04-08 10:28:33 -06002204 assert(current_renderpass_context_);
2205 if (!current_renderpass_context_) return;
2206
John Zulauffaea0ee2021-01-14 14:01:32 -07002207 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, cb_state_->activeRenderPassBeginInfo.renderArea,
2208 NextCommandTag(command));
John Zulauf355e49b2020-04-24 15:11:15 -06002209 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002210 current_renderpass_context_ = nullptr;
2211}
2212
John Zulauf49beb112020-11-04 16:06:31 -07002213bool CommandBufferAccessContext::ValidateSetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2214 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002215 // I'll put this here just in case we need to pass this in for future extension support
2216 const auto cmd = CMD_SETEVENT;
2217 bool skip = false;
2218 const auto *sync_event = GetEventState(event);
2219 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2220
2221 const char *const reset_set =
2222 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2223 "hazards.";
2224 const char *const wait =
2225 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
2226
2227 const auto exec_scope = WithEarlierPipelineStages(ExpandPipelineStages(GetQueueFlags(), stageMask));
2228 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2229 const char *vuid = nullptr;
2230 const char *message = nullptr;
2231 switch (sync_event->last_command) {
2232 case CMD_RESETEVENT:
2233 // Needs a barrier between reset and set
2234 vuid = "SYNC-vkCmdSetEvent-missingbarrier-reset";
2235 message = reset_set;
2236 break;
2237 case CMD_SETEVENT:
2238 // Needs a barrier between set and set
2239 vuid = "SYNC-vkCmdSetEvent-missingbarrier-set";
2240 message = reset_set;
2241 break;
2242 case CMD_WAITEVENTS:
2243 // Needs a barrier or is in second execution scope
2244 vuid = "SYNC-vkCmdSetEvent-missingbarrier-wait";
2245 message = wait;
2246 break;
2247 default:
2248 // The only other valid last command that wasn't one.
2249 assert(sync_event->last_command == CMD_NONE);
2250 break;
2251 }
2252 if (vuid) {
2253 assert(nullptr != message);
2254 const char *const cmd_name = CommandTypeString(cmd);
2255 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2256 cmd_name, CommandTypeString(sync_event->last_command));
2257 }
2258 }
2259
2260 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002261}
2262
John Zulauf4a6105a2020-11-17 15:11:05 -07002263void CommandBufferAccessContext::RecordSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask,
2264 const ResourceUsageTag &tag) {
2265 auto *sync_event = GetEventState(event);
2266 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2267
2268 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
2269 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
2270 // any issues caused by naive scope setting here.
2271
2272 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
2273 // Given:
2274 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
2275 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002276 auto scope = SyncExecScope::MakeSrc(GetQueueFlags(), stageMask);
John Zulauf4a6105a2020-11-17 15:11:05 -07002277
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002278 if (!sync_event->HasBarrier(stageMask, scope.exec_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002279 sync_event->unsynchronized_set = sync_event->last_command;
2280 sync_event->ResetFirstScope();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002281 } else if (sync_event->scope.exec_scope == 0) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002282 // We only set the scope if there isn't one
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002283 sync_event->scope = scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07002284
2285 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
2286 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002287 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002288 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
2289 }
2290 };
2291 GetCurrentAccessContext()->ForAll(set_scope);
2292 sync_event->unsynchronized_set = CMD_NONE;
2293 sync_event->first_scope_tag = tag;
2294 }
2295 sync_event->last_command = CMD_SETEVENT;
2296 sync_event->barriers = 0U;
2297}
John Zulauf49beb112020-11-04 16:06:31 -07002298
2299bool CommandBufferAccessContext::ValidateResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2300 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002301 // I'll put this here just in case we need to pass this in for future extension support
2302 const auto cmd = CMD_RESETEVENT;
2303
2304 bool skip = false;
2305 // TODO: EVENTS:
2306 // What is it we need to check... that we've had a reset since a set? Set/Set seems ill formed...
2307 const auto *sync_event = GetEventState(event);
2308 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2309
2310 const char *const set_wait =
2311 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2312 "hazards.";
2313 const char *message = set_wait; // Only one message this call.
2314 const auto exec_scope = WithEarlierPipelineStages(ExpandPipelineStages(GetQueueFlags(), stageMask));
2315 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2316 const char *vuid = nullptr;
2317 switch (sync_event->last_command) {
2318 case CMD_SETEVENT:
2319 // Needs a barrier between set and reset
2320 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
2321 break;
2322 case CMD_WAITEVENTS: {
2323 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
2324 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
2325 break;
2326 }
2327 default:
2328 // The only other valid last command that wasn't one.
2329 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT));
2330 break;
2331 }
2332 if (vuid) {
2333 const char *const cmd_name = CommandTypeString(cmd);
2334 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2335 cmd_name, CommandTypeString(sync_event->last_command));
2336 }
2337 }
2338 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002339}
2340
John Zulauf4a6105a2020-11-17 15:11:05 -07002341void CommandBufferAccessContext::RecordResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
2342 const auto cmd = CMD_RESETEVENT;
2343 auto *sync_event = GetEventState(event);
2344 if (!sync_event) return;
John Zulauf49beb112020-11-04 16:06:31 -07002345
John Zulauf4a6105a2020-11-17 15:11:05 -07002346 // Clear out the first sync scope, any races vs. wait or set are reported, so we'll keep the bookkeeping simple assuming
2347 // the safe case
2348 for (const auto address_type : kAddressTypes) {
2349 sync_event->first_scope[static_cast<size_t>(address_type)].clear();
2350 }
2351
2352 // Update the event state
2353 sync_event->last_command = cmd;
2354 sync_event->unsynchronized_set = CMD_NONE;
2355 sync_event->ResetFirstScope();
2356 sync_event->barriers = 0U;
2357}
2358
John Zulauf4a6105a2020-11-17 15:11:05 -07002359void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2360 // Erase is okay with the key not being
John Zulaufd5115702021-01-18 12:34:33 -07002361 auto event_it = event_state_.find(event);
2362 if (event_it != event_state_.end()) {
2363 SyncEventStateShared &sync_event = event_it->second;
2364 if (sync_event) {
2365 sync_event->destroyed = true;
2366 }
2367 event_state_.erase(event_it);
2368 }
2369}
2370
2371SyncEventStateShared &CommandBufferAccessContext::GetEventStateShared(VkEvent event) {
2372 SyncEventStateShared &event_state = event_state_[event];
2373 if (!event_state) {
2374 auto event_atate = sync_state_->GetShared<EVENT_STATE>(event);
2375 event_state.reset(new SyncEventState(event_atate));
2376 }
2377 return event_state;
2378}
2379
2380const SyncEventStateShared CommandBufferAccessContext::GetEventStateConstCastShared(VkEvent event) const {
2381 auto event_it = event_state_.find(event);
2382 if (event_it == event_state_.cend()) {
2383 return SyncEventStateShared();
2384 }
2385 return event_it->second;
2386}
2387
2388const SyncEventStateConstShared CommandBufferAccessContext::GetEventStateShared(VkEvent event) const {
2389 auto event_it = event_state_.find(event);
2390 if (event_it == event_state_.cend()) {
2391 return SyncEventStateConstShared();
2392 }
2393 return event_it->second;
John Zulauf4a6105a2020-11-17 15:11:05 -07002394}
2395
2396SyncEventState *CommandBufferAccessContext::GetEventState(VkEvent event) {
2397 auto &event_up = event_state_[event];
2398 if (!event_up) {
2399 auto event_atate = sync_state_->GetShared<EVENT_STATE>(event);
2400 event_up.reset(new SyncEventState(event_atate));
2401 }
2402 return event_up.get();
2403}
2404
2405const SyncEventState *CommandBufferAccessContext::GetEventState(VkEvent event) const {
2406 auto event_it = event_state_.find(event);
2407 if (event_it == event_state_.cend()) {
2408 return nullptr;
2409 }
2410 return event_it->second.get();
2411}
John Zulauf49beb112020-11-04 16:06:31 -07002412
John Zulauffaea0ee2021-01-14 14:01:32 -07002413bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandBufferAccessContext &cb_context,
2414 const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2415 const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002416 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002417 const auto &sync_state = cb_context.GetSyncState();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002418 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2419 if (!pipe ||
2420 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002421 return skip;
2422 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002423 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002424 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2425 VkExtent3D extent = CastTo3D(render_area.extent);
2426 VkOffset3D offset = CastTo3D(render_area.offset);
locke-lunarg37047832020-06-12 13:44:45 -06002427
John Zulauf1a224292020-06-30 14:52:13 -06002428 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002429 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002430 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2431 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002432 if (location >= subpass.colorAttachmentCount ||
2433 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002434 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002435 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002436 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf1a224292020-06-30 14:52:13 -06002437 HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002438 SyncOrdering::kColorAttachment, offset, extent);
locke-lunarg96dc9632020-06-10 17:22:18 -06002439 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002440 skip |= sync_state.LogError(img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002441 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002442 func_name, string_SyncHazard(hazard.hazard),
2443 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2444 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002445 location, cb_context.FormatUsage(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002446 }
2447 }
2448 }
locke-lunarg37047832020-06-12 13:44:45 -06002449
2450 // PHASE1 TODO: Add layout based read/vs. write selection.
2451 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002452 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002453 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002454 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002455 bool depth_write = false, stencil_write = false;
2456
2457 // PHASE1 TODO: These validation should be in core_checks.
2458 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002459 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2460 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002461 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2462 depth_write = true;
2463 }
2464 // PHASE1 TODO: It needs to check if stencil is writable.
2465 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2466 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2467 // PHASE1 TODO: These validation should be in core_checks.
2468 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002469 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002470 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2471 stencil_write = true;
2472 }
2473
2474 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2475 if (depth_write) {
2476 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002477 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002478 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002479 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002480 skip |= sync_state.LogError(
2481 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002482 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002483 func_name, string_SyncHazard(hazard.hazard),
2484 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2485 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002486 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002487 }
2488 }
2489 if (stencil_write) {
2490 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002491 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
John Zulauf8e3c3e92021-01-06 11:19:36 -07002492 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002493 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002494 skip |= sync_state.LogError(
2495 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002496 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002497 func_name, string_SyncHazard(hazard.hazard),
2498 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2499 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauffaea0ee2021-01-14 14:01:32 -07002500 cb_context.FormatUsage(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002501 }
locke-lunarg61870c22020-06-09 14:51:50 -06002502 }
2503 }
2504 return skip;
2505}
2506
locke-lunarg96dc9632020-06-10 17:22:18 -06002507void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2508 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002509 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2510 if (!pipe ||
2511 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002512 return;
2513 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002514 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002515 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2516 VkExtent3D extent = CastTo3D(render_area.extent);
2517 VkOffset3D offset = CastTo3D(render_area.offset);
2518
John Zulauf1a224292020-06-30 14:52:13 -06002519 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002520 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002521 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2522 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002523 if (location >= subpass.colorAttachmentCount ||
2524 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002525 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002526 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002527 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf8e3c3e92021-01-06 11:19:36 -07002528 current_context.UpdateAccessState(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
2529 SyncOrdering::kColorAttachment, offset, extent, 0, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002530 }
2531 }
locke-lunarg37047832020-06-12 13:44:45 -06002532
2533 // PHASE1 TODO: Add layout based read/vs. write selection.
2534 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002535 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002536 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002537 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002538 bool depth_write = false, stencil_write = false;
2539
2540 // PHASE1 TODO: These validation should be in core_checks.
2541 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002542 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2543 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002544 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2545 depth_write = true;
2546 }
2547 // PHASE1 TODO: It needs to check if stencil is writable.
2548 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2549 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2550 // PHASE1 TODO: These validation should be in core_checks.
2551 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002552 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002553 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2554 stencil_write = true;
2555 }
2556
2557 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2558 if (depth_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002559 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2560 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT,
2561 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002562 }
2563 if (stencil_write) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002564 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2565 SyncOrdering::kDepthStencilAttachment, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT,
2566 tag);
locke-lunarg37047832020-06-12 13:44:45 -06002567 }
locke-lunarg61870c22020-06-09 14:51:50 -06002568 }
2569}
2570
John Zulauffaea0ee2021-01-14 14:01:32 -07002571bool RenderPassAccessContext::ValidateNextSubpass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf1507ee42020-05-18 11:33:09 -06002572 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002573 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002574 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002575 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002576 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002577 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002578 func_name);
2579
John Zulauf355e49b2020-04-24 15:11:15 -06002580 const auto next_subpass = current_subpass_ + 1;
John Zulauf1507ee42020-05-18 11:33:09 -06002581 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauffaea0ee2021-01-14 14:01:32 -07002582 skip |= next_context.ValidateLayoutTransitions(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002583 if (!skip) {
2584 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2585 // on a copy of the (empty) next context.
2586 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2587 AccessContext temp_context(next_context);
2588 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kCurrentCommandTag);
John Zulauffaea0ee2021-01-14 14:01:32 -07002589 skip |= temp_context.ValidateLoadOperation(cb_context, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002590 }
John Zulauf7635de32020-05-29 17:14:15 -06002591 return skip;
2592}
John Zulauffaea0ee2021-01-14 14:01:32 -07002593bool RenderPassAccessContext::ValidateEndRenderPass(const CommandBufferAccessContext &cb_context, const VkRect2D &render_area,
John Zulauf7635de32020-05-29 17:14:15 -06002594 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002595 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002596 bool skip = false;
John Zulauffaea0ee2021-01-14 14:01:32 -07002597 skip |= CurrentContext().ValidateResolveOperations(cb_context, *rp_state_, render_area, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002598 current_subpass_);
John Zulauffaea0ee2021-01-14 14:01:32 -07002599 skip |= CurrentContext().ValidateStoreOperation(cb_context, *rp_state_, render_area, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002600 func_name);
John Zulauffaea0ee2021-01-14 14:01:32 -07002601 skip |= ValidateFinalSubpassLayoutTransitions(cb_context, render_area, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002602 return skip;
2603}
2604
John Zulauf7635de32020-05-29 17:14:15 -06002605AccessContext *RenderPassAccessContext::CreateStoreResolveProxy(const VkRect2D &render_area) const {
2606 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, render_area, attachment_views_);
2607}
2608
John Zulauffaea0ee2021-01-14 14:01:32 -07002609bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandBufferAccessContext &cb_context,
2610 const VkRect2D &render_area, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002611 bool skip = false;
2612
John Zulauf7635de32020-05-29 17:14:15 -06002613 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2614 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2615 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2616 // to apply and only copy then, if this proves a hot spot.
2617 std::unique_ptr<AccessContext> proxy_for_current;
2618
John Zulauf355e49b2020-04-24 15:11:15 -06002619 // Validate the "finalLayout" transitions to external
2620 // Get them from where there we're hidding in the extra entry.
2621 const auto &final_transitions = rp_state_->subpass_transitions.back();
2622 for (const auto &transition : final_transitions) {
2623 const auto &attach_view = attachment_views_[transition.attachment];
2624 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
2625 assert(trackback.context); // Transitions are given implicit transitions if the StateTracker is working correctly
John Zulauf7635de32020-05-29 17:14:15 -06002626 auto *context = trackback.context;
2627
2628 if (transition.prev_pass == current_subpass_) {
2629 if (!proxy_for_current) {
2630 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
2631 proxy_for_current.reset(CreateStoreResolveProxy(render_area));
2632 }
2633 context = proxy_for_current.get();
2634 }
2635
John Zulaufa0a98292020-09-18 09:30:10 -06002636 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2637 const auto merged_barrier = MergeBarriers(trackback.barriers);
2638 auto hazard = context->DetectImageBarrierHazard(*attach_view->image_state, merged_barrier.src_exec_scope,
2639 merged_barrier.src_access_scope, attach_view->normalized_subresource_range,
2640 AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002641 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -07002642 skip |= cb_context.GetSyncState().LogError(
2643 rp_state_->renderPass, string_SyncHazardVUID(hazard.hazard),
2644 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2645 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2646 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2647 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
2648 cb_context.FormatUsage(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06002649 }
2650 }
2651 return skip;
2652}
2653
2654void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag &tag) {
2655 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002656 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002657}
2658
John Zulauf1507ee42020-05-18 11:33:09 -06002659void RenderPassAccessContext::RecordLoadOperations(const VkRect2D &render_area, const ResourceUsageTag &tag) {
2660 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2661 auto &subpass_context = subpass_contexts_[current_subpass_];
2662 VkExtent3D extent = CastTo3D(render_area.extent);
2663 VkOffset3D offset = CastTo3D(render_area.offset);
2664
2665 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2666 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
2667 if (attachment_views_[i] == nullptr) continue; // UNUSED
2668 const auto &view = *attachment_views_[i];
2669 const IMAGE_STATE *image = view.image_state.get();
2670 if (image == nullptr) continue;
2671
2672 const auto &ci = attachment_ci[i];
2673 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002674 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002675 const bool is_color = !(has_depth || has_stencil);
2676
2677 if (is_color) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002678 subpass_context.UpdateAccessState(*image, ColorLoadUsage(ci.loadOp), SyncOrdering::kColorAttachment,
2679 view.normalized_subresource_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002680 } else {
2681 auto update_range = view.normalized_subresource_range;
2682 if (has_depth) {
2683 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002684 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.loadOp),
2685 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002686 }
2687 if (has_stencil) {
2688 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf8e3c3e92021-01-06 11:19:36 -07002689 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.stencilLoadOp),
2690 SyncOrdering::kDepthStencilAttachment, update_range, offset, extent, tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002691 }
2692 }
2693 }
2694 }
2695}
2696
John Zulauf355e49b2020-04-24 15:11:15 -06002697void RenderPassAccessContext::RecordBeginRenderPass(const SyncValidator &state, const CMD_BUFFER_STATE &cb_state,
John Zulauf1a224292020-06-30 14:52:13 -06002698 const AccessContext *external_context, VkQueueFlags queue_flags,
2699 const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002700 current_subpass_ = 0;
locke-lunargaecf2152020-05-12 17:15:41 -06002701 rp_state_ = cb_state.activeRenderPass.get();
John Zulauf355e49b2020-04-24 15:11:15 -06002702 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
2703 // Add this for all subpasses here so that they exsist during next subpass validation
2704 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002705 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulauf355e49b2020-04-24 15:11:15 -06002706 }
2707 attachment_views_ = state.GetCurrentAttachmentViews(cb_state);
2708
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002709 subpass_contexts_[current_subpass_].SetStartTag(tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002710 RecordLayoutTransitions(tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002711 RecordLoadOperations(cb_state.activeRenderPassBeginInfo.renderArea, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002712}
John Zulauf1507ee42020-05-18 11:33:09 -06002713
John Zulauffaea0ee2021-01-14 14:01:32 -07002714void RenderPassAccessContext::RecordNextSubpass(const VkRect2D &render_area, const ResourceUsageTag &prev_subpass_tag,
2715 const ResourceUsageTag &next_subpass_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002716 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauffaea0ee2021-01-14 14:01:32 -07002717 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
2718 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, prev_subpass_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002719
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002720 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2721 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002722 current_subpass_++;
2723 assert(current_subpass_ < subpass_contexts_.size());
John Zulauffaea0ee2021-01-14 14:01:32 -07002724 subpass_contexts_[current_subpass_].SetStartTag(next_subpass_tag);
2725 RecordLayoutTransitions(next_subpass_tag);
2726 RecordLoadOperations(render_area, next_subpass_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002727}
2728
John Zulauf1a224292020-06-30 14:52:13 -06002729void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const VkRect2D &render_area,
2730 const ResourceUsageTag &tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002731 // Add the resolve and store accesses
John Zulauf7635de32020-05-29 17:14:15 -06002732 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulaufaff20662020-06-01 14:07:58 -06002733 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulauf7635de32020-05-29 17:14:15 -06002734
John Zulauf355e49b2020-04-24 15:11:15 -06002735 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002736 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002737
2738 // Add the "finalLayout" transitions to external
2739 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002740 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2741 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2742 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002743 const auto &final_transitions = rp_state_->subpass_transitions.back();
2744 for (const auto &transition : final_transitions) {
2745 const auto &attachment = attachment_views_[transition.attachment];
2746 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufaa97d8b2020-07-14 10:58:13 -06002747 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.context);
John Zulaufd5115702021-01-18 12:34:33 -07002748 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002749 for (const auto &barrier : last_trackback.barriers) {
John Zulaufd5115702021-01-18 12:34:33 -07002750 barrier_action.EmplaceBack(PipelineBarrierOp(barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002751 }
John Zulauf1e331ec2020-12-04 18:29:38 -07002752 external_context->UpdateResourceAccess(*attachment->image_state, attachment->normalized_subresource_range, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002753 }
2754}
2755
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002756SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2757 SyncExecScope result;
2758 result.mask_param = mask_param;
2759 result.expanded_mask = ExpandPipelineStages(queue_flags, mask_param);
2760 result.exec_scope = WithEarlierPipelineStages(result.expanded_mask);
2761 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2762 return result;
2763}
2764
2765SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags mask_param) {
2766 SyncExecScope result;
2767 result.mask_param = mask_param;
2768 result.expanded_mask = ExpandPipelineStages(queue_flags, mask_param);
2769 result.exec_scope = WithLaterPipelineStages(result.expanded_mask);
2770 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2771 return result;
2772}
2773
2774SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
2775 src_exec_scope = src.exec_scope;
2776 src_access_scope = 0;
2777 dst_exec_scope = dst.exec_scope;
2778 dst_access_scope = 0;
2779}
2780
2781template <typename Barrier>
2782SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
2783 src_exec_scope = src.exec_scope;
2784 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2785 dst_exec_scope = dst.exec_scope;
2786 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2787}
2788
2789SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
2790 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
2791 src_exec_scope = src.exec_scope;
2792 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2793
2794 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
2795 dst_exec_scope = dst.exec_scope;
2796 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002797}
2798
John Zulaufb02c1eb2020-10-06 16:33:36 -06002799// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2800void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
2801 for (const auto &barrier : barriers) {
2802 ApplyBarrier(barrier, layout_transition);
2803 }
2804}
2805
John Zulauf89311b42020-09-29 16:28:47 -06002806// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2807// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2808// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufb02c1eb2020-10-06 16:33:36 -06002809void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, const ResourceUsageTag &tag) {
2810 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002811 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002812 assert(!pending_write_dep_chain);
John Zulaufa0a98292020-09-18 09:30:10 -06002813 for (const auto &barrier : barriers) {
John Zulauf89311b42020-09-29 16:28:47 -06002814 ApplyBarrier(barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002815 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002816 ApplyPendingBarriers(tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002817}
John Zulauf9cb530d2019-09-30 14:14:10 -06002818HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2819 HazardResult hazard;
2820 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002821 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002822 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002823 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002824 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002825 }
2826 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002827 // Write operation:
2828 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2829 // If reads exists -- test only against them because either:
2830 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2831 // * 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
2832 // the current write happens after the reads, so just test the write against the reades
2833 // Otherwise test against last_write
2834 //
2835 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002836 if (last_reads.size()) {
2837 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002838 if (IsReadHazard(usage_stage, read_access)) {
2839 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2840 break;
2841 }
2842 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002843 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002844 // Write-After-Write check -- if we have a previous write to test against
2845 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002846 }
2847 }
2848 return hazard;
2849}
2850
John Zulauf8e3c3e92021-01-06 11:19:36 -07002851HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering &ordering_rule) const {
2852 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06002853 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2854 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002855 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002856 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002857 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2858 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002859 if (IsRead(usage_bit)) {
2860 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2861 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2862 if (is_raw_hazard) {
2863 // NOTE: we know last_write is non-zero
2864 // See if the ordering rules save us from the simple RAW check above
2865 // First check to see if the current usage is covered by the ordering rules
2866 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2867 const bool usage_is_ordered =
2868 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2869 if (usage_is_ordered) {
2870 // Now see of the most recent write (or a subsequent read) are ordered
2871 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2872 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002873 }
2874 }
John Zulauf4285ee92020-09-23 10:20:52 -06002875 if (is_raw_hazard) {
2876 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
2877 }
John Zulauf361fb532020-07-22 10:45:39 -06002878 } else {
2879 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002880 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07002881 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06002882 // Look for any WAR hazards outside the ordered set of stages
John Zulauf4285ee92020-09-23 10:20:52 -06002883 VkPipelineStageFlags ordered_stages = 0;
2884 if (usage_write_is_ordered) {
2885 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
2886 ordered_stages = GetOrderedStages(ordering);
2887 }
2888 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
2889 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07002890 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06002891 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
2892 if (IsReadHazard(usage_stage, read_access)) {
2893 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2894 break;
2895 }
John Zulaufd14743a2020-07-03 09:42:39 -06002896 }
2897 }
John Zulauf4285ee92020-09-23 10:20:52 -06002898 } else if (!(last_write_is_ordered && usage_write_is_ordered)) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002899 if (last_write.any() && IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002900 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06002901 }
John Zulauf69133422020-05-20 14:55:53 -06002902 }
2903 }
2904 return hazard;
2905}
2906
John Zulauf2f952d22020-02-10 11:34:51 -07002907// Asynchronous Hazards occur between subpasses with no connection through the DAG
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002908HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag &start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07002909 HazardResult hazard;
2910 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002911 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
2912 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
2913 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07002914 if (IsRead(usage)) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002915 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002916 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07002917 }
2918 } else {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002919 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06002920 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07002921 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002922 // 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 -07002923 for (const auto &read_access : last_reads) {
2924 if (read_access.tag.index >= start_tag.index) {
2925 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002926 break;
2927 }
2928 }
John Zulauf2f952d22020-02-10 11:34:51 -07002929 }
2930 }
2931 return hazard;
2932}
2933
John Zulauf36bcf6a2020-02-03 15:12:52 -07002934HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002935 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07002936 // Only supporting image layout transitions for now
2937 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2938 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06002939 // only test for WAW if there no intervening read operations.
2940 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07002941 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06002942 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07002943 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002944 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06002945 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07002946 break;
2947 }
2948 }
John Zulauf4a6105a2020-11-17 15:11:05 -07002949 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2950 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2951 }
2952
2953 return hazard;
2954}
2955
2956HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
2957 const SyncStageAccessFlags &src_access_scope,
2958 const ResourceUsageTag &event_tag) const {
2959 // Only supporting image layout transitions for now
2960 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
2961 HazardResult hazard;
2962 // only test for WAW if there no intervening read operations.
2963 // See DetectHazard(SyncStagetAccessIndex) above for more details.
2964
John Zulaufab7756b2020-12-29 16:10:16 -07002965 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002966 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
2967 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07002968 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002969 if (read_access.tag.IsBefore(event_tag)) {
2970 // The read is in the events first synchronization scope, so we use a barrier hazard check
2971 // If the read stage is not in the src sync scope
2972 // *AND* not execution chained with an existing sync barrier (that's the or)
2973 // then the barrier access is unsafe (R/W after R)
2974 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
2975 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2976 break;
2977 }
2978 } else {
2979 // The read not in the event first sync scope and so is a hazard vs. the layout transition
2980 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2981 }
2982 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002983 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07002984 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
2985 if (write_tag.IsBefore(event_tag)) {
2986 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
2987 // So do a normal barrier hazard check
2988 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
2989 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2990 }
2991 } else {
2992 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06002993 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
2994 }
John Zulaufd14743a2020-07-03 09:42:39 -06002995 }
John Zulauf361fb532020-07-22 10:45:39 -06002996
John Zulauf0cb5be22020-01-23 12:18:22 -07002997 return hazard;
2998}
2999
John Zulauf5f13a792020-03-10 07:31:21 -06003000// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3001// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3002// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3003void ResourceAccessState::Resolve(const ResourceAccessState &other) {
3004 if (write_tag.IsBefore(other.write_tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003005 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3006 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003007 *this = other;
3008 } else if (!other.write_tag.IsBefore(write_tag)) {
3009 // This is the *equals* case for write operations, we merged the write barriers and the read state (but without the
3010 // dependency chaining logic or any stage expansion)
3011 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003012 pending_write_barriers |= other.pending_write_barriers;
3013 pending_layout_transition |= other.pending_layout_transition;
3014 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003015
John Zulaufd14743a2020-07-03 09:42:39 -06003016 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003017 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003018 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003019 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003020 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003021 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003022 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003023 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3024 // but we should wait on profiling data for that.
3025 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003026 auto &my_read = last_reads[my_read_index];
3027 if (other_read.stage == my_read.stage) {
3028 if (my_read.tag.IsBefore(other_read.tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003029 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003030 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003031 my_read.tag = other_read.tag;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003032 my_read.pending_dep_chain = other_read.pending_dep_chain;
3033 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3034 // May require tracking more than one access per stage.
3035 my_read.barriers = other_read.barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003036 if (my_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
3037 // Since I'm overwriting the fragement stage read, also update the input attachment info
3038 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003039 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003040 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003041 } else if (other_read.tag.IsBefore(my_read.tag)) {
3042 // The read tags match so merge the barriers
3043 my_read.barriers |= other_read.barriers;
3044 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003045 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003046
John Zulauf5f13a792020-03-10 07:31:21 -06003047 break;
3048 }
3049 }
3050 } else {
3051 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003052 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003053 last_read_stages |= other_read.stage;
John Zulauf4285ee92020-09-23 10:20:52 -06003054 if (other_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003055 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003056 }
John Zulauf5f13a792020-03-10 07:31:21 -06003057 }
3058 }
John Zulauf361fb532020-07-22 10:45:39 -06003059 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003060 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3061 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003062
3063 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3064 // of the copy and other into this using the update first logic.
3065 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3066 // of the other first_accesses... )
3067 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3068 FirstAccesses firsts(std::move(first_accesses_));
3069 first_accesses_.clear();
3070 first_read_stages_ = 0U;
3071 auto a = firsts.begin();
3072 auto a_end = firsts.end();
3073 for (auto &b : other.first_accesses_) {
3074 // TODO: Determine whether "IsBefore" or "IsGloballyBefore" is needed...
3075 while (a != a_end && a->tag.IsBefore(b.tag)) {
3076 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3077 ++a;
3078 }
3079 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3080 }
3081 for (; a != a_end; ++a) {
3082 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3083 }
3084 }
John Zulauf5f13a792020-03-10 07:31:21 -06003085}
3086
John Zulauf8e3c3e92021-01-06 11:19:36 -07003087void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag &tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003088 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3089 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003090 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003091 // Mulitple outstanding reads may be of interest and do dependency chains independently
3092 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3093 const auto usage_stage = PipelineStageBit(usage_index);
3094 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003095 for (auto &read_access : last_reads) {
3096 if (read_access.stage == usage_stage) {
3097 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003098 break;
3099 }
3100 }
3101 } else {
John Zulaufab7756b2020-12-29 16:10:16 -07003102 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003103 last_read_stages |= usage_stage;
3104 }
John Zulauf4285ee92020-09-23 10:20:52 -06003105
3106 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
3107 if (usage_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003108 // TODO Revisit re: multiple reads for a given stage
3109 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003110 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003111 } else {
3112 // Assume write
3113 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003114 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003115 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003116 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003117}
John Zulauf5f13a792020-03-10 07:31:21 -06003118
John Zulauf89311b42020-09-29 16:28:47 -06003119// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3120// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3121// We can overwrite them as *this* write is now after them.
3122//
3123// 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 -07003124void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag &tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003125 last_reads.clear();
John Zulauf89311b42020-09-29 16:28:47 -06003126 last_read_stages = 0;
3127 read_execution_barriers = 0;
John Zulauff51fbb62020-10-02 14:43:24 -06003128 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
John Zulauf89311b42020-09-29 16:28:47 -06003129
3130 write_barriers = 0;
3131 write_dependency_chain = 0;
3132 write_tag = tag;
3133 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003134}
3135
John Zulauf89311b42020-09-29 16:28:47 -06003136// Apply the memory barrier without updating the existing barriers. The execution barrier
3137// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3138// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3139// replace the current write barriers or add to them, so accumulate to pending as well.
3140void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) {
3141 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3142 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003143 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
3144 // transistion, under the theory of "most recent access". If the read/write *isn't* safe
3145 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3146 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulauf4a6105a2020-11-17 15:11:05 -07003147 if (layout_transition || WriteInSourceScopeOrChain(barrier.src_exec_scope, barrier.src_access_scope)) {
John Zulauf89311b42020-09-29 16:28:47 -06003148 pending_write_barriers |= barrier.dst_access_scope;
3149 pending_write_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003150 }
John Zulauf89311b42020-09-29 16:28:47 -06003151 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3152 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003153
John Zulauf89311b42020-09-29 16:28:47 -06003154 if (!pending_layout_transition) {
3155 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3156 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003157 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003158 // 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 -07003159 if (barrier.src_exec_scope & (read_access.stage | read_access.barriers)) {
3160 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003161 }
3162 }
John Zulaufa0a98292020-09-18 09:30:10 -06003163 }
John Zulaufa0a98292020-09-18 09:30:10 -06003164}
3165
John Zulauf4a6105a2020-11-17 15:11:05 -07003166// Apply the tag scoped memory barrier without updating the existing barriers. The execution barrier
3167// changes the "chaining" state, but to keep barriers independent. See discussion above.
3168void ResourceAccessState::ApplyBarrier(const ResourceUsageTag &scope_tag, const SyncBarrier &barrier, bool layout_transition) {
3169 // The scope logic for events is, if we're here, the resource usage was flagged as "in the first execution scope" at
3170 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3171 // in order to know if it's in the excecution scope
3172 // Notice that the layout transition sets the pending barriers *regardless*, as any lack of src_access_scope to
3173 // guard against the layout transition should be reported in the detect barrier hazard phase, and we only report
3174 // errors w.r.t. "most recent" accesses.
3175 if (layout_transition || ((write_tag.IsBefore(scope_tag)) && (barrier.src_access_scope & last_write).any())) {
3176 pending_write_barriers |= barrier.dst_access_scope;
3177 pending_write_dep_chain |= barrier.dst_exec_scope;
3178 }
3179 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3180 pending_layout_transition |= layout_transition;
3181
3182 if (!pending_layout_transition) {
3183 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3184 // don't need to be tracked as we're just going to zero them.
John Zulaufab7756b2020-12-29 16:10:16 -07003185 for (auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003186 // If this read is the same one we included in the set event and in scope, then apply the execution barrier...
3187 // NOTE: That's not really correct... this read stage might *not* have been included in the setevent, and the barriers
3188 // representing the chain might have changed since then (that would be an odd usage), so as a first approximation
3189 // we'll assume the barriers *haven't* been changed since (if the tag hasn't), and while this could be a false
3190 // positive in the case of Set; SomeBarrier; Wait; we'll live with it until we can add more state to the first scope
3191 // capture (the specific write and read stages that *were* in scope at the moment of SetEvents.
3192 // TODO: eliminate the false positive by including write/read-stages "in scope" information in SetEvents first_scope
John Zulaufab7756b2020-12-29 16:10:16 -07003193 if (read_access.tag.IsBefore(scope_tag) && (barrier.src_exec_scope & (read_access.stage | read_access.barriers))) {
3194 read_access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulauf4a6105a2020-11-17 15:11:05 -07003195 }
3196 }
3197 }
3198}
John Zulauf89311b42020-09-29 16:28:47 -06003199void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag &tag) {
3200 if (pending_layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003201 // SetWrite clobbers the read count, and thus we don't have to clear the read_state out.
3202 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003203 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf89311b42020-09-29 16:28:47 -06003204 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003205 }
John Zulauf89311b42020-09-29 16:28:47 -06003206
3207 // Apply the accumulate execution barriers (and thus update chaining information)
3208 // for layout transition, read count is zeroed by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003209 for (auto &read_access : last_reads) {
3210 read_access.barriers |= read_access.pending_dep_chain;
3211 read_execution_barriers |= read_access.barriers;
3212 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003213 }
3214
3215 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3216 write_dependency_chain |= pending_write_dep_chain;
3217 write_barriers |= pending_write_barriers;
3218 pending_write_dep_chain = 0;
3219 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003220}
3221
John Zulauf59e25072020-07-17 10:55:21 -06003222// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003223VkPipelineStageFlags ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
John Zulauf59e25072020-07-17 10:55:21 -06003224 VkPipelineStageFlags barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003225
John Zulaufab7756b2020-12-29 16:10:16 -07003226 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003227 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003228 barriers = read_access.barriers;
3229 break;
John Zulauf59e25072020-07-17 10:55:21 -06003230 }
3231 }
John Zulauf4285ee92020-09-23 10:20:52 -06003232
John Zulauf59e25072020-07-17 10:55:21 -06003233 return barriers;
3234}
3235
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003236inline bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlagBits usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003237 assert(IsRead(usage));
3238 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3239 // * the previous reads are not hazards, and thus last_write must be visible and available to
3240 // any reads that happen after.
3241 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3242 // 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 -07003243 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003244}
3245
John Zulauf8e3c3e92021-01-06 11:19:36 -07003246VkPipelineStageFlags ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003247 // Whether the stage are in the ordering scope only matters if the current write is ordered
3248 VkPipelineStageFlags ordered_stages = last_read_stages & ordering.exec_scope;
3249 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003250 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003251 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003252 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
3253 ordered_stages |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
3254 }
3255
3256 return ordered_stages;
3257}
3258
John Zulauffaea0ee2021-01-14 14:01:32 -07003259void ResourceAccessState::UpdateFirst(const ResourceUsageTag &tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
3260 // Only record until we record a write.
3261 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003262 const VkPipelineStageFlags usage_stage =
3263 IsRead(usage_index) ? static_cast<VkPipelineStageFlags>(PipelineStageBit(usage_index)) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003264 if (0 == (usage_stage & first_read_stages_)) {
3265 // If this is a read we haven't seen or a write, record.
3266 first_read_stages_ |= usage_stage;
3267 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3268 }
3269 }
3270}
3271
John Zulaufd1f85d42020-04-15 12:23:15 -06003272void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003273 auto *access_context = GetAccessContextNoInsert(command_buffer);
3274 if (access_context) {
3275 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003276 }
3277}
3278
John Zulaufd1f85d42020-04-15 12:23:15 -06003279void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3280 auto access_found = cb_access_state.find(command_buffer);
3281 if (access_found != cb_access_state.end()) {
3282 access_found->second->Reset();
3283 cb_access_state.erase(access_found);
3284 }
3285}
3286
John Zulauf9cb530d2019-09-30 14:14:10 -06003287bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3288 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3289 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003290 const auto *cb_context = GetAccessContext(commandBuffer);
3291 assert(cb_context);
3292 if (!cb_context) return skip;
3293 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003294
John Zulauf3d84f1b2020-03-09 13:33:25 -06003295 // If we have no previous accesses, we have no hazards
John Zulauf3d84f1b2020-03-09 13:33:25 -06003296 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003297 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003298
3299 for (uint32_t region = 0; region < regionCount; region++) {
3300 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003301 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003302 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003303 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003304 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003305 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003306 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003307 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003308 cb_context->FormatUsage(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003309 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003310 }
John Zulauf16adfc92020-04-08 10:28:33 -06003311 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003312 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf355e49b2020-04-24 15:11:15 -06003313 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003314 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003315 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003316 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003317 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003318 cb_context->FormatUsage(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003319 }
3320 }
3321 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003322 }
3323 return skip;
3324}
3325
3326void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3327 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003328 auto *cb_context = GetAccessContext(commandBuffer);
3329 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003330 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003331 auto *context = cb_context->GetCurrentAccessContext();
3332
John Zulauf9cb530d2019-09-30 14:14:10 -06003333 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003334 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003335
3336 for (uint32_t region = 0; region < regionCount; region++) {
3337 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003338 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003339 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003340 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003341 }
John Zulauf16adfc92020-04-08 10:28:33 -06003342 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003343 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003344 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003345 }
3346 }
3347}
3348
John Zulauf4a6105a2020-11-17 15:11:05 -07003349void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3350 // Clear out events from the command buffer contexts
3351 for (auto &cb_context : cb_access_state) {
3352 cb_context.second->RecordDestroyEvent(event);
3353 }
3354}
3355
Jeff Leger178b1e52020-10-05 12:22:23 -04003356bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3357 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3358 bool skip = false;
3359 const auto *cb_context = GetAccessContext(commandBuffer);
3360 assert(cb_context);
3361 if (!cb_context) return skip;
3362 const auto *context = cb_context->GetCurrentAccessContext();
3363
3364 // If we have no previous accesses, we have no hazards
3365 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3366 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3367
3368 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3369 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3370 if (src_buffer) {
3371 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
3372 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3373 if (hazard.hazard) {
3374 // TODO -- add tag information to log msg when useful.
3375 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
3376 "vkCmdCopyBuffer2KHR(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
3377 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003378 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003379 }
3380 }
3381 if (dst_buffer && !skip) {
3382 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
3383 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3384 if (hazard.hazard) {
3385 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
3386 "vkCmdCopyBuffer2KHR(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
3387 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003388 region, cb_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003389 }
3390 }
3391 if (skip) break;
3392 }
3393 return skip;
3394}
3395
3396void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3397 auto *cb_context = GetAccessContext(commandBuffer);
3398 assert(cb_context);
3399 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER2KHR);
3400 auto *context = cb_context->GetCurrentAccessContext();
3401
3402 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3403 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3404
3405 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3406 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3407 if (src_buffer) {
3408 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003409 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003410 }
3411 if (dst_buffer) {
3412 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003413 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003414 }
3415 }
3416}
3417
John Zulauf5c5e88d2019-12-26 11:22:02 -07003418bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3419 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3420 const VkImageCopy *pRegions) const {
3421 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003422 const auto *cb_access_context = GetAccessContext(commandBuffer);
3423 assert(cb_access_context);
3424 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003425
John Zulauf3d84f1b2020-03-09 13:33:25 -06003426 const auto *context = cb_access_context->GetCurrentAccessContext();
3427 assert(context);
3428 if (!context) return skip;
3429
3430 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3431 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003432 for (uint32_t region = 0; region < regionCount; region++) {
3433 const auto &copy_region = pRegions[region];
3434 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003435 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003436 copy_region.srcOffset, copy_region.extent);
3437 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003438 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003439 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003440 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003441 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003442 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003443 }
3444
3445 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003446 VkExtent3D dst_copy_extent =
3447 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf540266b2020-04-06 18:54:53 -06003448 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
locke-lunarg1df1f882020-03-02 16:42:08 -07003449 copy_region.dstOffset, dst_copy_extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003450 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003451 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003452 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003453 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003454 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003455 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07003456 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003457 }
3458 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003459
John Zulauf5c5e88d2019-12-26 11:22:02 -07003460 return skip;
3461}
3462
3463void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3464 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3465 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003466 auto *cb_access_context = GetAccessContext(commandBuffer);
3467 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003468 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003469 auto *context = cb_access_context->GetCurrentAccessContext();
3470 assert(context);
3471
John Zulauf5c5e88d2019-12-26 11:22:02 -07003472 auto *src_image = Get<IMAGE_STATE>(srcImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003473 auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003474
3475 for (uint32_t region = 0; region < regionCount; region++) {
3476 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06003477 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003478 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3479 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003480 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003481 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003482 VkExtent3D dst_copy_extent =
3483 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003484 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3485 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003486 }
3487 }
3488}
3489
Jeff Leger178b1e52020-10-05 12:22:23 -04003490bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
3491 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
3492 bool skip = false;
3493 const auto *cb_access_context = GetAccessContext(commandBuffer);
3494 assert(cb_access_context);
3495 if (!cb_access_context) return skip;
3496
3497 const auto *context = cb_access_context->GetCurrentAccessContext();
3498 assert(context);
3499 if (!context) return skip;
3500
3501 const auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3502 const auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3503 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3504 const auto &copy_region = pCopyImageInfo->pRegions[region];
3505 if (src_image) {
3506 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
3507 copy_region.srcOffset, copy_region.extent);
3508 if (hazard.hazard) {
3509 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
3510 "vkCmdCopyImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
3511 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003512 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003513 }
3514 }
3515
3516 if (dst_image) {
3517 VkExtent3D dst_copy_extent =
3518 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
3519 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
3520 copy_region.dstOffset, dst_copy_extent);
3521 if (hazard.hazard) {
3522 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
3523 "vkCmdCopyImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
3524 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07003525 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003526 }
3527 if (skip) break;
3528 }
3529 }
3530
3531 return skip;
3532}
3533
3534void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
3535 auto *cb_access_context = GetAccessContext(commandBuffer);
3536 assert(cb_access_context);
3537 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE2KHR);
3538 auto *context = cb_access_context->GetCurrentAccessContext();
3539 assert(context);
3540
3541 auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3542 auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3543
3544 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3545 const auto &copy_region = pCopyImageInfo->pRegions[region];
3546 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003547 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
3548 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003549 }
3550 if (dst_image) {
3551 VkExtent3D dst_copy_extent =
3552 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf8e3c3e92021-01-06 11:19:36 -07003553 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3554 copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003555 }
3556 }
3557}
3558
John Zulauf9cb530d2019-09-30 14:14:10 -06003559bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3560 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3561 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3562 uint32_t bufferMemoryBarrierCount,
3563 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3564 uint32_t imageMemoryBarrierCount,
3565 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
3566 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003567 const auto *cb_access_context = GetAccessContext(commandBuffer);
3568 assert(cb_access_context);
3569 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07003570
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003571 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3572 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3573 imageMemoryBarrierCount, pImageMemoryBarriers);
3574 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06003575 return skip;
3576}
3577
3578void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3579 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3580 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3581 uint32_t bufferMemoryBarrierCount,
3582 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3583 uint32_t imageMemoryBarrierCount,
3584 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003585 auto *cb_access_context = GetAccessContext(commandBuffer);
3586 assert(cb_access_context);
3587 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06003588
John Zulaufe7f6a5e2021-01-16 14:31:18 -07003589 SyncOpPipelineBarrier pipeline_barrier(*this, cb_access_context->GetQueueFlags(), srcStageMask, dstStageMask, dependencyFlags,
3590 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
3591 imageMemoryBarrierCount, pImageMemoryBarriers);
3592 pipeline_barrier.Record(cb_access_context, cb_access_context->NextCommandTag(CMD_PIPELINEBARRIER));
John Zulauf9cb530d2019-09-30 14:14:10 -06003593}
3594
3595void SyncValidator::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
3596 const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
3597 // The state tracker sets up the device state
3598 StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result);
3599
John Zulauf5f13a792020-03-10 07:31:21 -06003600 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
3601 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06003602 // TODO: Find a good way to do this hooklessly.
3603 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
3604 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeSyncValidation);
3605 SyncValidator *sync_device_state = static_cast<SyncValidator *>(validation_data);
3606
John Zulaufd1f85d42020-04-15 12:23:15 -06003607 sync_device_state->SetCommandBufferResetCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3608 sync_device_state->ResetCommandBufferCallback(command_buffer);
3609 });
3610 sync_device_state->SetCommandBufferFreeCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3611 sync_device_state->FreeCommandBufferCallback(command_buffer);
3612 });
John Zulauf9cb530d2019-09-30 14:14:10 -06003613}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003614
John Zulauf355e49b2020-04-24 15:11:15 -06003615bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003616 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003617 bool skip = false;
3618 const auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
3619 auto cb_context = GetAccessContext(commandBuffer);
3620
3621 if (rp_state && cb_context) {
3622 skip |= cb_context->ValidateBeginRenderPass(*rp_state, pRenderPassBegin, pSubpassBeginInfo, func_name);
3623 }
3624
3625 return skip;
3626}
3627
3628bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3629 VkSubpassContents contents) const {
3630 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003631 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003632 subpass_begin_info.contents = contents;
3633 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, "vkCmdBeginRenderPass");
3634 return skip;
3635}
3636
3637bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003638 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003639 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3640 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2");
3641 return skip;
3642}
3643
3644bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3645 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003646 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003647 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3648 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2KHR");
3649 return skip;
3650}
3651
John Zulauf3d84f1b2020-03-09 13:33:25 -06003652void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
3653 VkResult result) {
3654 // The state tracker sets up the command buffer state
3655 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
3656
3657 // Create/initialize the structure that trackers accesses at the command buffer scope.
3658 auto cb_access_context = GetAccessContext(commandBuffer);
3659 assert(cb_access_context);
3660 cb_access_context->Reset();
3661}
3662
3663void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
John Zulauf355e49b2020-04-24 15:11:15 -06003664 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003665 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06003666 if (cb_context) {
3667 cb_context->RecordBeginRenderPass(cb_context->NextCommandTag(command));
John Zulauf3d84f1b2020-03-09 13:33:25 -06003668 }
3669}
3670
3671void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3672 VkSubpassContents contents) {
3673 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003674 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003675 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003676 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003677}
3678
3679void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3680 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3681 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003682 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003683}
3684
3685void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3686 const VkRenderPassBeginInfo *pRenderPassBegin,
3687 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3688 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003689 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
3690}
3691
Mike Schuchardt2df08912020-12-15 16:28:09 -08003692bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3693 const VkSubpassEndInfo *pSubpassEndInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003694 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->ValidateNextSubpass(func_name);
3705
3706 return skip;
3707}
3708
3709bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
3710 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003711 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06003712 subpass_begin_info.contents = contents;
3713 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, "vkCmdNextSubpass");
3714 return skip;
3715}
3716
Mike Schuchardt2df08912020-12-15 16:28:09 -08003717bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3718 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003719 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3720 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2KHR");
3721 return skip;
3722}
3723
3724bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3725 const VkSubpassEndInfo *pSubpassEndInfo) const {
3726 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3727 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2");
3728 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003729}
3730
3731void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003732 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003733 auto cb_context = GetAccessContext(commandBuffer);
3734 assert(cb_context);
3735 auto cb_state = cb_context->GetCommandBufferState();
3736 if (!cb_state) return;
3737
3738 auto rp_state = cb_state->activeRenderPass;
3739 if (!rp_state) return;
3740
John Zulauffaea0ee2021-01-14 14:01:32 -07003741 cb_context->RecordNextSubpass(*rp_state, command);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003742}
3743
3744void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
3745 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07003746 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06003747 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003748 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003749}
3750
3751void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3752 const VkSubpassEndInfo *pSubpassEndInfo) {
3753 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003754 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003755}
3756
3757void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3758 const VkSubpassEndInfo *pSubpassEndInfo) {
3759 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003760 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003761}
3762
Mike Schuchardt2df08912020-12-15 16:28:09 -08003763bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003764 const char *func_name) const {
3765 bool skip = false;
3766
3767 auto cb_context = GetAccessContext(commandBuffer);
3768 assert(cb_context);
3769 auto cb_state = cb_context->GetCommandBufferState();
3770 if (!cb_state) return skip;
3771
3772 auto rp_state = cb_state->activeRenderPass;
3773 if (!rp_state) return skip;
3774
3775 skip |= cb_context->ValidateEndRenderpass(func_name);
3776 return skip;
3777}
3778
3779bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3780 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
3781 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, "vkEndRenderPass");
3782 return skip;
3783}
3784
Mike Schuchardt2df08912020-12-15 16:28:09 -08003785bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003786 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3787 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2");
3788 return skip;
3789}
3790
3791bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003792 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003793 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3794 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2KHR");
3795 return skip;
3796}
3797
3798void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
3799 CMD_TYPE command) {
John Zulaufe5da6e52020-03-18 15:32:18 -06003800 // Resolve the all subpass contexts to the command buffer contexts
3801 auto cb_context = GetAccessContext(commandBuffer);
3802 assert(cb_context);
3803 auto cb_state = cb_context->GetCommandBufferState();
3804 if (!cb_state) return;
3805
locke-lunargaecf2152020-05-12 17:15:41 -06003806 const auto *rp_state = cb_state->activeRenderPass.get();
John Zulaufe5da6e52020-03-18 15:32:18 -06003807 if (!rp_state) return;
3808
John Zulauffaea0ee2021-01-14 14:01:32 -07003809 cb_context->RecordEndRenderPass(*rp_state, command);
John Zulaufe5da6e52020-03-18 15:32:18 -06003810}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003811
John Zulauf33fc1d52020-07-17 11:01:10 -06003812// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
3813// updates to a resource which do not conflict at the byte level.
3814// TODO: Revisit this rule to see if it needs to be tighter or looser
3815// TODO: Add programatic control over suppression heuristics
3816bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
3817 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
3818}
3819
John Zulauf3d84f1b2020-03-09 13:33:25 -06003820void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06003821 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06003822 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003823}
3824
3825void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003826 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003827 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003828}
3829
3830void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06003831 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06003832 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003833}
locke-lunarga19c71d2020-03-02 18:17:04 -07003834
Jeff Leger178b1e52020-10-05 12:22:23 -04003835template <typename BufferImageCopyRegionType>
3836bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3837 VkImageLayout dstImageLayout, uint32_t regionCount,
3838 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003839 bool skip = false;
3840 const auto *cb_access_context = GetAccessContext(commandBuffer);
3841 assert(cb_access_context);
3842 if (!cb_access_context) return skip;
3843
Jeff Leger178b1e52020-10-05 12:22:23 -04003844 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3845 const char *func_name = is_2khr ? "vkCmdCopyBufferToImage2KHR()" : "vkCmdCopyBufferToImage()";
3846
locke-lunarga19c71d2020-03-02 18:17:04 -07003847 const auto *context = cb_access_context->GetCurrentAccessContext();
3848 assert(context);
3849 if (!context) return skip;
3850
3851 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
locke-lunarga19c71d2020-03-02 18:17:04 -07003852 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
3853
3854 for (uint32_t region = 0; region < regionCount; region++) {
3855 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07003856 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07003857 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003858 if (src_buffer) {
3859 ResourceAccessRange src_range =
3860 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3861 hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3862 if (hazard.hazard) {
3863 // PHASE1 TODO -- add tag information to log msg when useful.
3864 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
3865 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3866 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003867 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003868 }
3869 }
3870
3871 hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource,
3872 copy_region.imageOffset, copy_region.imageExtent);
locke-lunarga19c71d2020-03-02 18:17:04 -07003873 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003874 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003875 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003876 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003877 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003878 }
3879 if (skip) break;
3880 }
3881 if (skip) break;
3882 }
3883 return skip;
3884}
3885
Jeff Leger178b1e52020-10-05 12:22:23 -04003886bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3887 VkImageLayout dstImageLayout, uint32_t regionCount,
3888 const VkBufferImageCopy *pRegions) const {
3889 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
3890 COPY_COMMAND_VERSION_1);
3891}
3892
3893bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3894 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
3895 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3896 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3897 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3898}
3899
3900template <typename BufferImageCopyRegionType>
3901void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3902 VkImageLayout dstImageLayout, uint32_t regionCount,
3903 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07003904 auto *cb_access_context = GetAccessContext(commandBuffer);
3905 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04003906
3907 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3908 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYBUFFERTOIMAGE2KHR : CMD_COPYBUFFERTOIMAGE;
3909
3910 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07003911 auto *context = cb_access_context->GetCurrentAccessContext();
3912 assert(context);
3913
3914 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf16adfc92020-04-08 10:28:33 -06003915 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07003916
3917 for (uint32_t region = 0; region < regionCount; region++) {
3918 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07003919 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07003920 if (src_buffer) {
3921 ResourceAccessRange src_range =
3922 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
3923 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
3924 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07003925 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
3926 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07003927 }
3928 }
3929}
3930
Jeff Leger178b1e52020-10-05 12:22:23 -04003931void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3932 VkImageLayout dstImageLayout, uint32_t regionCount,
3933 const VkBufferImageCopy *pRegions) {
3934 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
3935 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1);
3936}
3937
3938void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
3939 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
3940 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
3941 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
3942 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
3943 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
3944}
3945
3946template <typename BufferImageCopyRegionType>
3947bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3948 VkBuffer dstBuffer, uint32_t regionCount,
3949 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07003950 bool skip = false;
3951 const auto *cb_access_context = GetAccessContext(commandBuffer);
3952 assert(cb_access_context);
3953 if (!cb_access_context) return skip;
3954
Jeff Leger178b1e52020-10-05 12:22:23 -04003955 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
3956 const char *func_name = is_2khr ? "vkCmdCopyImageToBuffer2KHR()" : "vkCmdCopyImageToBuffer()";
3957
locke-lunarga19c71d2020-03-02 18:17:04 -07003958 const auto *context = cb_access_context->GetCurrentAccessContext();
3959 assert(context);
3960 if (!context) return skip;
3961
3962 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3963 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
3964 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
3965 for (uint32_t region = 0; region < regionCount; region++) {
3966 const auto &copy_region = pRegions[region];
3967 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003968 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07003969 copy_region.imageOffset, copy_region.imageExtent);
3970 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003971 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04003972 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06003973 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003974 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07003975 }
John Zulauf477700e2021-01-06 11:41:49 -07003976 if (dst_mem) {
3977 ResourceAccessRange dst_range =
3978 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
3979 hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3980 if (hazard.hazard) {
3981 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
3982 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
3983 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07003984 cb_access_context->FormatUsage(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07003985 }
locke-lunarga19c71d2020-03-02 18:17:04 -07003986 }
3987 }
3988 if (skip) break;
3989 }
3990 return skip;
3991}
3992
Jeff Leger178b1e52020-10-05 12:22:23 -04003993bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
3994 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
3995 const VkBufferImageCopy *pRegions) const {
3996 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
3997 COPY_COMMAND_VERSION_1);
3998}
3999
4000bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4001 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4002 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4003 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4004 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
4005}
4006
4007template <typename BufferImageCopyRegionType>
4008void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4009 VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions,
4010 CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004011 auto *cb_access_context = GetAccessContext(commandBuffer);
4012 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004013
4014 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
4015 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYIMAGETOBUFFER2KHR : CMD_COPYIMAGETOBUFFER;
4016
4017 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004018 auto *context = cb_access_context->GetCurrentAccessContext();
4019 assert(context);
4020
4021 const auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004022 auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4023 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 -06004024 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004025
4026 for (uint32_t region = 0; region < regionCount; region++) {
4027 const auto &copy_region = pRegions[region];
4028 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004029 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4030 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004031 if (dst_buffer) {
4032 ResourceAccessRange dst_range =
4033 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
4034 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
4035 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004036 }
4037 }
4038}
4039
Jeff Leger178b1e52020-10-05 12:22:23 -04004040void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4041 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4042 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
4043 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1);
4044}
4045
4046void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4047 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4048 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4049 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4050 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4051 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
4052}
4053
4054template <typename RegionType>
4055bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4056 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4057 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004058 bool skip = false;
4059 const auto *cb_access_context = GetAccessContext(commandBuffer);
4060 assert(cb_access_context);
4061 if (!cb_access_context) return skip;
4062
4063 const auto *context = cb_access_context->GetCurrentAccessContext();
4064 assert(context);
4065 if (!context) return skip;
4066
4067 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4068 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4069
4070 for (uint32_t region = 0; region < regionCount; region++) {
4071 const auto &blit_region = pRegions[region];
4072 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004073 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4074 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4075 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4076 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4077 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4078 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
4079 auto hazard =
4080 context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004081 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004082 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004083 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004084 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004085 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004086 }
4087 }
4088
4089 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004090 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4091 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4092 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4093 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4094 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4095 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
4096 auto hazard =
4097 context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004098 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004099 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004100 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004101 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004102 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004103 }
4104 if (skip) break;
4105 }
4106 }
4107
4108 return skip;
4109}
4110
Jeff Leger178b1e52020-10-05 12:22:23 -04004111bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4112 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4113 const VkImageBlit *pRegions, VkFilter filter) const {
4114 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4115 "vkCmdBlitImage");
4116}
4117
4118bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4119 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4120 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4121 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4122 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4123}
4124
4125template <typename RegionType>
4126void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4127 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4128 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004129 auto *cb_access_context = GetAccessContext(commandBuffer);
4130 assert(cb_access_context);
4131 auto *context = cb_access_context->GetCurrentAccessContext();
4132 assert(context);
4133
4134 auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004135 auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004136
4137 for (uint32_t region = 0; region < regionCount; region++) {
4138 const auto &blit_region = pRegions[region];
4139 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004140 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4141 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4142 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4143 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4144 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4145 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004146 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4147 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004148 }
4149 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004150 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4151 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4152 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4153 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4154 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4155 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
John Zulauf8e3c3e92021-01-06 11:19:36 -07004156 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4157 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004158 }
4159 }
4160}
locke-lunarg36ba2592020-04-03 09:42:04 -06004161
Jeff Leger178b1e52020-10-05 12:22:23 -04004162void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4163 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4164 const VkImageBlit *pRegions, VkFilter filter) {
4165 auto *cb_access_context = GetAccessContext(commandBuffer);
4166 assert(cb_access_context);
4167 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4168 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4169 pRegions, filter);
4170 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4171}
4172
4173void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4174 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4175 auto *cb_access_context = GetAccessContext(commandBuffer);
4176 assert(cb_access_context);
4177 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4178 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4179 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4180 pBlitImageInfo->filter, tag);
4181}
4182
John Zulauffaea0ee2021-01-14 14:01:32 -07004183bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4184 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4185 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4186 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004187 bool skip = false;
4188 if (drawCount == 0) return skip;
4189
4190 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4191 VkDeviceSize size = struct_size;
4192 if (drawCount == 1 || stride == size) {
4193 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004194 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004195 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4196 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004197 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004198 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004199 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004200 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004201 }
4202 } else {
4203 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004204 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004205 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4206 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004207 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004208 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4209 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004210 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004211 break;
4212 }
4213 }
4214 }
4215 return skip;
4216}
4217
locke-lunarg61870c22020-06-09 14:51:50 -06004218void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag &tag, const VkDeviceSize struct_size,
4219 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4220 uint32_t stride) {
locke-lunargff255f92020-05-13 18:53:52 -06004221 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4222 VkDeviceSize size = struct_size;
4223 if (drawCount == 1 || stride == size) {
4224 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004225 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004226 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004227 } else {
4228 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004229 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004230 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4231 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004232 }
4233 }
4234}
4235
John Zulauffaea0ee2021-01-14 14:01:32 -07004236bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4237 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4238 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004239 bool skip = false;
4240
4241 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004242 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004243 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4244 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004245 skip |= LogError(count_buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004246 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004247 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004248 cb_context.FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004249 }
4250 return skip;
4251}
4252
locke-lunarg61870c22020-06-09 14:51:50 -06004253void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag &tag, VkBuffer buffer, VkDeviceSize offset) {
locke-lunargff255f92020-05-13 18:53:52 -06004254 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004255 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004256 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004257}
4258
locke-lunarg36ba2592020-04-03 09:42:04 -06004259bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004260 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004261 const auto *cb_access_context = GetAccessContext(commandBuffer);
4262 assert(cb_access_context);
4263 if (!cb_access_context) return skip;
4264
locke-lunarg61870c22020-06-09 14:51:50 -06004265 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004266 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004267}
4268
4269void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004270 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004271 auto *cb_access_context = GetAccessContext(commandBuffer);
4272 assert(cb_access_context);
4273 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004274
locke-lunarg61870c22020-06-09 14:51:50 -06004275 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004276}
locke-lunarge1a67022020-04-29 00:15:36 -06004277
4278bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004279 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004280 const auto *cb_access_context = GetAccessContext(commandBuffer);
4281 assert(cb_access_context);
4282 if (!cb_access_context) return skip;
4283
4284 const auto *context = cb_access_context->GetCurrentAccessContext();
4285 assert(context);
4286 if (!context) return skip;
4287
locke-lunarg61870c22020-06-09 14:51:50 -06004288 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004289 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4290 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004291 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004292}
4293
4294void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004295 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004296 auto *cb_access_context = GetAccessContext(commandBuffer);
4297 assert(cb_access_context);
4298 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4299 auto *context = cb_access_context->GetCurrentAccessContext();
4300 assert(context);
4301
locke-lunarg61870c22020-06-09 14:51:50 -06004302 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4303 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004304}
4305
4306bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4307 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004308 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004309 const auto *cb_access_context = GetAccessContext(commandBuffer);
4310 assert(cb_access_context);
4311 if (!cb_access_context) return skip;
4312
locke-lunarg61870c22020-06-09 14:51:50 -06004313 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4314 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4315 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004316 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004317}
4318
4319void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4320 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004321 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004322 auto *cb_access_context = GetAccessContext(commandBuffer);
4323 assert(cb_access_context);
4324 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004325
locke-lunarg61870c22020-06-09 14:51:50 -06004326 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4327 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4328 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004329}
4330
4331bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4332 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004333 bool skip = false;
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
locke-lunarg61870c22020-06-09 14:51:50 -06004338 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4339 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4340 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004341 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004342}
4343
4344void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4345 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004346 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004347 auto *cb_access_context = GetAccessContext(commandBuffer);
4348 assert(cb_access_context);
4349 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004350
locke-lunarg61870c22020-06-09 14:51:50 -06004351 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4352 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4353 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004354}
4355
4356bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4357 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004358 bool skip = false;
4359 if (drawCount == 0) return skip;
4360
locke-lunargff255f92020-05-13 18:53:52 -06004361 const auto *cb_access_context = GetAccessContext(commandBuffer);
4362 assert(cb_access_context);
4363 if (!cb_access_context) return skip;
4364
4365 const auto *context = cb_access_context->GetCurrentAccessContext();
4366 assert(context);
4367 if (!context) return skip;
4368
locke-lunarg61870c22020-06-09 14:51:50 -06004369 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4370 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004371 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4372 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004373
4374 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4375 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4376 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004377 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004378 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004379}
4380
4381void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4382 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004383 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004384 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06004385 auto *cb_access_context = GetAccessContext(commandBuffer);
4386 assert(cb_access_context);
4387 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
4388 auto *context = cb_access_context->GetCurrentAccessContext();
4389 assert(context);
4390
locke-lunarg61870c22020-06-09 14:51:50 -06004391 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4392 cb_access_context->RecordDrawSubpassAttachment(tag);
4393 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004394
4395 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4396 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4397 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004398 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004399}
4400
4401bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4402 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004403 bool skip = false;
4404 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06004405 const auto *cb_access_context = GetAccessContext(commandBuffer);
4406 assert(cb_access_context);
4407 if (!cb_access_context) return skip;
4408
4409 const auto *context = cb_access_context->GetCurrentAccessContext();
4410 assert(context);
4411 if (!context) return skip;
4412
locke-lunarg61870c22020-06-09 14:51:50 -06004413 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
4414 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004415 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4416 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004417
4418 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4419 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4420 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004421 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004422 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004423}
4424
4425void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4426 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004427 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004428 auto *cb_access_context = GetAccessContext(commandBuffer);
4429 assert(cb_access_context);
4430 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
4431 auto *context = cb_access_context->GetCurrentAccessContext();
4432 assert(context);
4433
locke-lunarg61870c22020-06-09 14:51:50 -06004434 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4435 cb_access_context->RecordDrawSubpassAttachment(tag);
4436 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004437
4438 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4439 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4440 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004441 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004442}
4443
4444bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4445 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4446 uint32_t stride, const char *function) const {
4447 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004448 const auto *cb_access_context = GetAccessContext(commandBuffer);
4449 assert(cb_access_context);
4450 if (!cb_access_context) return skip;
4451
4452 const auto *context = cb_access_context->GetCurrentAccessContext();
4453 assert(context);
4454 if (!context) return skip;
4455
locke-lunarg61870c22020-06-09 14:51:50 -06004456 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4457 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004458 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4459 maxDrawCount, stride, function);
4460 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004461
4462 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4463 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4464 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004465 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004466 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004467}
4468
4469bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4470 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4471 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004472 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4473 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004474}
4475
4476void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4477 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4478 uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004479 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4480 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004481 auto *cb_access_context = GetAccessContext(commandBuffer);
4482 assert(cb_access_context);
4483 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECTCOUNT);
4484 auto *context = cb_access_context->GetCurrentAccessContext();
4485 assert(context);
4486
locke-lunarg61870c22020-06-09 14:51:50 -06004487 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4488 cb_access_context->RecordDrawSubpassAttachment(tag);
4489 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
4490 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004491
4492 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4493 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4494 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004495 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004496}
4497
4498bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4499 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4500 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004501 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4502 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004503}
4504
4505void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4506 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4507 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004508 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4509 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004510 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004511}
4512
4513bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4514 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4515 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004516 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4517 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004518}
4519
4520void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4521 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4522 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004523 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4524 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004525 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4526}
4527
4528bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4529 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4530 uint32_t stride, const char *function) const {
4531 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004532 const auto *cb_access_context = GetAccessContext(commandBuffer);
4533 assert(cb_access_context);
4534 if (!cb_access_context) return skip;
4535
4536 const auto *context = cb_access_context->GetCurrentAccessContext();
4537 assert(context);
4538 if (!context) return skip;
4539
locke-lunarg61870c22020-06-09 14:51:50 -06004540 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4541 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07004542 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
4543 offset, maxDrawCount, stride, function);
4544 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004545
4546 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4547 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4548 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004549 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004550 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004551}
4552
4553bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4554 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4555 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004556 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4557 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004558}
4559
4560void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4561 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4562 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004563 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4564 maxDrawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004565 auto *cb_access_context = GetAccessContext(commandBuffer);
4566 assert(cb_access_context);
4567 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECTCOUNT);
4568 auto *context = cb_access_context->GetCurrentAccessContext();
4569 assert(context);
4570
locke-lunarg61870c22020-06-09 14:51:50 -06004571 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4572 cb_access_context->RecordDrawSubpassAttachment(tag);
4573 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
4574 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004575
4576 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4577 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06004578 // We will update the index and vertex buffer in SubmitQueue in the future.
4579 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004580}
4581
4582bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
4583 VkDeviceSize offset, VkBuffer countBuffer,
4584 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4585 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004586 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4587 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004588}
4589
4590void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4591 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4592 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004593 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4594 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004595 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4596}
4597
4598bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
4599 VkDeviceSize offset, VkBuffer countBuffer,
4600 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4601 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004602 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4603 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004604}
4605
4606void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4607 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4608 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004609 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4610 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004611 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4612}
4613
4614bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4615 const VkClearColorValue *pColor, uint32_t rangeCount,
4616 const VkImageSubresourceRange *pRanges) const {
4617 bool skip = false;
4618 const auto *cb_access_context = GetAccessContext(commandBuffer);
4619 assert(cb_access_context);
4620 if (!cb_access_context) return skip;
4621
4622 const auto *context = cb_access_context->GetCurrentAccessContext();
4623 assert(context);
4624 if (!context) return skip;
4625
4626 const auto *image_state = Get<IMAGE_STATE>(image);
4627
4628 for (uint32_t index = 0; index < rangeCount; index++) {
4629 const auto &range = pRanges[index];
4630 if (image_state) {
4631 auto hazard =
4632 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4633 if (hazard.hazard) {
4634 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004635 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004636 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004637 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004638 }
4639 }
4640 }
4641 return skip;
4642}
4643
4644void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4645 const VkClearColorValue *pColor, uint32_t rangeCount,
4646 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004647 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004648 auto *cb_access_context = GetAccessContext(commandBuffer);
4649 assert(cb_access_context);
4650 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
4651 auto *context = cb_access_context->GetCurrentAccessContext();
4652 assert(context);
4653
4654 const auto *image_state = Get<IMAGE_STATE>(image);
4655
4656 for (uint32_t index = 0; index < rangeCount; index++) {
4657 const auto &range = pRanges[index];
4658 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004659 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4660 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004661 }
4662 }
4663}
4664
4665bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4666 VkImageLayout imageLayout,
4667 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4668 const VkImageSubresourceRange *pRanges) const {
4669 bool skip = false;
4670 const auto *cb_access_context = GetAccessContext(commandBuffer);
4671 assert(cb_access_context);
4672 if (!cb_access_context) return skip;
4673
4674 const auto *context = cb_access_context->GetCurrentAccessContext();
4675 assert(context);
4676 if (!context) return skip;
4677
4678 const auto *image_state = Get<IMAGE_STATE>(image);
4679
4680 for (uint32_t index = 0; index < rangeCount; index++) {
4681 const auto &range = pRanges[index];
4682 if (image_state) {
4683 auto hazard =
4684 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4685 if (hazard.hazard) {
4686 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004687 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004688 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauffaea0ee2021-01-14 14:01:32 -07004689 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004690 }
4691 }
4692 }
4693 return skip;
4694}
4695
4696void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4697 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4698 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004699 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004700 auto *cb_access_context = GetAccessContext(commandBuffer);
4701 assert(cb_access_context);
4702 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
4703 auto *context = cb_access_context->GetCurrentAccessContext();
4704 assert(context);
4705
4706 const auto *image_state = Get<IMAGE_STATE>(image);
4707
4708 for (uint32_t index = 0; index < rangeCount; index++) {
4709 const auto &range = pRanges[index];
4710 if (image_state) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004711 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, {0, 0, 0},
4712 image_state->createInfo.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004713 }
4714 }
4715}
4716
4717bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
4718 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
4719 VkDeviceSize dstOffset, VkDeviceSize stride,
4720 VkQueryResultFlags flags) const {
4721 bool skip = false;
4722 const auto *cb_access_context = GetAccessContext(commandBuffer);
4723 assert(cb_access_context);
4724 if (!cb_access_context) return skip;
4725
4726 const auto *context = cb_access_context->GetCurrentAccessContext();
4727 assert(context);
4728 if (!context) return skip;
4729
4730 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4731
4732 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004733 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
locke-lunarge1a67022020-04-29 00:15:36 -06004734 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4735 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004736 skip |=
4737 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4738 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004739 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004740 }
4741 }
locke-lunargff255f92020-05-13 18:53:52 -06004742
4743 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004744 return skip;
4745}
4746
4747void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
4748 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4749 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004750 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
4751 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06004752 auto *cb_access_context = GetAccessContext(commandBuffer);
4753 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06004754 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06004755 auto *context = cb_access_context->GetCurrentAccessContext();
4756 assert(context);
4757
4758 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4759
4760 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004761 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004762 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004763 }
locke-lunargff255f92020-05-13 18:53:52 -06004764
4765 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004766}
4767
4768bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4769 VkDeviceSize size, uint32_t data) const {
4770 bool skip = false;
4771 const auto *cb_access_context = GetAccessContext(commandBuffer);
4772 assert(cb_access_context);
4773 if (!cb_access_context) return skip;
4774
4775 const auto *context = cb_access_context->GetCurrentAccessContext();
4776 assert(context);
4777 if (!context) return skip;
4778
4779 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4780
4781 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004782 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
locke-lunarge1a67022020-04-29 00:15:36 -06004783 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4784 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004785 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004786 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004787 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004788 }
4789 }
4790 return skip;
4791}
4792
4793void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4794 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004795 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06004796 auto *cb_access_context = GetAccessContext(commandBuffer);
4797 assert(cb_access_context);
4798 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
4799 auto *context = cb_access_context->GetCurrentAccessContext();
4800 assert(context);
4801
4802 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4803
4804 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004805 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004806 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004807 }
4808}
4809
4810bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4811 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4812 const VkImageResolve *pRegions) const {
4813 bool skip = false;
4814 const auto *cb_access_context = GetAccessContext(commandBuffer);
4815 assert(cb_access_context);
4816 if (!cb_access_context) return skip;
4817
4818 const auto *context = cb_access_context->GetCurrentAccessContext();
4819 assert(context);
4820 if (!context) return skip;
4821
4822 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4823 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4824
4825 for (uint32_t region = 0; region < regionCount; region++) {
4826 const auto &resolve_region = pRegions[region];
4827 if (src_image) {
4828 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4829 resolve_region.srcOffset, resolve_region.extent);
4830 if (hazard.hazard) {
4831 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004832 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004833 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004834 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004835 }
4836 }
4837
4838 if (dst_image) {
4839 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4840 resolve_region.dstOffset, resolve_region.extent);
4841 if (hazard.hazard) {
4842 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004843 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004844 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauffaea0ee2021-01-14 14:01:32 -07004845 cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004846 }
4847 if (skip) break;
4848 }
4849 }
4850
4851 return skip;
4852}
4853
4854void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4855 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4856 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004857 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4858 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06004859 auto *cb_access_context = GetAccessContext(commandBuffer);
4860 assert(cb_access_context);
4861 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
4862 auto *context = cb_access_context->GetCurrentAccessContext();
4863 assert(context);
4864
4865 auto *src_image = Get<IMAGE_STATE>(srcImage);
4866 auto *dst_image = Get<IMAGE_STATE>(dstImage);
4867
4868 for (uint32_t region = 0; region < regionCount; region++) {
4869 const auto &resolve_region = pRegions[region];
4870 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004871 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4872 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004873 }
4874 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004875 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4876 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004877 }
4878 }
4879}
4880
Jeff Leger178b1e52020-10-05 12:22:23 -04004881bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4882 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
4883 bool skip = false;
4884 const auto *cb_access_context = GetAccessContext(commandBuffer);
4885 assert(cb_access_context);
4886 if (!cb_access_context) return skip;
4887
4888 const auto *context = cb_access_context->GetCurrentAccessContext();
4889 assert(context);
4890 if (!context) return skip;
4891
4892 const auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4893 const auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4894
4895 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4896 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4897 if (src_image) {
4898 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
4899 resolve_region.srcOffset, resolve_region.extent);
4900 if (hazard.hazard) {
4901 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
4902 "vkCmdResolveImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
4903 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004904 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004905 }
4906 }
4907
4908 if (dst_image) {
4909 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
4910 resolve_region.dstOffset, resolve_region.extent);
4911 if (hazard.hazard) {
4912 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
4913 "vkCmdResolveImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
4914 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauffaea0ee2021-01-14 14:01:32 -07004915 region, cb_access_context->FormatUsage(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004916 }
4917 if (skip) break;
4918 }
4919 }
4920
4921 return skip;
4922}
4923
4924void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4925 const VkResolveImageInfo2KHR *pResolveImageInfo) {
4926 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
4927 auto *cb_access_context = GetAccessContext(commandBuffer);
4928 assert(cb_access_context);
4929 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE2KHR);
4930 auto *context = cb_access_context->GetCurrentAccessContext();
4931 assert(context);
4932
4933 auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
4934 auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
4935
4936 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
4937 const auto &resolve_region = pResolveImageInfo->pRegions[region];
4938 if (src_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004939 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, SyncOrdering::kNonAttachment,
4940 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004941 }
4942 if (dst_image) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07004943 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
4944 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004945 }
4946 }
4947}
4948
locke-lunarge1a67022020-04-29 00:15:36 -06004949bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4950 VkDeviceSize dataSize, const void *pData) const {
4951 bool skip = false;
4952 const auto *cb_access_context = GetAccessContext(commandBuffer);
4953 assert(cb_access_context);
4954 if (!cb_access_context) return skip;
4955
4956 const auto *context = cb_access_context->GetCurrentAccessContext();
4957 assert(context);
4958 if (!context) return skip;
4959
4960 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4961
4962 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004963 // VK_WHOLE_SIZE not allowed
4964 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
locke-lunarge1a67022020-04-29 00:15:36 -06004965 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4966 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004967 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004968 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07004969 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004970 }
4971 }
4972 return skip;
4973}
4974
4975void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4976 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004977 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06004978 auto *cb_access_context = GetAccessContext(commandBuffer);
4979 assert(cb_access_context);
4980 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
4981 auto *context = cb_access_context->GetCurrentAccessContext();
4982 assert(context);
4983
4984 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4985
4986 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004987 // VK_WHOLE_SIZE not allowed
4988 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004989 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004990 }
4991}
locke-lunargff255f92020-05-13 18:53:52 -06004992
4993bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
4994 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
4995 bool skip = false;
4996 const auto *cb_access_context = GetAccessContext(commandBuffer);
4997 assert(cb_access_context);
4998 if (!cb_access_context) return skip;
4999
5000 const auto *context = cb_access_context->GetCurrentAccessContext();
5001 assert(context);
5002 if (!context) return skip;
5003
5004 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5005
5006 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005007 const ResourceAccessRange range = MakeRange(dstOffset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005008 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
5009 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005010 skip |=
5011 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5012 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauffaea0ee2021-01-14 14:01:32 -07005013 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatUsage(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005014 }
5015 }
5016 return skip;
5017}
5018
5019void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5020 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005021 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005022 auto *cb_access_context = GetAccessContext(commandBuffer);
5023 assert(cb_access_context);
5024 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5025 auto *context = cb_access_context->GetCurrentAccessContext();
5026 assert(context);
5027
5028 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5029
5030 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005031 const ResourceAccessRange range = MakeRange(dstOffset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005032 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005033 }
5034}
John Zulauf49beb112020-11-04 16:06:31 -07005035
5036bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5037 bool skip = false;
5038 const auto *cb_context = GetAccessContext(commandBuffer);
5039 assert(cb_context);
5040 if (!cb_context) return skip;
5041
5042 return cb_context->ValidateSetEvent(commandBuffer, event, stageMask);
5043}
5044
5045void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5046 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5047 auto *cb_context = GetAccessContext(commandBuffer);
5048 assert(cb_context);
5049 if (!cb_context) return;
John Zulauf4a6105a2020-11-17 15:11:05 -07005050 const auto tag = cb_context->NextCommandTag(CMD_SETEVENT);
5051 cb_context->RecordSetEvent(commandBuffer, event, stageMask, tag);
John Zulauf49beb112020-11-04 16:06:31 -07005052}
5053
5054bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5055 VkPipelineStageFlags stageMask) const {
5056 bool skip = false;
5057 const auto *cb_context = GetAccessContext(commandBuffer);
5058 assert(cb_context);
5059 if (!cb_context) return skip;
5060
5061 return cb_context->ValidateResetEvent(commandBuffer, event, stageMask);
5062}
5063
5064void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5065 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5066 auto *cb_context = GetAccessContext(commandBuffer);
5067 assert(cb_context);
5068 if (!cb_context) return;
5069
5070 cb_context->RecordResetEvent(commandBuffer, event, stageMask);
5071}
5072
5073bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5074 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5075 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5076 uint32_t bufferMemoryBarrierCount,
5077 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5078 uint32_t imageMemoryBarrierCount,
5079 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5080 bool skip = false;
5081 const auto *cb_context = GetAccessContext(commandBuffer);
5082 assert(cb_context);
5083 if (!cb_context) return skip;
5084
John Zulaufd5115702021-01-18 12:34:33 -07005085 SyncOpWaitEvents wait_events_op(*cb_context, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
5086 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5087 imageMemoryBarrierCount, pImageMemoryBarriers);
5088 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005089}
5090
5091void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5092 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5093 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5094 uint32_t bufferMemoryBarrierCount,
5095 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5096 uint32_t imageMemoryBarrierCount,
5097 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5098 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5099 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5100 imageMemoryBarrierCount, pImageMemoryBarriers);
5101
5102 auto *cb_context = GetAccessContext(commandBuffer);
5103 assert(cb_context);
5104 if (!cb_context) return;
5105
John Zulauf4a6105a2020-11-17 15:11:05 -07005106 const auto tag = cb_context->NextCommandTag(CMD_WAITEVENTS);
John Zulaufd5115702021-01-18 12:34:33 -07005107 SyncOpWaitEvents wait_events_op(*cb_context, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask,
5108 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5109 imageMemoryBarrierCount, pImageMemoryBarriers);
5110 return wait_events_op.Record(cb_context, tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07005111}
5112
5113void SyncEventState::ResetFirstScope() {
5114 for (const auto address_type : kAddressTypes) {
5115 first_scope[static_cast<size_t>(address_type)].clear();
5116 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005117 scope = SyncExecScope();
John Zulauf4a6105a2020-11-17 15:11:05 -07005118}
5119
5120// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
5121SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(VkPipelineStageFlags srcStageMask) const {
5122 IgnoreReason reason = NotIgnored;
5123
5124 if (last_command == CMD_RESETEVENT && !HasBarrier(0U, 0U)) {
5125 reason = ResetWaitRace;
5126 } else if (unsynchronized_set) {
5127 reason = SetRace;
5128 } else {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005129 const VkPipelineStageFlags missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005130 if (missing_bits) reason = MissingStageBits;
5131 }
5132
5133 return reason;
5134}
5135
5136bool SyncEventState::HasBarrier(VkPipelineStageFlags stageMask, VkPipelineStageFlags exec_scope_arg) const {
5137 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5138 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5139 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005140}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005141
John Zulaufd5115702021-01-18 12:34:33 -07005142SyncOpBarriers::SyncOpBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags, VkPipelineStageFlags srcStageMask,
5143 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5144 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5145 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5146 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005147 : dependency_flags_(dependencyFlags),
5148 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, srcStageMask)),
5149 dst_exec_scope_(SyncExecScope::MakeDst(queue_flags, dstStageMask)) {
5150 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5151 MakeMemoryBarriers(src_exec_scope_, dst_exec_scope_, dependencyFlags, memoryBarrierCount, pMemoryBarriers);
5152 MakeBufferMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, bufferMemoryBarrierCount,
5153 pBufferMemoryBarriers);
5154 MakeImageMemoryBarriers(sync_state, src_exec_scope_, dst_exec_scope_, dependencyFlags, imageMemoryBarrierCount,
5155 pImageMemoryBarriers);
5156}
5157
John Zulaufd5115702021-01-18 12:34:33 -07005158SyncOpPipelineBarrier::SyncOpPipelineBarrier(const SyncValidator &sync_state, VkQueueFlags queue_flags,
5159 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5160 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5161 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5162 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5163 const VkImageMemoryBarrier *pImageMemoryBarriers)
5164 : SyncOpBarriers(sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
5165 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5166
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005167bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
5168 bool skip = false;
5169 const auto *context = cb_context.GetCurrentAccessContext();
5170 assert(context);
5171 if (!context) return skip;
5172 // Validate Image Layout transitions
5173 for (const auto image_barrier : image_memory_barriers_) {
5174 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
5175 const auto *image_state = image_barrier.image.get();
5176 if (!image_state) continue;
5177 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
5178 if (hazard.hazard) {
5179 // PHASE1 TODO -- add tag information to log msg when useful.
5180 const auto &sync_state = cb_context.GetSyncState();
5181 const auto image_handle = image_state->image;
5182 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
5183 "vkCmdPipelineBarrier: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.",
5184 string_SyncHazard(hazard.hazard), image_barrier.index,
5185 sync_state.report_data->FormatHandle(image_handle).c_str(),
5186 cb_context.FormatUsage(hazard).c_str());
5187 }
5188 }
5189
5190 return skip;
5191}
5192
John Zulaufd5115702021-01-18 12:34:33 -07005193struct SyncOpPipelineBarrierFunctorFactory {
5194 using BarrierOpFunctor = PipelineBarrierOp;
5195 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5196 using GlobalBarrierOpFunctor = PipelineBarrierOp;
5197 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5198 using BufferRange = ResourceAccessRange;
5199 using ImageRange = subresource_adapter::ImageRangeGenerator;
5200 using GlobalRange = ResourceAccessRange;
5201
5202 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier, bool layout_transition) const {
5203 return ApplyFunctor(BarrierOpFunctor(barrier, layout_transition));
5204 }
5205 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5206 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
5207 }
5208 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier) const {
5209 return GlobalBarrierOpFunctor(barrier, false);
5210 }
5211
5212 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
5213 if (!SimpleBinding(buffer)) return ResourceAccessRange();
5214 const auto base_address = ResourceBaseAddress(buffer);
5215 return (range + base_address);
5216 }
5217 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5218 if (!SimpleBinding(image)) subresource_adapter::ImageRangeGenerator();
5219
5220 const auto base_address = ResourceBaseAddress(image);
5221 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), range.subresource_range, range.offset,
5222 range.extent, base_address);
5223 return range_gen;
5224 }
5225 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
5226};
5227
5228template <typename Barriers, typename FunctorFactory>
5229void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5230 AccessContext *context) {
5231 for (const auto &barrier : barriers) {
5232 const auto *state = barrier.GetState();
5233 if (state) {
5234 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
5235 auto update_action = factory.MakeApplyFunctor(barrier.barrier, barrier.IsLayoutTransition());
5236 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
5237 UpdateMemoryAccessState(accesses, update_action, &range_gen);
5238 }
5239 }
5240}
5241
5242template <typename Barriers, typename FunctorFactory>
5243void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag &tag,
5244 AccessContext *access_context) {
5245 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
5246 for (const auto &barrier : barriers) {
5247 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(barrier));
5248 }
5249 for (const auto address_type : kAddressTypes) {
5250 auto range_gen = factory.MakeGlobalRangeGen(address_type);
5251 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
5252 }
5253}
5254
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005255void SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07005256 SyncOpPipelineBarrierFunctorFactory factory;
5257 auto *access_context = cb_context->GetCurrentAccessContext();
5258 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5259 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5260 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005261
5262 cb_context->ApplyGlobalBarriersToEvents(src_exec_scope_, dst_exec_scope_);
5263}
5264
John Zulaufd5115702021-01-18 12:34:33 -07005265void SyncOpBarriers::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst, VkDependencyFlags dependency_flags,
5266 uint32_t memory_barrier_count, const VkMemoryBarrier *memory_barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005267 memory_barriers_.reserve(std::min<uint32_t>(1, memory_barrier_count));
5268 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
5269 const auto &barrier = memory_barriers[barrier_index];
5270 SyncBarrier sync_barrier(barrier, src, dst);
5271 memory_barriers_.emplace_back(sync_barrier);
5272 }
5273 if (0 == memory_barrier_count) {
5274 // If there are no global memory barriers, force an exec barrier
5275 memory_barriers_.emplace_back(SyncBarrier(src, dst));
5276 }
5277}
5278
John Zulaufd5115702021-01-18 12:34:33 -07005279void SyncOpBarriers::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5280 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5281 const VkBufferMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005282 buffer_memory_barriers_.reserve(barrier_count);
5283 for (uint32_t index = 0; index < barrier_count; index++) {
5284 const auto &barrier = barriers[index];
5285 auto buffer = sync_state.GetShared<BUFFER_STATE>(barrier.buffer);
5286 if (buffer) {
5287 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
5288 const auto range = MakeRange(barrier.offset, barrier_size);
5289 const SyncBarrier sync_barrier(barrier, src, dst);
5290 buffer_memory_barriers_.emplace_back(buffer, sync_barrier, range);
5291 } else {
5292 buffer_memory_barriers_.emplace_back();
5293 }
5294 }
5295}
5296
John Zulaufd5115702021-01-18 12:34:33 -07005297void SyncOpBarriers::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src, const SyncExecScope &dst,
5298 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
5299 const VkImageMemoryBarrier *barriers) {
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005300 image_memory_barriers_.reserve(barrier_count);
5301 for (uint32_t index = 0; index < barrier_count; index++) {
5302 const auto &barrier = barriers[index];
5303 const auto image = sync_state.GetShared<IMAGE_STATE>(barrier.image);
5304 if (image) {
5305 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
5306 const SyncBarrier sync_barrier(barrier, src, dst);
5307 image_memory_barriers_.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout,
5308 subresource_range);
5309 } else {
5310 image_memory_barriers_.emplace_back();
5311 image_memory_barriers_.back().index = index; // Just in case we're interested in the ones we skipped.
5312 }
5313 }
5314}
John Zulaufd5115702021-01-18 12:34:33 -07005315
5316SyncOpWaitEvents::SyncOpWaitEvents(const CommandBufferAccessContext &cb_context, VkQueueFlags queue_flags, uint32_t eventCount,
5317 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5318 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5319 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5320 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
5321 : SyncOpBarriers(cb_context.GetSyncState(), queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
5322 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
5323 pImageMemoryBarriers) {
5324 MakeEventsList(cb_context, eventCount, pEvents);
5325}
5326
5327bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
5328 const auto cmd = CMD_WAITEVENTS;
5329 const char *const ignored = "Wait operation is ignored for this event.";
5330 bool skip = false;
5331 const auto &sync_state = cb_context.GetSyncState();
5332 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer;
5333
5334 if (src_exec_scope_.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
5335 const char *const cmd_name = CommandTypeString(cmd);
5336 const char *const vuid = "SYNC-vkCmdWaitEvents-hostevent-unsupported";
5337 skip = sync_state.LogInfo(command_buffer_handle, vuid,
5338 "%s, srcStageMask includes %s, unsupported by synchronization validaton.", cmd_name,
5339 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT), ignored);
5340 }
5341
5342 VkPipelineStageFlags event_stage_masks = 0U;
5343 bool events_not_found = false;
5344 for (const auto &sync_event_shared : events_) {
5345 const auto sync_event = sync_event_shared.get();
5346 if (!sync_event) {
5347 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
5348 events_not_found = true; // Demote "extra_stage_bits" error to warning, to avoid false positives.
5349
5350 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
5351 }
5352 const auto event = sync_event->event->event;
5353 // TODO add "destroyed" checks
5354
5355 event_stage_masks |= sync_event->scope.mask_param;
5356 const auto ignore_reason = sync_event->IsIgnoredByWait(src_exec_scope_.mask_param);
5357 if (ignore_reason) {
5358 switch (ignore_reason) {
5359 case SyncEventState::ResetWaitRace: {
5360 const char *const cmd_name = CommandTypeString(cmd);
5361 const char *const vuid = "SYNC-vkCmdWaitEvents-missingbarrier-reset";
5362 const char *const message =
5363 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
5364 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5365 cmd_name, CommandTypeString(sync_event->last_command), ignored);
5366 break;
5367 }
5368 case SyncEventState::SetRace: {
5369 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for this
5370 // event
5371 const char *const cmd_name = CommandTypeString(cmd);
5372 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
5373 const char *const message =
5374 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, % %s";
5375 const char *const reason = "First synchronization scope is undefined.";
5376 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5377 CommandTypeString(sync_event->last_command), reason, ignored);
5378 break;
5379 }
5380 case SyncEventState::MissingStageBits: {
5381 const VkPipelineStageFlags missing_bits = sync_event->scope.mask_param & ~src_exec_scope_.mask_param;
5382 // Issue error message that event waited for is not in wait events scope
5383 const char *const cmd_name = CommandTypeString(cmd);
5384 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5385 const char *const message =
5386 "%s: %s stageMask 0x%" PRIx32 " includes bits not present in srcStageMask 0x%" PRIx32
5387 ". Bits missing from srcStageMask %s. %s";
5388 skip |= sync_state.LogError(event, vuid, message, cmd_name, sync_state.report_data->FormatHandle(event).c_str(),
5389 sync_event->scope.mask_param, src_exec_scope_.mask_param,
5390 string_VkPipelineStageFlags(missing_bits).c_str(), ignored);
5391 break;
5392 }
5393 default:
5394 assert(ignore_reason == SyncEventState::NotIgnored);
5395 }
5396 } else if (image_memory_barriers_.size()) {
5397 const auto *context = cb_context.GetCurrentAccessContext();
5398 assert(context);
5399 for (const auto &image_memory_barrier : image_memory_barriers_) {
5400 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
5401 const auto *image_state = image_memory_barrier.image.get();
5402 if (!image_state) continue;
5403 const auto &subresource_range = image_memory_barrier.range.subresource_range;
5404 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
5405 const auto hazard =
5406 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
5407 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
5408 if (hazard.hazard) {
5409 const char *const cmd_name = CommandTypeString(cmd);
5410 skip |= sync_state.LogError(image_state->image, string_SyncHazardVUID(hazard.hazard),
5411 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", cmd_name,
5412 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
5413 sync_state.report_data->FormatHandle(image_state->image).c_str(),
5414 cb_context.FormatUsage(hazard).c_str());
5415 break;
5416 }
5417 }
5418 }
5419 }
5420
5421 // Note that we can't check for HOST in pEvents as we don't track that set event type
5422 const auto extra_stage_bits = (src_exec_scope_.mask_param & ~VK_PIPELINE_STAGE_HOST_BIT) & ~event_stage_masks;
5423 if (extra_stage_bits) {
5424 // Issue error message that event waited for is not in wait events scope
5425 const char *const cmd_name = CommandTypeString(cmd);
5426 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
5427 const char *const message =
5428 "%s: srcStageMask 0x%" PRIx32 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
5429 if (events_not_found) {
5430 skip |= sync_state.LogInfo(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5431 string_VkPipelineStageFlags(extra_stage_bits).c_str(),
5432 " vkCmdSetEvent may be in previously submitted command buffer.");
5433 } else {
5434 skip |= sync_state.LogError(command_buffer_handle, vuid, message, cmd_name, src_exec_scope_.mask_param,
5435 string_VkPipelineStageFlags(extra_stage_bits).c_str(), "");
5436 }
5437 }
5438 return skip;
5439}
5440
5441struct SyncOpWaitEventsFunctorFactory {
5442 using BarrierOpFunctor = WaitEventBarrierOp;
5443 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
5444 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
5445 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
5446 using BufferRange = EventSimpleRangeGenerator;
5447 using ImageRange = EventImageRangeGenerator;
5448 using GlobalRange = EventSimpleRangeGenerator;
5449
5450 // Need to restrict to only valid exec and access scope for this event
5451 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
5452 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
5453 barrier.src_exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope;
5454 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
5455 return barrier;
5456 }
5457 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier_arg, bool layout_transition) const {
5458 auto barrier = RestrictToEvent(barrier_arg);
5459 return ApplyFunctor(BarrierOpFunctor(sync_event->first_scope_tag, barrier, layout_transition));
5460 }
5461 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, const ResourceUsageTag &tag) const {
5462 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
5463 }
5464 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier_arg) const {
5465 auto barrier = RestrictToEvent(barrier_arg);
5466 return GlobalBarrierOpFunctor(sync_event->first_scope_tag, barrier, false);
5467 }
5468
5469 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
5470 const AccessAddressType address_type = GetAccessAddressType(buffer);
5471 const auto base_address = ResourceBaseAddress(buffer);
5472 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
5473 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
5474 return filtered_range_gen;
5475 }
5476 ImageRange MakeRangeGen(const IMAGE_STATE &image, const SyncImageMemoryBarrier::SubImageRange &range) const {
5477 if (!SimpleBinding(image)) return ImageRange();
5478 const auto address_type = GetAccessAddressType(image);
5479 const auto base_address = ResourceBaseAddress(image);
5480 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), range.subresource_range,
5481 range.offset, range.extent, base_address);
5482 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
5483
5484 return filtered_range_gen;
5485 }
5486 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
5487 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
5488 }
5489 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
5490 SyncEventState *sync_event;
5491};
5492
5493void SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context, const ResourceUsageTag &tag) const {
5494 auto *access_context = cb_context->GetCurrentAccessContext();
5495 assert(access_context);
5496 if (!access_context) return;
5497
5498 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
5499 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
5500 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
5501 access_context->ResolvePreviousAccesses();
5502
5503 const auto &dst = dst_exec_scope_;
5504 // TODO... this needs change the SyncEventContext it's using depending on whether this is replay... the recorded
5505 // sync_event will be in the recorded context, but we need to update the sync_events in the current context....
5506 for (auto &sync_event_shared : events_) {
5507 const auto sync_event = sync_event_shared.get();
5508 if (!sync_event) continue;
5509
5510 sync_event->last_command = CMD_WAITEVENTS;
5511
5512 if (!sync_event->IsIgnoredByWait(src_exec_scope_.mask_param)) {
5513 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
5514 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
5515 // of the barriers is maintained.
5516 SyncOpWaitEventsFunctorFactory factory(sync_event);
5517 ApplyBarriers(buffer_memory_barriers_, factory, tag, access_context);
5518 ApplyBarriers(image_memory_barriers_, factory, tag, access_context);
5519 ApplyGlobalBarriers(memory_barriers_, factory, tag, access_context);
5520
5521 // Apply the global barrier to the event itself (for race condition tracking)
5522 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
5523 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
5524 sync_event->barriers |= dst.exec_scope;
5525 } else {
5526 // We ignored this wait, so we don't have any effective synchronization barriers for it.
5527 sync_event->barriers = 0U;
5528 }
5529 }
5530
5531 // Apply the pending barriers
5532 ResolvePendingBarrierFunctor apply_pending_action(tag);
5533 access_context->ApplyToContext(apply_pending_action);
5534}
5535
5536void SyncOpWaitEvents::MakeEventsList(const CommandBufferAccessContext &cb_context, uint32_t event_count, const VkEvent *events) {
5537 events_.reserve(event_count);
5538 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
5539 events_.emplace_back(cb_context.GetEventStateConstCastShared(events[event_index]));
5540 }
5541}