blob: efe3ee7f77ac21fc098d4f53edffe589ab47cbd3 [file] [log] [blame]
locke-lunarg8ec19162020-06-16 18:48:34 -06001/* Copyright (c) 2019-2020 The Khronos Group Inc.
2 * Copyright (c) 2019-2020 Valve Corporation
3 * Copyright (c) 2019-2020 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>
18 */
19
20#include <limits>
21#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060022#include <memory>
23#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060024#include "synchronization_validation.h"
25
John Zulauf43cc7462020-12-03 12:33:12 -070026const static std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
27 AccessAddressType::kLinear, AccessAddressType::kIdealized};
28
John Zulauf9cb530d2019-09-30 14:14:10 -060029static const char *string_SyncHazardVUID(SyncHazard hazard) {
30 switch (hazard) {
31 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070032 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060033 break;
34 case SyncHazard::READ_AFTER_WRITE:
35 return "SYNC-HAZARD-READ_AFTER_WRITE";
36 break;
37 case SyncHazard::WRITE_AFTER_READ:
38 return "SYNC-HAZARD-WRITE_AFTER_READ";
39 break;
40 case SyncHazard::WRITE_AFTER_WRITE:
41 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
42 break;
John Zulauf2f952d22020-02-10 11:34:51 -070043 case SyncHazard::READ_RACING_WRITE:
44 return "SYNC-HAZARD-READ-RACING-WRITE";
45 break;
46 case SyncHazard::WRITE_RACING_WRITE:
47 return "SYNC-HAZARD-WRITE-RACING-WRITE";
48 break;
49 case SyncHazard::WRITE_RACING_READ:
50 return "SYNC-HAZARD-WRITE-RACING-READ";
51 break;
John Zulauf9cb530d2019-09-30 14:14:10 -060052 default:
53 assert(0);
54 }
55 return "SYNC-HAZARD-INVALID";
56}
57
John Zulauf59e25072020-07-17 10:55:21 -060058static bool IsHazardVsRead(SyncHazard hazard) {
59 switch (hazard) {
60 case SyncHazard::NONE:
61 return false;
62 break;
63 case SyncHazard::READ_AFTER_WRITE:
64 return false;
65 break;
66 case SyncHazard::WRITE_AFTER_READ:
67 return true;
68 break;
69 case SyncHazard::WRITE_AFTER_WRITE:
70 return false;
71 break;
72 case SyncHazard::READ_RACING_WRITE:
73 return false;
74 break;
75 case SyncHazard::WRITE_RACING_WRITE:
76 return false;
77 break;
78 case SyncHazard::WRITE_RACING_READ:
79 return true;
80 break;
81 default:
82 assert(0);
83 }
84 return false;
85}
86
John Zulauf9cb530d2019-09-30 14:14:10 -060087static const char *string_SyncHazard(SyncHazard hazard) {
88 switch (hazard) {
89 case SyncHazard::NONE:
90 return "NONR";
91 break;
92 case SyncHazard::READ_AFTER_WRITE:
93 return "READ_AFTER_WRITE";
94 break;
95 case SyncHazard::WRITE_AFTER_READ:
96 return "WRITE_AFTER_READ";
97 break;
98 case SyncHazard::WRITE_AFTER_WRITE:
99 return "WRITE_AFTER_WRITE";
100 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700101 case SyncHazard::READ_RACING_WRITE:
102 return "READ_RACING_WRITE";
103 break;
104 case SyncHazard::WRITE_RACING_WRITE:
105 return "WRITE_RACING_WRITE";
106 break;
107 case SyncHazard::WRITE_RACING_READ:
108 return "WRITE_RACING_READ";
109 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600110 default:
111 assert(0);
112 }
113 return "INVALID HAZARD";
114}
115
John Zulauf37ceaed2020-07-03 16:18:15 -0600116static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
117 // Return the info for the first bit found
118 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700119 for (size_t i = 0; i < flags.size(); i++) {
120 if (flags.test(i)) {
121 info = &syncStageAccessInfoByStageAccessIndex[i];
122 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600123 }
124 }
125 return info;
126}
127
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700128static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600129 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700130 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600131 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700132 } else {
133 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
134 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
135 if ((flags & info.stage_access_bit).any()) {
136 if (!out_str.empty()) {
137 out_str.append(sep);
138 }
139 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600140 }
John Zulauf59e25072020-07-17 10:55:21 -0600141 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700142 if (out_str.length() == 0) {
143 out_str.append("Unhandled SyncStageAccess");
144 }
John Zulauf59e25072020-07-17 10:55:21 -0600145 }
146 return out_str;
147}
148
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700149static std::string string_UsageTag(const ResourceUsageTag &tag) {
150 std::stringstream out;
151
152 out << "command: " << CommandTypeString(tag.command);
153 out << ", seq_no: " << ((tag.index >> 1) & UINT32_MAX) << ", reset_no: " << (tag.index >> 33);
154 if (tag.index & 1) {
155 out << ", subcmd: " << (tag.index & 1);
156 }
157 return out.str();
158}
159
John Zulauf37ceaed2020-07-03 16:18:15 -0600160static std::string string_UsageTag(const HazardResult &hazard) {
161 const auto &tag = hazard.tag;
John Zulauf59e25072020-07-17 10:55:21 -0600162 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
163 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
John Zulauf1dae9192020-06-16 15:46:44 -0600164 std::stringstream out;
John Zulauf37ceaed2020-07-03 16:18:15 -0600165 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
166 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
John Zulauf59e25072020-07-17 10:55:21 -0600167 out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name;
168 if (IsHazardVsRead(hazard.hazard)) {
169 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
170 out << ", read_barriers: " << string_VkPipelineStageFlags(barriers);
171 } else {
172 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
173 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
174 }
175
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700176 out << ", " << string_UsageTag(tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600177 return out.str();
178}
179
John Zulaufd14743a2020-07-03 09:42:39 -0600180// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
181// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
182// also reflects this special case for read hazard detection (using access instead of exec scope)
John Zulaufb027cdb2020-05-21 14:25:22 -0600183static constexpr VkPipelineStageFlags kColorAttachmentExecScope = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700184static const SyncStageAccessFlags kColorAttachmentAccessScope =
185 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
186 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
187 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
188 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
John Zulaufb027cdb2020-05-21 14:25:22 -0600189static constexpr VkPipelineStageFlags kDepthStencilAttachmentExecScope =
190 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700191static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
192 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
193 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_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 -0600195
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700196static const SyncOrderingBarrier kColorAttachmentRasterOrder = {kColorAttachmentExecScope, kColorAttachmentAccessScope};
197static const SyncOrderingBarrier kDepthStencilAttachmentRasterOrder = {kDepthStencilAttachmentExecScope,
198 kDepthStencilAttachmentAccessScope};
199static const SyncOrderingBarrier kAttachmentRasterOrder = {kDepthStencilAttachmentExecScope | kColorAttachmentExecScope,
200 kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope};
John Zulauf7635de32020-05-29 17:14:15 -0600201// Sometimes we have an internal access conflict, and we using the kCurrentCommandTag to set and detect in temporary/proxy contexts
John Zulaufcc6fecb2020-06-17 15:24:54 -0600202static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, CMD_NONE);
John Zulaufb027cdb2020-05-21 14:25:22 -0600203
John Zulaufb02c1eb2020-10-06 16:33:36 -0600204static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) {
205 return bindable.binding.offset + bindable.binding.mem_state->fake_base_address;
206}
207
208static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; }
209
locke-lunarg3c038002020-04-30 23:08:08 -0600210inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
211 if (size == VK_WHOLE_SIZE) {
212 return (whole_size - offset);
213 }
214 return size;
215}
216
John Zulauf3e86bf02020-09-12 10:47:57 -0600217static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
218 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
219}
220
John Zulauf16adfc92020-04-08 10:28:33 -0600221template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600222static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600223 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
224}
225
John Zulauf355e49b2020-04-24 15:11:15 -0600226static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600227
John Zulauf3e86bf02020-09-12 10:47:57 -0600228static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
229 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
230}
231
232static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
233 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
234}
235
John Zulauf4a6105a2020-11-17 15:11:05 -0700236// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
237//
238// Usage:
239// Constructor() -- initializes the generator to point to the begin of the space declared.
240// * -- the current range of the generator empty signfies end
241// ++ -- advance to the next non-empty range (or end)
242
243// A wrapper for a single range with the same semantics as the actual generators below
244template <typename KeyType>
245class SingleRangeGenerator {
246 public:
247 SingleRangeGenerator(const KeyType &range) : current_(range) {}
248 KeyType &operator*() const { return *current_; }
249 KeyType *operator->() const { return &*current_; }
250 SingleRangeGenerator &operator++() {
251 current_ = KeyType(); // just one real range
252 return *this;
253 }
254
255 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
256
257 private:
258 SingleRangeGenerator() = default;
259 const KeyType range_;
260 KeyType current_;
261};
262
263// Generate the ranges that are the intersection of range and the entries in the FilterMap
264template <typename FilterMap, typename KeyType = typename FilterMap::key_type>
265class FilteredRangeGenerator {
266 public:
267 FilteredRangeGenerator(const FilterMap &filter, const KeyType &range)
268 : range_(range), filter_(&filter), filter_pos_(), current_() {
269 SeekBegin();
270 }
271 const KeyType &operator*() const { return current_; }
272 const KeyType *operator->() const { return &current_; }
273 FilteredRangeGenerator &operator++() {
274 ++filter_pos_;
275 UpdateCurrent();
276 return *this;
277 }
278
279 bool operator==(const FilteredRangeGenerator &other) const { return current_ == other.current_; }
280
281 private:
282 FilteredRangeGenerator() = default;
283 void UpdateCurrent() {
284 if (filter_pos_ != filter_->cend()) {
285 current_ = range_ & filter_pos_->first;
286 } else {
287 current_ = KeyType();
288 }
289 }
290 void SeekBegin() {
291 filter_pos_ = filter_->lower_bound(range_);
292 UpdateCurrent();
293 }
294 const KeyType range_;
295 const FilterMap *filter_;
296 typename FilterMap::const_iterator filter_pos_;
297 KeyType current_;
298};
299using EventSimpleRangeGenerator = FilteredRangeGenerator<SyncEventState::ScopeMap>;
300
301// Templated to allow for different Range generators or map sources...
302
303// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
304// Note that begin *cannot* reset RangeGen (image range generation currently doesn't support it), so you can only iterate over
305// this generator once.
306template <typename FilterMap, typename RangeGen, typename KeyType = typename FilterMap::key_type>
307class FilteredGeneratorGenerator {
308 public:
309 FilteredGeneratorGenerator(const FilterMap &filter, RangeGen &gen) : filter_(&filter), gen_(&gen), filter_pos_(), current_() {
310 SeekBegin();
311 }
312 const KeyType &operator*() const { return current_; }
313 const KeyType *operator->() const { return &current_; }
314 FilteredGeneratorGenerator &operator++() {
315 KeyType gen_range = GenRange();
316 KeyType filter_range = FilterRange();
317 current_ = KeyType();
318 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
319 if (gen_range.end > filter_range.end) {
320 // if the generated range is beyond the filter_range, advance the filter range
321 filter_range = AdvanceFilter();
322 } else {
323 gen_range = AdvanceGen();
324 }
325 current_ = gen_range & filter_range;
326 }
327 return *this;
328 }
329
330 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
331
332 private:
333 KeyType AdvanceFilter() {
334 ++filter_pos_;
335 auto filter_range = FilterRange();
336 if (filter_range.valid()) {
337 FastForwardGen(filter_range);
338 }
339 return filter_range;
340 }
341 KeyType AdvanceGen() {
342 ++(*gen_);
343 auto gen_range = GenRange();
344 if (gen_range.valid()) {
345 FastForwardFilter(gen_range);
346 }
347 return gen_range;
348 }
349
350 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
351 KeyType GenRange() const { return *(*gen_); }
352
353 KeyType FastForwardFilter(const KeyType &range) {
354 auto filter_range = FilterRange();
355 int retry_count = 0;
356 const static int kRetryLimit = 2; // TODO -- determine wheter this limit is optimal
357 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
358 if (retry_count < kRetryLimit) {
359 ++filter_pos_;
360 filter_range = FilterRange();
361 retry_count++;
362 } else {
363 // Okay we've tried walking, do a seek.
364 filter_pos_ = filter_->lower_bound(range);
365 break;
366 }
367 }
368 return FilterRange();
369 }
370
371 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
372 // faster.
373 KeyType FastForwardGen(const KeyType &range) {
374 auto gen_range = GenRange();
375 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
376 ++(*gen_);
377 gen_range = GenRange();
378 }
379 return gen_range;
380 }
381
382 void SeekBegin() {
383 auto gen_range = GenRange();
384 if (gen_range.empty()) {
385 current_ = KeyType();
386 filter_pos_ = filter_->cend();
387 } else {
388 filter_pos_ = filter_->lower_bound(gen_range);
389 current_ = gen_range & FilterRange();
390 }
391 }
392
393 FilteredGeneratorGenerator() = default;
394 const FilterMap *filter_;
395 RangeGen *const gen_;
396 typename FilterMap::const_iterator filter_pos_;
397 KeyType current_;
398};
399
400using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
401
John Zulauf0cb5be22020-01-23 12:18:22 -0700402// Expand the pipeline stage without regard to whether the are valid w.r.t. queue or extension
403VkPipelineStageFlags ExpandPipelineStages(VkQueueFlags queue_flags, VkPipelineStageFlags stage_mask) {
404 VkPipelineStageFlags expanded = stage_mask;
405 if (VK_PIPELINE_STAGE_ALL_COMMANDS_BIT & stage_mask) {
406 expanded = expanded & ~VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
407 for (const auto &all_commands : syncAllCommandStagesByQueueFlags) {
408 if (all_commands.first & queue_flags) {
409 expanded |= all_commands.second;
410 }
411 }
412 }
413 if (VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT & stage_mask) {
414 expanded = expanded & ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT;
415 expanded |= syncAllCommandStagesByQueueFlags.at(VK_QUEUE_GRAPHICS_BIT) & ~VK_PIPELINE_STAGE_HOST_BIT;
416 }
417 return expanded;
418}
419
John Zulauf36bcf6a2020-02-03 15:12:52 -0700420VkPipelineStageFlags RelatedPipelineStages(VkPipelineStageFlags stage_mask,
Jeremy Gebben91c36902020-11-09 08:17:08 -0700421 const std::map<VkPipelineStageFlagBits, VkPipelineStageFlags> &map) {
John Zulauf36bcf6a2020-02-03 15:12:52 -0700422 VkPipelineStageFlags unscanned = stage_mask;
423 VkPipelineStageFlags related = 0;
Jonah Ryan-Davis185189c2020-07-14 10:28:52 -0400424 for (const auto &entry : map) {
425 const auto &stage = entry.first;
John Zulauf36bcf6a2020-02-03 15:12:52 -0700426 if (stage & unscanned) {
427 related = related | entry.second;
428 unscanned = unscanned & ~stage;
429 if (!unscanned) break;
430 }
431 }
432 return related;
433}
434
435VkPipelineStageFlags WithEarlierPipelineStages(VkPipelineStageFlags stage_mask) {
436 return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyEarlierStages);
437}
438
439VkPipelineStageFlags WithLaterPipelineStages(VkPipelineStageFlags stage_mask) {
440 return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyLaterStages);
441}
442
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700443static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
John Zulauf5c5e88d2019-12-26 11:22:02 -0700444
John Zulauf3e86bf02020-09-12 10:47:57 -0600445ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
446 VkDeviceSize stride) {
447 VkDeviceSize range_start = offset + first_index * stride;
448 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600449 if (count == UINT32_MAX) {
450 range_size = buf_whole_size - range_start;
451 } else {
452 range_size = count * stride;
453 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600454 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600455}
456
locke-lunarg654e3692020-06-04 17:19:15 -0600457SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
458 VkShaderStageFlagBits stage_flag) {
459 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
460 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
461 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
462 }
463 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
464 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
465 assert(0);
466 }
467 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
468 return stage_access->second.uniform_read;
469 }
470
471 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
472 // Because if write hazard happens, read hazard might or might not happen.
473 // But if write hazard doesn't happen, read hazard is impossible to happen.
474 if (descriptor_data.is_writable) {
475 return stage_access->second.shader_write;
476 }
477 return stage_access->second.shader_read;
478}
479
locke-lunarg37047832020-06-12 13:44:45 -0600480bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
481 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
482 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
483 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
484 ? true
485 : false;
486}
487
488bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
489 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
490 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
491 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
492 ? true
493 : false;
494}
495
John Zulauf355e49b2020-04-24 15:11:15 -0600496// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600497template <typename Action>
498static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
499 Action &action) {
500 // At this point the "apply over range" logic only supports a single memory binding
501 if (!SimpleBinding(image_state)) return;
502 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600503 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700504 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
505 image_state.createInfo.extent, base_address);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600506 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700507 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600508 }
509}
510
John Zulauf7635de32020-05-29 17:14:15 -0600511// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
512// Used by both validation and record operations
513//
514// The signature for Action() reflect the needs of both uses.
515template <typename Action>
516void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
517 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) {
518 VkExtent3D extent = CastTo3D(render_area.extent);
519 VkOffset3D offset = CastTo3D(render_area.offset);
520 const auto &rp_ci = rp_state.createInfo;
521 const auto *attachment_ci = rp_ci.pAttachments;
522 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
523
524 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
525 const auto *color_attachments = subpass_ci.pColorAttachments;
526 const auto *color_resolve = subpass_ci.pResolveAttachments;
527 if (color_resolve && color_attachments) {
528 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
529 const auto &color_attach = color_attachments[i].attachment;
530 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
531 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
532 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
533 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, kColorAttachmentRasterOrder, offset, extent, 0);
534 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
535 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, kColorAttachmentRasterOrder, offset, extent, 0);
536 }
537 }
538 }
539
540 // Depth stencil resolve only if the extension is present
541 const auto ds_resolve = lvl_find_in_chain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
542 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
543 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
544 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
545 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
546 const auto src_ci = attachment_ci[src_at];
547 // The formats are required to match so we can pick either
548 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
549 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
550 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
551 VkImageAspectFlags aspect_mask = 0u;
552
553 // Figure out which aspects are actually touched during resolve operations
554 const char *aspect_string = nullptr;
555 if (resolve_depth && resolve_stencil) {
556 // Validate all aspects together
557 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
558 aspect_string = "depth/stencil";
559 } else if (resolve_depth) {
560 // Validate depth only
561 aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT;
562 aspect_string = "depth";
563 } else if (resolve_stencil) {
564 // Validate all stencil only
565 aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT;
566 aspect_string = "stencil";
567 }
568
569 if (aspect_mask) {
570 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at],
Jeremy Gebbenec5cd382020-11-16 15:53:45 -0700571 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, kAttachmentRasterOrder, offset, extent,
John Zulauf7635de32020-05-29 17:14:15 -0600572 aspect_mask);
573 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at],
574 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, kAttachmentRasterOrder, offset, extent, aspect_mask);
575 }
576 }
577}
578
579// Action for validating resolve operations
580class ValidateResolveAction {
581 public:
582 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context, const SyncValidator &sync_state,
583 const char *func_name)
584 : render_pass_(render_pass),
585 subpass_(subpass),
586 context_(context),
587 sync_state_(sync_state),
588 func_name_(func_name),
589 skip_(false) {}
590 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
591 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const SyncOrderingBarrier &ordering,
592 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
593 HazardResult hazard;
594 hazard = context_.DetectHazard(view, current_usage, ordering, offset, extent, aspect_mask);
595 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -0600596 skip_ |= sync_state_.LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
597 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -0600598 " to resolve attachment %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -0600599 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name,
John Zulauf37ceaed2020-07-03 16:18:15 -0600600 src_at, dst_at, string_UsageTag(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600601 }
602 }
603 // Providing a mechanism for the constructing caller to get the result of the validation
604 bool GetSkip() const { return skip_; }
605
606 private:
607 VkRenderPass render_pass_;
608 const uint32_t subpass_;
609 const AccessContext &context_;
610 const SyncValidator &sync_state_;
611 const char *func_name_;
612 bool skip_;
613};
614
615// Update action for resolve operations
616class UpdateStateResolveAction {
617 public:
618 UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {}
619 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
620 const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const SyncOrderingBarrier &ordering,
621 const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) {
622 // Ignores validation only arguments...
623 context_.UpdateAccessState(view, current_usage, offset, extent, aspect_mask, tag_);
624 }
625
626 private:
627 AccessContext &context_;
628 const ResourceUsageTag &tag_;
629};
630
John Zulauf59e25072020-07-17 10:55:21 -0600631void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700632 const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) {
John Zulauf59e25072020-07-17 10:55:21 -0600633 access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_));
634 usage_index = usage_index_;
635 hazard = hazard_;
636 prior_access = prior_;
637 tag = tag_;
638}
639
John Zulauf540266b2020-04-06 18:54:53 -0600640AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
641 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600642 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600643 Reset();
644 const auto &subpass_dep = dependencies[subpass];
645 prev_.reserve(subpass_dep.prev.size());
John Zulauf355e49b2020-04-24 15:11:15 -0600646 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600647 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600648 const auto prev_pass = prev_dep.first->pass;
649 const auto &prev_barriers = prev_dep.second;
650 assert(prev_dep.second.size());
651 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
652 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700653 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600654
655 async_.reserve(subpass_dep.async.size());
656 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700657 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600658 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600659 if (subpass_dep.barrier_from_external.size()) {
660 src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external);
John Zulaufe5da6e52020-03-18 15:32:18 -0600661 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600662 if (subpass_dep.barrier_to_external.size()) {
663 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600664 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700665}
666
John Zulauf5f13a792020-03-10 07:31:21 -0600667template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700668HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600669 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600670 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600671 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600672
673 HazardResult hazard;
674 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
675 hazard = detector.Detect(prev);
676 }
677 return hazard;
678}
679
John Zulauf4a6105a2020-11-17 15:11:05 -0700680template <typename Action>
681void AccessContext::ForAll(Action &&action) {
682 for (const auto address_type : kAddressTypes) {
683 auto &accesses = GetAccessStateMap(address_type);
684 for (const auto &access : accesses) {
685 action(address_type, access);
686 }
687 }
688}
689
John Zulauf3d84f1b2020-03-09 13:33:25 -0600690// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
691// the DAG of the contexts (for example subpasses)
692template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700693HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600694 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600695 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600696
John Zulauf1a224292020-06-30 14:52:13 -0600697 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600698 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
699 // so we'll check these first
700 for (const auto &async_context : async_) {
701 hazard = async_context->DetectAsyncHazard(type, detector, range);
702 if (hazard.hazard) return hazard;
703 }
John Zulauf5f13a792020-03-10 07:31:21 -0600704 }
705
John Zulauf1a224292020-06-30 14:52:13 -0600706 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600707
John Zulauf69133422020-05-20 14:55:53 -0600708 const auto &accesses = GetAccessStateMap(type);
709 const auto from = accesses.lower_bound(range);
710 const auto to = accesses.upper_bound(range);
711 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600712
John Zulauf69133422020-05-20 14:55:53 -0600713 for (auto pos = from; pos != to; ++pos) {
714 // Cover any leading gap, or gap between entries
715 if (detect_prev) {
716 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
717 // Cover any leading gap, or gap between entries
718 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600719 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600720 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600721 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600722 if (hazard.hazard) return hazard;
723 }
John Zulauf69133422020-05-20 14:55:53 -0600724 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
725 gap.begin = pos->first.end;
726 }
727
728 hazard = detector.Detect(pos);
729 if (hazard.hazard) return hazard;
730 }
731
732 if (detect_prev) {
733 // Detect in the trailing empty as needed
734 gap.end = range.end;
735 if (gap.non_empty()) {
736 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600737 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600738 }
739
740 return hazard;
741}
742
743// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
744template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700745HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
746 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600747 auto &accesses = GetAccessStateMap(type);
748 const auto from = accesses.lower_bound(range);
749 const auto to = accesses.upper_bound(range);
750
John Zulauf3d84f1b2020-03-09 13:33:25 -0600751 HazardResult hazard;
John Zulauf16adfc92020-04-08 10:28:33 -0600752 for (auto pos = from; pos != to && !hazard.hazard; ++pos) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700753 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600754 }
John Zulauf16adfc92020-04-08 10:28:33 -0600755
John Zulauf3d84f1b2020-03-09 13:33:25 -0600756 return hazard;
757}
758
John Zulaufb02c1eb2020-10-06 16:33:36 -0600759struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700760 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600761 void operator()(ResourceAccessState *access) const {
762 assert(access);
763 access->ApplyBarriers(barriers, true);
764 }
765 const std::vector<SyncBarrier> &barriers;
766};
767
768struct ApplyTrackbackBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700769 explicit ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600770 void operator()(ResourceAccessState *access) const {
771 assert(access);
772 assert(!access->HasPendingState());
773 access->ApplyBarriers(barriers, false);
774 access->ApplyPendingBarriers(kCurrentCommandTag);
775 }
776 const std::vector<SyncBarrier> &barriers;
777};
778
779// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
780// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
781// *different* map from dest.
782// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
783// range [first, last)
784template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600785static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
786 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600787 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600788 auto at = entry;
789 for (auto pos = first; pos != last; ++pos) {
790 // Every member of the input iterator range must fit within the remaining portion of entry
791 assert(at->first.includes(pos->first));
792 assert(at != dest->end());
793 // Trim up at to the same size as the entry to resolve
794 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600795 auto access = pos->second; // intentional copy
796 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600797 at->second.Resolve(access);
798 ++at; // Go to the remaining unused section of entry
799 }
800}
801
John Zulaufa0a98292020-09-18 09:30:10 -0600802static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
803 SyncBarrier merged = {};
804 for (const auto &barrier : barriers) {
805 merged.Merge(barrier);
806 }
807 return merged;
808}
809
John Zulaufb02c1eb2020-10-06 16:33:36 -0600810template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700811void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600812 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
813 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600814 if (!range.non_empty()) return;
815
John Zulauf355e49b2020-04-24 15:11:15 -0600816 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
817 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600818 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600819 if (current->pos_B->valid) {
820 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600821 auto access = src_pos->second; // intentional copy
822 barrier_action(&access);
823
John Zulauf16adfc92020-04-08 10:28:33 -0600824 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600825 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
826 trimmed->second.Resolve(access);
827 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600828 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600829 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600830 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600831 }
John Zulauf16adfc92020-04-08 10:28:33 -0600832 } else {
833 // we have to descend to fill this gap
834 if (recur_to_infill) {
John Zulauf355e49b2020-04-24 15:11:15 -0600835 if (current->pos_A->valid) {
836 // Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation
837 ResourceAccessRangeMap gap_map;
John Zulauf3bcab5e2020-06-19 14:42:32 -0600838 ResolvePreviousAccess(type, current_range, &gap_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600839 ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -0600840 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600841 // There isn't anything in dest in current)range, so we can accumulate directly into it.
842 ResolvePreviousAccess(type, current_range, resolve_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600843 // Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current
844 for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) {
845 barrier_action(&pos->second);
John Zulauf355e49b2020-04-24 15:11:15 -0600846 }
847 }
848 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
849 // iterator of the outer while.
850
851 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
852 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
853 // we stepped on the dest map
locke-lunarg88dbb542020-06-23 22:05:42 -0600854 const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
855 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -0600856 current.seek(seek_to);
857 } else if (!current->pos_A->valid && infill_state) {
858 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
859 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
860 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -0600861 }
John Zulauf5f13a792020-03-10 07:31:21 -0600862 }
John Zulauf16adfc92020-04-08 10:28:33 -0600863 ++current;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600864 }
John Zulauf1a224292020-06-30 14:52:13 -0600865
866 // Infill if range goes passed both the current and resolve map prior contents
867 if (recur_to_infill && (current->range.end < range.end)) {
868 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
869 ResourceAccessRangeMap gap_map;
870 const auto the_end = resolve_map->end();
871 ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state);
872 for (auto &access : gap_map) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600873 barrier_action(&access.second);
John Zulauf1a224292020-06-30 14:52:13 -0600874 resolve_map->insert(the_end, access);
875 }
876 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600877}
878
John Zulauf43cc7462020-12-03 12:33:12 -0700879void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
880 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufe5da6e52020-03-18 15:32:18 -0600881 if ((prev_.size() == 0) && (src_external_.context == nullptr)) {
John Zulauf5f13a792020-03-10 07:31:21 -0600882 if (range.non_empty() && infill_state) {
883 descent_map->insert(std::make_pair(range, *infill_state));
884 }
885 } else {
886 // Look for something to fill the gap further along.
887 for (const auto &prev_dep : prev_) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600888 const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers);
889 prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600890 }
891
John Zulaufe5da6e52020-03-18 15:32:18 -0600892 if (src_external_.context) {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600893 const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers);
894 src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -0600895 }
896 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600897}
898
John Zulauf4a6105a2020-11-17 15:11:05 -0700899// Non-lazy import of all accesses, WaitEvents needs this.
900void AccessContext::ResolvePreviousAccesses() {
901 ResourceAccessState default_state;
902 for (const auto address_type : kAddressTypes) {
903 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
904 }
905}
906
John Zulauf43cc7462020-12-03 12:33:12 -0700907AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
908 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -0600909}
910
John Zulauf1507ee42020-05-18 11:33:09 -0600911static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
912 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
913 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE;
914 return stage_access;
915}
916static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
917 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
918 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE;
919 return stage_access;
920}
921
John Zulauf7635de32020-05-29 17:14:15 -0600922// Caller must manage returned pointer
923static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
924 uint32_t subpass, const VkRect2D &render_area,
925 std::vector<const IMAGE_VIEW_STATE *> attachment_views) {
926 auto *proxy = new AccessContext(context);
927 proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulaufaff20662020-06-01 14:07:58 -0600928 proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag);
John Zulauf7635de32020-05-29 17:14:15 -0600929 return proxy;
930}
931
John Zulaufb02c1eb2020-10-06 16:33:36 -0600932template <typename BarrierAction>
John Zulauf52446eb2020-10-22 16:40:08 -0600933class ResolveAccessRangeFunctor {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600934 public:
John Zulauf43cc7462020-12-03 12:33:12 -0700935 ResolveAccessRangeFunctor(const AccessContext &context, AccessAddressType address_type, ResourceAccessRangeMap *descent_map,
936 const ResourceAccessState *infill_state, BarrierAction &barrier_action)
John Zulauf52446eb2020-10-22 16:40:08 -0600937 : context_(context),
938 address_type_(address_type),
939 descent_map_(descent_map),
940 infill_state_(infill_state),
941 barrier_action_(barrier_action) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600942 ResolveAccessRangeFunctor() = delete;
943 void operator()(const ResourceAccessRange &range) const {
944 context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_);
945 }
946
947 private:
John Zulauf52446eb2020-10-22 16:40:08 -0600948 const AccessContext &context_;
John Zulauf43cc7462020-12-03 12:33:12 -0700949 const AccessAddressType address_type_;
John Zulauf52446eb2020-10-22 16:40:08 -0600950 ResourceAccessRangeMap *const descent_map_;
951 const ResourceAccessState *infill_state_;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600952 BarrierAction &barrier_action_;
953};
954
John Zulaufb02c1eb2020-10-06 16:33:36 -0600955template <typename BarrierAction>
956void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -0700957 BarrierAction &barrier_action, AccessAddressType address_type,
958 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const {
John Zulaufb02c1eb2020-10-06 16:33:36 -0600959 const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action);
960 ApplyOverImageRange(image_state, subresource_range, action);
John Zulauf62f10592020-04-03 12:20:02 -0600961}
962
John Zulauf7635de32020-05-29 17:14:15 -0600963// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulauf1507ee42020-05-18 11:33:09 -0600964bool AccessContext::ValidateLayoutTransitions(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -0600965 const VkRect2D &render_area, uint32_t subpass,
966 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
967 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -0600968 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -0600969 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
970 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
971 // those affects have not been recorded yet.
972 //
973 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
974 // to apply and only copy then, if this proves a hot spot.
975 std::unique_ptr<AccessContext> proxy_for_prev;
976 TrackBack proxy_track_back;
977
John Zulauf355e49b2020-04-24 15:11:15 -0600978 const auto &transitions = rp_state.subpass_transitions[subpass];
979 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -0600980 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
981
982 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
983 if (prev_needs_proxy) {
984 if (!proxy_for_prev) {
985 proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass,
986 render_area, attachment_views));
987 proxy_track_back = *track_back;
988 proxy_track_back.context = proxy_for_prev.get();
989 }
990 track_back = &proxy_track_back;
991 }
992 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -0600993 if (hazard.hazard) {
John Zulauf389c34b2020-07-28 11:19:35 -0600994 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
995 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
996 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
997 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
998 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
999 string_UsageTag(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06001000 }
1001 }
1002 return skip;
1003}
1004
John Zulauf1507ee42020-05-18 11:33:09 -06001005bool AccessContext::ValidateLoadOperation(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001006 const VkRect2D &render_area, uint32_t subpass,
1007 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1008 const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001009 bool skip = false;
1010 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1011 VkExtent3D extent = CastTo3D(render_area.extent);
1012 VkOffset3D offset = CastTo3D(render_area.offset);
John Zulaufa0a98292020-09-18 09:30:10 -06001013
John Zulauf1507ee42020-05-18 11:33:09 -06001014 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1015 if (subpass == rp_state.attachment_first_subpass[i]) {
1016 if (attachment_views[i] == nullptr) continue;
1017 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1018 const IMAGE_STATE *image = view.image_state.get();
1019 if (image == nullptr) continue;
1020 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001021
1022 // Need check in the following way
1023 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1024 // vs. transition
1025 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1026 // for each aspect loaded.
1027
1028 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001029 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001030 const bool is_color = !(has_depth || has_stencil);
1031
1032 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001033 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001034
John Zulaufaff20662020-06-01 14:07:58 -06001035 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001036 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001037
John Zulaufb02c1eb2020-10-06 16:33:36 -06001038 auto hazard_range = view.normalized_subresource_range;
1039 bool checked_stencil = false;
1040 if (is_color) {
John Zulauf859089b2020-10-29 17:37:03 -06001041 hazard = DetectHazard(*image, load_index, view.normalized_subresource_range, kColorAttachmentRasterOrder, offset,
1042 extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001043 aspect = "color";
1044 } else {
1045 if (has_depth) {
1046 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
John Zulauf859089b2020-10-29 17:37:03 -06001047 hazard = DetectHazard(*image, load_index, hazard_range, kDepthStencilAttachmentRasterOrder, offset, extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001048 aspect = "depth";
1049 }
1050 if (!hazard.hazard && has_stencil) {
1051 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
John Zulauf859089b2020-10-29 17:37:03 -06001052 hazard =
1053 DetectHazard(*image, stencil_load_index, hazard_range, kDepthStencilAttachmentRasterOrder, offset, extent);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001054 aspect = "stencil";
1055 checked_stencil = true;
1056 }
1057 }
1058
1059 if (hazard.hazard) {
1060 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
1061 if (hazard.tag == kCurrentCommandTag) {
1062 // Hazard vs. ILT
1063 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1064 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1065 " aspect %s during load with loadOp %s.",
1066 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1067 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06001068 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1069 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001070 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001071 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf37ceaed2020-07-03 16:18:15 -06001072 string_UsageTag(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001073 }
1074 }
1075 }
1076 }
1077 return skip;
1078}
1079
John Zulaufaff20662020-06-01 14:07:58 -06001080// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1081// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1082// store is part of the same Next/End operation.
1083// The latter is handled in layout transistion validation directly
1084bool AccessContext::ValidateStoreOperation(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state,
1085 const VkRect2D &render_area, uint32_t subpass,
1086 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1087 const char *func_name) const {
1088 bool skip = false;
1089 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1090 VkExtent3D extent = CastTo3D(render_area.extent);
1091 VkOffset3D offset = CastTo3D(render_area.offset);
1092
1093 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1094 if (subpass == rp_state.attachment_last_subpass[i]) {
1095 if (attachment_views[i] == nullptr) continue;
1096 const IMAGE_VIEW_STATE &view = *attachment_views[i];
1097 const IMAGE_STATE *image = view.image_state.get();
1098 if (image == nullptr) continue;
1099 const auto &ci = attachment_ci[i];
1100
1101 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1102 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1103 // sake, we treat DONT_CARE as writing.
1104 const bool has_depth = FormatHasDepth(ci.format);
1105 const bool has_stencil = FormatHasStencil(ci.format);
1106 const bool is_color = !(has_depth || has_stencil);
1107 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1108 if (!has_stencil && !store_op_stores) continue;
1109
1110 HazardResult hazard;
1111 const char *aspect = nullptr;
1112 bool checked_stencil = false;
1113 if (is_color) {
1114 hazard = DetectHazard(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
1115 view.normalized_subresource_range, kAttachmentRasterOrder, offset, extent);
1116 aspect = "color";
1117 } else {
1118 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1119 auto hazard_range = view.normalized_subresource_range;
1120 if (has_depth && store_op_stores) {
1121 hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1122 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
1123 kAttachmentRasterOrder, offset, extent);
1124 aspect = "depth";
1125 }
1126 if (!hazard.hazard && has_stencil && stencil_op_stores) {
1127 hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1128 hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range,
1129 kAttachmentRasterOrder, offset, extent);
1130 aspect = "stencil";
1131 checked_stencil = true;
1132 }
1133 }
1134
1135 if (hazard.hazard) {
1136 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1137 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf1dae9192020-06-16 15:46:44 -06001138 skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard),
1139 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001140 " %s aspect during store with %s %s. Access info %s",
John Zulauf1dae9192020-06-16 15:46:44 -06001141 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, op_type_string,
John Zulauf37ceaed2020-07-03 16:18:15 -06001142 store_op_string, string_UsageTag(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001143 }
1144 }
1145 }
1146 return skip;
1147}
1148
John Zulaufb027cdb2020-05-21 14:25:22 -06001149bool AccessContext::ValidateResolveOperations(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state,
1150 const VkRect2D &render_area,
1151 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name,
1152 uint32_t subpass) const {
John Zulauf7635de32020-05-29 17:14:15 -06001153 ValidateResolveAction validate_action(rp_state.renderPass, subpass, *this, sync_state, func_name);
1154 ResolveOperation(validate_action, rp_state, render_area, attachment_views, subpass);
1155 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001156}
1157
John Zulauf3d84f1b2020-03-09 13:33:25 -06001158class HazardDetector {
1159 SyncStageAccessIndex usage_index_;
1160
1161 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001162 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001163 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1164 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001165 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001166 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001167};
1168
John Zulauf69133422020-05-20 14:55:53 -06001169class HazardDetectorWithOrdering {
1170 const SyncStageAccessIndex usage_index_;
1171 const SyncOrderingBarrier &ordering_;
1172
1173 public:
1174 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1175 return pos->second.DetectHazard(usage_index_, ordering_);
1176 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001177 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1178 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001179 }
1180 HazardDetectorWithOrdering(SyncStageAccessIndex usage, const SyncOrderingBarrier &ordering)
1181 : usage_index_(usage), ordering_(ordering) {}
1182};
1183
John Zulauf16adfc92020-04-08 10:28:33 -06001184HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001185 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001186 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001187 const auto base_address = ResourceBaseAddress(buffer);
1188 HazardDetector detector(usage_index);
1189 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001190}
1191
John Zulauf69133422020-05-20 14:55:53 -06001192template <typename Detector>
1193HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1194 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1195 const VkExtent3D &extent, DetectOptions options) const {
1196 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001197 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001198 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1199 base_address);
1200 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001201 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001202 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001203 if (hazard.hazard) return hazard;
1204 }
1205 return HazardResult();
1206}
1207
John Zulauf540266b2020-04-06 18:54:53 -06001208HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1209 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1210 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001211 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1212 subresource.layerCount};
John Zulauf1507ee42020-05-18 11:33:09 -06001213 return DetectHazard(image, current_usage, subresource_range, offset, extent);
1214}
1215
1216HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1217 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1218 const VkExtent3D &extent) const {
John Zulauf69133422020-05-20 14:55:53 -06001219 HazardDetector detector(current_usage);
1220 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
1221}
1222
1223HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1224 const VkImageSubresourceRange &subresource_range, const SyncOrderingBarrier &ordering,
1225 const VkOffset3D &offset, const VkExtent3D &extent) const {
1226 HazardDetectorWithOrdering detector(current_usage, ordering);
1227 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001228}
1229
John Zulaufb027cdb2020-05-21 14:25:22 -06001230// Some common code for looking at attachments, if there's anything wrong, we return no hazard, core validation
1231// should have reported the issue regarding an invalid attachment entry
1232HazardResult AccessContext::DetectHazard(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage,
1233 const SyncOrderingBarrier &ordering, const VkOffset3D &offset, const VkExtent3D &extent,
1234 VkImageAspectFlags aspect_mask) const {
1235 if (view != nullptr) {
1236 const IMAGE_STATE *image = view->image_state.get();
1237 if (image != nullptr) {
1238 auto *detect_range = &view->normalized_subresource_range;
1239 VkImageSubresourceRange masked_range;
1240 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1241 masked_range = view->normalized_subresource_range;
1242 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1243 detect_range = &masked_range;
1244 }
1245
1246 // NOTE: The range encoding code is not robust to invalid ranges, so we protect it from our change
1247 if (detect_range->aspectMask) {
1248 return DetectHazard(*image, current_usage, *detect_range, ordering, offset, extent);
1249 }
1250 }
1251 }
1252 return HazardResult();
1253}
John Zulauf43cc7462020-12-03 12:33:12 -07001254
John Zulauf3d84f1b2020-03-09 13:33:25 -06001255class BarrierHazardDetector {
1256 public:
1257 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1258 SyncStageAccessFlags src_access_scope)
1259 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1260
John Zulauf5f13a792020-03-10 07:31:21 -06001261 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1262 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001263 }
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001264 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001265 // 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 -07001266 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001267 }
1268
1269 private:
1270 SyncStageAccessIndex usage_index_;
1271 VkPipelineStageFlags src_exec_scope_;
1272 SyncStageAccessFlags src_access_scope_;
1273};
1274
John Zulauf4a6105a2020-11-17 15:11:05 -07001275class EventBarrierHazardDetector {
1276 public:
1277 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
1278 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
1279 const ResourceUsageTag &scope_tag)
1280 : usage_index_(usage_index),
1281 src_exec_scope_(src_exec_scope),
1282 src_access_scope_(src_access_scope),
1283 event_scope_(event_scope),
1284 scope_pos_(event_scope.cbegin()),
1285 scope_end_(event_scope.cend()),
1286 scope_tag_(scope_tag) {}
1287
1288 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1289 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1290 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1291 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1292 if (scope_pos_ == scope_end_) return HazardResult();
1293 if (!scope_pos_->first.intersects(pos->first)) {
1294 event_scope_.lower_bound(pos->first);
1295 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1296 }
1297
1298 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1299 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1300 }
1301 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, const ResourceUsageTag &start_tag) const {
1302 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1303 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1304 }
1305
1306 private:
1307 SyncStageAccessIndex usage_index_;
1308 VkPipelineStageFlags src_exec_scope_;
1309 SyncStageAccessFlags src_access_scope_;
1310 const SyncEventState::ScopeMap &event_scope_;
1311 SyncEventState::ScopeMap::const_iterator scope_pos_;
1312 SyncEventState::ScopeMap::const_iterator scope_end_;
1313 const ResourceUsageTag &scope_tag_;
1314};
1315
1316HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
1317 const SyncStageAccessFlags &src_access_scope,
1318 const VkImageSubresourceRange &subresource_range,
1319 const SyncEventState &sync_event, DetectOptions options) const {
1320 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1321 // first access scope map to use, and there's no easy way to plumb it in below.
1322 const auto address_type = ImageAddressType(image);
1323 const auto &event_scope = sync_event.FirstScope(address_type);
1324
1325 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1326 event_scope, sync_event.first_scope_tag);
1327 VkOffset3D zero_offset = {0, 0, 0};
1328 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
1329}
1330
John Zulauf16adfc92020-04-08 10:28:33 -06001331HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001332 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001333 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001334 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001335 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
1336 VkOffset3D zero_offset = {0, 0, 0};
1337 return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001338}
1339
John Zulauf355e49b2020-04-24 15:11:15 -06001340HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001341 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001342 const VkImageMemoryBarrier &barrier) const {
1343 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1344 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1345 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1346}
1347
John Zulauf9cb530d2019-09-30 14:14:10 -06001348template <typename Flags, typename Map>
1349SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1350 SyncStageAccessFlags scope = 0;
1351 for (const auto &bit_scope : map) {
1352 if (flag_mask < bit_scope.first) break;
1353
1354 if (flag_mask & bit_scope.first) {
1355 scope |= bit_scope.second;
1356 }
1357 }
1358 return scope;
1359}
1360
1361SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags stages) {
1362 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1363}
1364
1365SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags accesses) {
1366 return AccessScopeImpl(accesses, syncStageAccessMaskByAccessBit);
1367}
1368
1369// Getting from stage mask and access mask to stage/acess masks is something we need to be good at...
1370SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags stages, VkAccessFlags accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001371 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1372 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1373 // 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 -06001374 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1375}
1376
1377template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001378void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001379 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1380 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001381 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001382 auto pos = accesses->lower_bound(range);
1383 if (pos == accesses->end() || !pos->first.intersects(range)) {
1384 // The range is empty, fill it with a default value.
1385 pos = action.Infill(accesses, pos, range);
1386 } else if (range.begin < pos->first.begin) {
1387 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001388 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001389 } else if (pos->first.begin < range.begin) {
1390 // Trim the beginning if needed
1391 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1392 ++pos;
1393 }
1394
1395 const auto the_end = accesses->end();
1396 while ((pos != the_end) && pos->first.intersects(range)) {
1397 if (pos->first.end > range.end) {
1398 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1399 }
1400
1401 pos = action(accesses, pos);
1402 if (pos == the_end) break;
1403
1404 auto next = pos;
1405 ++next;
1406 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1407 // Need to infill if next is disjoint
1408 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001409 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001410 next = action.Infill(accesses, next, new_range);
1411 }
1412 pos = next;
1413 }
1414}
John Zulauf4a6105a2020-11-17 15:11:05 -07001415template <typename Action, typename RangeGen>
1416void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1417 assert(range_gen_arg);
1418 auto &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
1419 for (; range_gen->non_empty(); ++range_gen) {
1420 UpdateMemoryAccessState(accesses, *range_gen, action);
1421 }
1422}
John Zulauf9cb530d2019-09-30 14:14:10 -06001423
1424struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001425 using Iterator = ResourceAccessRangeMap::iterator;
1426 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001427 // this is only called on gaps, and never returns a gap.
1428 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001429 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001430 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001431 }
John Zulauf5f13a792020-03-10 07:31:21 -06001432
John Zulauf5c5e88d2019-12-26 11:22:02 -07001433 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001434 auto &access_state = pos->second;
1435 access_state.Update(usage, tag);
1436 return pos;
1437 }
1438
John Zulauf43cc7462020-12-03 12:33:12 -07001439 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf540266b2020-04-06 18:54:53 -06001440 const ResourceUsageTag &tag_)
John Zulauf16adfc92020-04-08 10:28:33 -06001441 : type(type_), context(context_), usage(usage_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001442 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001443 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001444 const SyncStageAccessIndex usage;
John Zulauf9cb530d2019-09-30 14:14:10 -06001445 const ResourceUsageTag &tag;
1446};
1447
John Zulauf4a6105a2020-11-17 15:11:05 -07001448// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001449struct PipelineBarrierOp {
1450 SyncBarrier barrier;
1451 bool layout_transition;
1452 PipelineBarrierOp(const SyncBarrier &barrier_, bool layout_transition_)
1453 : barrier(barrier_), layout_transition(layout_transition_) {}
1454 PipelineBarrierOp() = default;
1455 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(barrier, layout_transition); }
1456};
John Zulauf4a6105a2020-11-17 15:11:05 -07001457// The barrier operation for wait events
1458struct WaitEventBarrierOp {
1459 const ResourceUsageTag *scope_tag;
1460 SyncBarrier barrier;
1461 bool layout_transition;
1462 WaitEventBarrierOp(const ResourceUsageTag &scope_tag_, const SyncBarrier &barrier_, bool layout_transition_)
1463 : scope_tag(&scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1464 WaitEventBarrierOp() = default;
1465 void operator()(ResourceAccessState *access_state) const {
1466 assert(scope_tag); // Not valid to have a non-scope op executed, default construct included for std::vector support
1467 access_state->ApplyBarrier(*scope_tag, barrier, layout_transition);
1468 }
1469};
John Zulauf1e331ec2020-12-04 18:29:38 -07001470
John Zulauf4a6105a2020-11-17 15:11:05 -07001471// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1472// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1473// of a collection is known/present.
John Zulauf1e331ec2020-12-04 18:29:38 -07001474template <typename BarrierOp>
John Zulauf89311b42020-09-29 16:28:47 -06001475class ApplyBarrierOpsFunctor {
1476 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001477 using Iterator = ResourceAccessRangeMap::iterator;
1478 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
John Zulauf9cb530d2019-09-30 14:14:10 -06001479
John Zulauf5c5e88d2019-12-26 11:22:02 -07001480 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001481 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001482 for (const auto &op : barrier_ops_) {
1483 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001484 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001485
John Zulauf89311b42020-09-29 16:28:47 -06001486 if (resolve_) {
1487 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1488 // another walk
1489 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001490 }
1491 return pos;
1492 }
1493
John Zulauf89311b42020-09-29 16:28:47 -06001494 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf1e331ec2020-12-04 18:29:38 -07001495 ApplyBarrierOpsFunctor(bool resolve, const std::vector<BarrierOp> &barrier_ops, const ResourceUsageTag &tag)
1496 : resolve_(resolve), barrier_ops_(barrier_ops), tag_(tag) {}
John Zulauf89311b42020-09-29 16:28:47 -06001497
1498 private:
1499 bool resolve_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001500 const std::vector<BarrierOp> &barrier_ops_;
1501 const ResourceUsageTag &tag_;
1502};
1503
John Zulauf4a6105a2020-11-17 15:11:05 -07001504// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1505// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1506template <typename BarrierOp>
1507class ApplyBarrierFunctor {
1508 public:
1509 using Iterator = ResourceAccessRangeMap::iterator;
1510 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1511
1512 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1513 auto &access_state = pos->second;
1514 barrier_op_(&access_state);
1515 return pos;
1516 }
1517
1518 ApplyBarrierFunctor(const BarrierOp &barrier_op) : barrier_op_(barrier_op) {}
1519
1520 private:
1521 const BarrierOp barrier_op_;
1522};
1523
John Zulauf1e331ec2020-12-04 18:29:38 -07001524// This functor resolves the pendinging state.
1525class ResolvePendingBarrierFunctor {
1526 public:
1527 using Iterator = ResourceAccessRangeMap::iterator;
1528 inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; }
1529
1530 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
1531 auto &access_state = pos->second;
1532 access_state.ApplyPendingBarriers(tag_);
1533 return pos;
1534 }
1535
1536 ResolvePendingBarrierFunctor(const ResourceUsageTag &tag) : tag_(tag) {}
1537
1538 private:
John Zulauf89311b42020-09-29 16:28:47 -06001539 const ResourceUsageTag &tag_;
John Zulauf9cb530d2019-09-30 14:14:10 -06001540};
1541
John Zulauf43cc7462020-12-03 12:33:12 -07001542void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -06001543 const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001544 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, tag);
1545 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001546}
1547
John Zulauf16adfc92020-04-08 10:28:33 -06001548void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage,
John Zulauf355e49b2020-04-24 15:11:15 -06001549 const ResourceAccessRange &range, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001550 if (!SimpleBinding(buffer)) return;
1551 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf43cc7462020-12-03 12:33:12 -07001552 UpdateAccessState(AccessAddressType::kLinear, current_usage, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001553}
John Zulauf355e49b2020-04-24 15:11:15 -06001554
John Zulauf540266b2020-04-06 18:54:53 -06001555void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf355e49b2020-04-24 15:11:15 -06001556 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf540266b2020-04-06 18:54:53 -06001557 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001558 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001559 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001560 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1561 base_address);
1562 const auto address_type = ImageAddressType(image);
John Zulauf16adfc92020-04-08 10:28:33 -06001563 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, tag);
John Zulauf5f13a792020-03-10 07:31:21 -06001564 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001565 UpdateMemoryAccessState(&GetAccessStateMap(address_type), *range_gen, action);
John Zulauf5f13a792020-03-10 07:31:21 -06001566 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001567}
John Zulauf7635de32020-05-29 17:14:15 -06001568void AccessContext::UpdateAccessState(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const VkOffset3D &offset,
1569 const VkExtent3D &extent, VkImageAspectFlags aspect_mask, const ResourceUsageTag &tag) {
1570 if (view != nullptr) {
1571 const IMAGE_STATE *image = view->image_state.get();
1572 if (image != nullptr) {
1573 auto *update_range = &view->normalized_subresource_range;
1574 VkImageSubresourceRange masked_range;
1575 if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask
1576 masked_range = view->normalized_subresource_range;
1577 masked_range.aspectMask = aspect_mask & masked_range.aspectMask;
1578 update_range = &masked_range;
1579 }
1580 UpdateAccessState(*image, current_usage, *update_range, offset, extent, tag);
1581 }
1582 }
1583}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001584
John Zulauf355e49b2020-04-24 15:11:15 -06001585void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1586 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1587 const VkExtent3D &extent, const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001588 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1589 subresource.layerCount};
1590 UpdateAccessState(image, current_usage, subresource_range, offset, extent, tag);
1591}
1592
John Zulauf540266b2020-04-06 18:54:53 -06001593template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001594void AccessContext::UpdateResourceAccess(const BUFFER_STATE &buffer, const ResourceAccessRange &range, const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001595 if (!SimpleBinding(buffer)) return;
1596 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf43cc7462020-12-03 12:33:12 -07001597 UpdateMemoryAccessState(&GetAccessStateMap(AccessAddressType::kLinear), (range + base_address), action);
John Zulauf540266b2020-04-06 18:54:53 -06001598}
1599
1600template <typename Action>
John Zulauf89311b42020-09-29 16:28:47 -06001601void AccessContext::UpdateResourceAccess(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1602 const Action action) {
John Zulauf16adfc92020-04-08 10:28:33 -06001603 if (!SimpleBinding(image)) return;
1604 const auto address_type = ImageAddressType(image);
1605 auto *accesses = &GetAccessStateMap(address_type);
John Zulauf540266b2020-04-06 18:54:53 -06001606
John Zulauf16adfc92020-04-08 10:28:33 -06001607 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001608 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, {0, 0, 0},
1609 image.createInfo.extent, base_address);
1610
John Zulauf540266b2020-04-06 18:54:53 -06001611 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001612 UpdateMemoryAccessState(accesses, *range_gen, action);
John Zulauf540266b2020-04-06 18:54:53 -06001613 }
1614}
1615
John Zulauf7635de32020-05-29 17:14:15 -06001616void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1617 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1618 const ResourceUsageTag &tag) {
1619 UpdateStateResolveAction update(*this, tag);
1620 ResolveOperation(update, rp_state, render_area, attachment_views, subpass);
1621}
1622
John Zulaufaff20662020-06-01 14:07:58 -06001623void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
1624 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass,
1625 const ResourceUsageTag &tag) {
1626 const auto *attachment_ci = rp_state.createInfo.pAttachments;
1627 VkExtent3D extent = CastTo3D(render_area.extent);
1628 VkOffset3D offset = CastTo3D(render_area.offset);
1629
1630 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1631 if (rp_state.attachment_last_subpass[i] == subpass) {
1632 if (attachment_views[i] == nullptr) continue; // UNUSED
1633 const auto &view = *attachment_views[i];
1634 const IMAGE_STATE *image = view.image_state.get();
1635 if (image == nullptr) continue;
1636
1637 const auto &ci = attachment_ci[i];
1638 const bool has_depth = FormatHasDepth(ci.format);
1639 const bool has_stencil = FormatHasStencil(ci.format);
1640 const bool is_color = !(has_depth || has_stencil);
1641 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1642
1643 if (is_color && store_op_stores) {
1644 UpdateAccessState(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, view.normalized_subresource_range,
1645 offset, extent, tag);
1646 } else {
1647 auto update_range = view.normalized_subresource_range;
1648 if (has_depth && store_op_stores) {
1649 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
1650 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, update_range, offset, extent,
1651 tag);
1652 }
1653 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM;
1654 if (has_stencil && stencil_op_stores) {
1655 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
1656 UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, update_range, offset, extent,
1657 tag);
1658 }
1659 }
1660 }
1661 }
1662}
1663
John Zulauf540266b2020-04-06 18:54:53 -06001664template <typename Action>
1665void AccessContext::ApplyGlobalBarriers(const Action &barrier_action) {
1666 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001667 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001668 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001669 }
1670}
1671
1672void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001673 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1674 auto &context = contexts[subpass_index];
John Zulaufb02c1eb2020-10-06 16:33:36 -06001675 ApplyTrackbackBarriersAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001676 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001677 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001678 }
1679 }
1680}
1681
John Zulauf355e49b2020-04-24 15:11:15 -06001682// Suitable only for *subpass* access contexts
John Zulauf7635de32020-05-29 17:14:15 -06001683HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const IMAGE_VIEW_STATE *attach_view) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001684 if (!attach_view) return HazardResult();
1685 const auto image_state = attach_view->image_state.get();
1686 if (!image_state) return HazardResult();
1687
John Zulauf355e49b2020-04-24 15:11:15 -06001688 // We should never ask for a transition from a context we don't have
John Zulauf7635de32020-05-29 17:14:15 -06001689 assert(track_back.context);
John Zulauf355e49b2020-04-24 15:11:15 -06001690
1691 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001692 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1693 const auto merged_barrier = MergeBarriers(track_back.barriers);
1694 HazardResult hazard =
1695 track_back.context->DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
1696 attach_view->normalized_subresource_range, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001697 if (!hazard.hazard) {
1698 // The Async hazard check is against the current context's async set.
John Zulaufa0a98292020-09-18 09:30:10 -06001699 hazard = DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001700 attach_view->normalized_subresource_range, kDetectAsync);
1701 }
John Zulaufa0a98292020-09-18 09:30:10 -06001702
John Zulauf355e49b2020-04-24 15:11:15 -06001703 return hazard;
1704}
1705
John Zulaufb02c1eb2020-10-06 16:33:36 -06001706void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
1707 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
1708 const ResourceUsageTag &tag) {
1709 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001710 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001711 for (const auto &transition : transitions) {
1712 const auto prev_pass = transition.prev_pass;
1713 const auto attachment_view = attachment_views[transition.attachment];
1714 if (!attachment_view) continue;
1715 const auto *image = attachment_view->image_state.get();
1716 if (!image) continue;
1717 if (!SimpleBinding(*image)) continue;
1718
1719 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1720 assert(trackback);
1721
1722 // Import the attachments into the current context
1723 const auto *prev_context = trackback->context;
1724 assert(prev_context);
1725 const auto address_type = ImageAddressType(*image);
1726 auto &target_map = GetAccessStateMap(address_type);
1727 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
1728 prev_context->ResolveAccessRange(*image, attachment_view->normalized_subresource_range, barrier_action, address_type,
John Zulauf646cc292020-10-23 09:16:45 -06001729 &target_map, &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001730 }
1731
John Zulauf86356ca2020-10-19 11:46:41 -06001732 // If there were no transitions skip this global map walk
1733 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001734 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulauf86356ca2020-10-19 11:46:41 -06001735 ApplyGlobalBarriers(apply_pending_action);
1736 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001737}
John Zulauf4a6105a2020-11-17 15:11:05 -07001738void CommandBufferAccessContext::ApplyBufferBarriers(const SyncEventState &sync_event, VkPipelineStageFlags dst_exec_scope,
1739 const SyncStageAccessFlags &dst_stage_accesses, uint32_t barrier_count,
1740 const VkBufferMemoryBarrier *barriers) {
1741 const auto &scope_tag = sync_event.first_scope_tag;
1742 auto *access_context = GetCurrentAccessContext();
1743 const auto address_type = AccessAddressType::kLinear;
1744 for (uint32_t index = 0; index < barrier_count; index++) {
1745 auto barrier = barriers[index]; // barrier is a copy
1746 const auto *buffer = sync_state_->Get<BUFFER_STATE>(barrier.buffer);
1747 if (!buffer) continue;
1748 const auto base_address = ResourceBaseAddress(*buffer);
1749 barrier.size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
1750 const ResourceAccessRange range = MakeRange(barrier) + base_address;
1751 const auto src_access_scope = SyncStageAccess::AccessScope(sync_event.stage_accesses, barrier.srcAccessMask);
1752 const auto dst_access_scope = SyncStageAccess::AccessScope(dst_stage_accesses, barrier.dstAccessMask);
1753 const SyncBarrier sync_barrier(sync_event.exec_scope, src_access_scope, dst_exec_scope, dst_access_scope);
1754 const ApplyBarrierFunctor<WaitEventBarrierOp> barrier_action({scope_tag, sync_barrier, false /* layout_transition */});
1755 EventSimpleRangeGenerator filtered_range_gen(sync_event.FirstScope(address_type), range);
1756 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barrier_action, &filtered_range_gen);
1757 }
1758}
1759
1760void CommandBufferAccessContext::ApplyGlobalBarriers(SyncEventState &sync_event, VkPipelineStageFlags dstStageMask,
1761 VkPipelineStageFlags dst_exec_scope,
1762 const SyncStageAccessFlags &dst_stage_accesses, uint32_t memory_barrier_count,
1763 const VkMemoryBarrier *pMemoryBarriers, const ResourceUsageTag &tag) {
1764 std::vector<WaitEventBarrierOp> barrier_ops;
1765 barrier_ops.reserve(std::min<uint32_t>(memory_barrier_count, 1));
1766 const auto &scope_tag = sync_event.first_scope_tag;
1767 auto *access_context = GetCurrentAccessContext();
1768 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
1769 const auto &barrier = pMemoryBarriers[barrier_index];
1770 SyncBarrier sync_barrier(sync_event.exec_scope,
1771 SyncStageAccess::AccessScope(sync_event.stage_accesses, barrier.srcAccessMask), dst_exec_scope,
1772 SyncStageAccess::AccessScope(dst_stage_accesses, barrier.dstAccessMask));
1773 barrier_ops.emplace_back(scope_tag, sync_barrier, false);
1774 }
1775 if (0 == memory_barrier_count) {
1776 // If there are no global memory barriers, force an exec barrier
1777 barrier_ops.emplace_back(scope_tag, SyncBarrier(sync_event.exec_scope, 0, dst_exec_scope, 0), false);
1778 }
1779 ApplyBarrierOpsFunctor<WaitEventBarrierOp> barriers_functor(false /* don't resolve */, barrier_ops, tag);
1780 for (const auto address_type : kAddressTypes) {
1781 EventSimpleRangeGenerator filtered_range_gen(sync_event.FirstScope(address_type), kFullRange);
1782 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &filtered_range_gen);
1783 }
1784
1785 // Apply the global barrier to the event itself (for race condition tracking)
1786 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
1787 sync_event.barriers = dstStageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
1788 sync_event.barriers |= dst_exec_scope;
1789}
1790
1791void CommandBufferAccessContext::ApplyGlobalBarriersToEvents(VkPipelineStageFlags srcStageMask, VkPipelineStageFlags src_exec_scope,
1792 VkPipelineStageFlags dstStageMask,
1793 VkPipelineStageFlags dst_exec_scope) {
1794 const bool all_commands_bit = 0 != (srcStageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
1795 for (auto &event_pair : event_state_) {
1796 assert(event_pair.second); // Shouldn't be storing empty
1797 auto &sync_event = *event_pair.second;
1798 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
1799 if ((sync_event.barriers & src_exec_scope) || all_commands_bit) {
1800 sync_event.barriers |= dst_exec_scope;
1801 sync_event.barriers |= dstStageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
1802 }
1803 }
1804}
1805
1806void CommandBufferAccessContext::ApplyImageBarriers(const SyncEventState &sync_event, VkPipelineStageFlags dst_exec_scope,
1807 const SyncStageAccessFlags &dst_stage_accesses, uint32_t barrier_count,
1808 const VkImageMemoryBarrier *barriers, const ResourceUsageTag &tag) {
1809 const auto &scope_tag = sync_event.first_scope_tag;
1810 auto *access_context = GetCurrentAccessContext();
1811 for (uint32_t index = 0; index < barrier_count; index++) {
1812 const auto &barrier = barriers[index];
1813 const auto *image = sync_state_->Get<IMAGE_STATE>(barrier.image);
1814 if (!image) continue;
1815 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
1816 bool layout_transition = barrier.oldLayout != barrier.newLayout;
1817 const auto src_access_scope = SyncStageAccess::AccessScope(sync_event.stage_accesses, barrier.srcAccessMask);
1818 const auto dst_access_scope = SyncStageAccess::AccessScope(dst_stage_accesses, barrier.dstAccessMask);
1819 const SyncBarrier sync_barrier(sync_event.exec_scope, src_access_scope, dst_exec_scope, dst_access_scope);
1820 const ApplyBarrierFunctor<WaitEventBarrierOp> barrier_action({scope_tag, sync_barrier, layout_transition});
1821 const auto base_address = ResourceBaseAddress(*image);
1822 subresource_adapter::ImageRangeGenerator range_gen(*image->fragment_encoder.get(), subresource_range, {0, 0, 0},
1823 image->createInfo.extent, base_address);
1824 const auto address_type = AccessContext::ImageAddressType(*image);
1825 EventImageRangeGenerator filtered_range_gen(sync_event.FirstScope(address_type), range_gen);
1826 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barrier_action, &filtered_range_gen);
1827 }
1828}
John Zulaufb02c1eb2020-10-06 16:33:36 -06001829
John Zulauf355e49b2020-04-24 15:11:15 -06001830// Class CommandBufferAccessContext: Keep track of resource access state information for a specific command buffer
1831bool CommandBufferAccessContext::ValidateBeginRenderPass(const RENDER_PASS_STATE &rp_state,
1832
1833 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001834 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001835 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
1836 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06001837
John Zulauf86356ca2020-10-19 11:46:41 -06001838 assert(pRenderPassBegin);
1839 if (nullptr == pRenderPassBegin) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06001840
John Zulauf86356ca2020-10-19 11:46:41 -06001841 const uint32_t subpass = 0;
John Zulauf355e49b2020-04-24 15:11:15 -06001842
John Zulauf86356ca2020-10-19 11:46:41 -06001843 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
1844 // hasn't happened yet)
1845 const std::vector<AccessContext> empty_context_vector;
1846 AccessContext temp_context(subpass, queue_flags_, rp_state.subpass_dependencies, empty_context_vector,
1847 const_cast<AccessContext *>(&cb_access_context_));
John Zulauf355e49b2020-04-24 15:11:15 -06001848
John Zulauf86356ca2020-10-19 11:46:41 -06001849 // Create a view list
1850 const auto fb_state = sync_state_->Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
1851 assert(fb_state);
1852 if (nullptr == fb_state) return skip;
1853 // NOTE: Must not use COMMAND_BUFFER_STATE variant of this as RecordCmdBeginRenderPass hasn't run and thus
1854 // the activeRenderPass.* fields haven't been set.
1855 const auto views = sync_state_->GetAttachmentViews(*pRenderPassBegin, *fb_state);
1856
1857 // Validate transitions
1858 skip |= temp_context.ValidateLayoutTransitions(*sync_state_, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
1859
1860 // Validate load operations if there were no layout transition hazards
1861 if (!skip) {
1862 temp_context.RecordLayoutTransitions(rp_state, subpass, views, kCurrentCommandTag);
1863 skip |= temp_context.ValidateLoadOperation(*sync_state_, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06001864 }
John Zulauf86356ca2020-10-19 11:46:41 -06001865
John Zulauf355e49b2020-04-24 15:11:15 -06001866 return skip;
1867}
1868
locke-lunarg61870c22020-06-09 14:51:50 -06001869bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1870 const char *func_name) const {
1871 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001872 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001873 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001874 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
1875 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001876 return skip;
1877 }
1878
1879 using DescriptorClass = cvdescriptorset::DescriptorClass;
1880 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1881 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
1882 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
1883 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1884
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001885 for (const auto &stage_state : pipe->stage_state) {
1886 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
1887 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001888 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001889 }
locke-lunarg61870c22020-06-09 14:51:50 -06001890 for (const auto &set_binding : stage_state.descriptor_uses) {
1891 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
1892 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
1893 set_binding.first.second);
1894 const auto descriptor_type = binding_it.GetType();
1895 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1896 auto array_idx = 0;
1897
1898 if (binding_it.IsVariableDescriptorCount()) {
1899 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1900 }
1901 SyncStageAccessIndex sync_index =
1902 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1903
1904 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1905 uint32_t index = i - index_range.start;
1906 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1907 switch (descriptor->GetClass()) {
1908 case DescriptorClass::ImageSampler:
1909 case DescriptorClass::Image: {
1910 const IMAGE_VIEW_STATE *img_view_state = nullptr;
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001911 VkImageLayout image_layout;
locke-lunarg61870c22020-06-09 14:51:50 -06001912 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001913 const auto image_sampler_descriptor = static_cast<const ImageSamplerDescriptor *>(descriptor);
1914 img_view_state = image_sampler_descriptor->GetImageViewState();
1915 image_layout = image_sampler_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001916 } else {
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001917 const auto image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1918 img_view_state = image_descriptor->GetImageViewState();
1919 image_layout = image_descriptor->GetImageLayout();
locke-lunarg61870c22020-06-09 14:51:50 -06001920 }
1921 if (!img_view_state) continue;
1922 const IMAGE_STATE *img_state = img_view_state->image_state.get();
1923 VkExtent3D extent = {};
1924 VkOffset3D offset = {};
1925 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1926 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1927 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
1928 } else {
1929 extent = img_state->createInfo.extent;
1930 }
John Zulauf361fb532020-07-22 10:45:39 -06001931 HazardResult hazard;
1932 const auto &subresource_range = img_view_state->normalized_subresource_range;
1933 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
1934 // Input attachments are subject to raster ordering rules
1935 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
1936 kAttachmentRasterOrder, offset, extent);
1937 } else {
1938 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, offset, extent);
1939 }
John Zulauf33fc1d52020-07-17 11:01:10 -06001940 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001941 skip |= sync_state_->LogError(
1942 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001943 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1944 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001945 func_name, string_SyncHazard(hazard.hazard),
1946 sync_state_->report_data->FormatHandle(img_view_state->image_view).c_str(),
1947 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001948 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001949 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1950 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
1951 set_binding.first.second, index, string_UsageTag(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001952 }
1953 break;
1954 }
1955 case DescriptorClass::TexelBuffer: {
1956 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
1957 if (!buf_view_state) continue;
1958 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06001959 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06001960 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06001961 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001962 skip |= sync_state_->LogError(
1963 buf_view_state->buffer_view, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001964 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1965 func_name, string_SyncHazard(hazard.hazard),
locke-lunarg88dbb542020-06-23 22:05:42 -06001966 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view).c_str(),
1967 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001968 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001969 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1970 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
1971 string_UsageTag(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001972 }
1973 break;
1974 }
1975 case DescriptorClass::GeneralBuffer: {
1976 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
1977 auto buf_state = buffer_descriptor->GetBufferState();
1978 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06001979 const ResourceAccessRange range =
1980 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06001981 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06001982 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06001983 skip |= sync_state_->LogError(
1984 buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001985 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
1986 func_name, string_SyncHazard(hazard.hazard),
1987 sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
locke-lunarg88dbb542020-06-23 22:05:42 -06001988 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(),
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001989 sync_state_->report_data->FormatHandle(pipe->pipeline).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001990 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1991 string_VkDescriptorType(descriptor_type), set_binding.first.second, index,
1992 string_UsageTag(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001993 }
1994 break;
1995 }
1996 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
1997 default:
1998 break;
1999 }
2000 }
2001 }
2002 }
2003 return skip;
2004}
2005
2006void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
2007 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002008 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002009 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002010 GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pipe, &per_sets);
2011 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002012 return;
2013 }
2014
2015 using DescriptorClass = cvdescriptorset::DescriptorClass;
2016 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2017 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
2018 using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor;
2019 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2020
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002021 for (const auto &stage_state : pipe->stage_state) {
2022 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pipe->graphicsPipelineCI.pRasterizationState &&
2023 pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002024 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002025 }
locke-lunarg61870c22020-06-09 14:51:50 -06002026 for (const auto &set_binding : stage_state.descriptor_uses) {
2027 cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set;
2028 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
2029 set_binding.first.second);
2030 const auto descriptor_type = binding_it.GetType();
2031 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2032 auto array_idx = 0;
2033
2034 if (binding_it.IsVariableDescriptorCount()) {
2035 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2036 }
2037 SyncStageAccessIndex sync_index =
2038 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2039
2040 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2041 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2042 switch (descriptor->GetClass()) {
2043 case DescriptorClass::ImageSampler:
2044 case DescriptorClass::Image: {
2045 const IMAGE_VIEW_STATE *img_view_state = nullptr;
2046 if (descriptor->GetClass() == DescriptorClass::ImageSampler) {
2047 img_view_state = static_cast<const ImageSamplerDescriptor *>(descriptor)->GetImageViewState();
2048 } else {
2049 img_view_state = static_cast<const ImageDescriptor *>(descriptor)->GetImageViewState();
2050 }
2051 if (!img_view_state) continue;
2052 const IMAGE_STATE *img_state = img_view_state->image_state.get();
2053 VkExtent3D extent = {};
2054 VkOffset3D offset = {};
2055 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2056 extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2057 offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2058 } else {
2059 extent = img_state->createInfo.extent;
2060 }
2061 current_context_->UpdateAccessState(*img_state, sync_index, img_view_state->normalized_subresource_range,
2062 offset, extent, tag);
2063 break;
2064 }
2065 case DescriptorClass::TexelBuffer: {
2066 auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState();
2067 if (!buf_view_state) continue;
2068 const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002069 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002070 current_context_->UpdateAccessState(*buf_state, sync_index, range, tag);
2071 break;
2072 }
2073 case DescriptorClass::GeneralBuffer: {
2074 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
2075 auto buf_state = buffer_descriptor->GetBufferState();
2076 if (!buf_state) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06002077 const ResourceAccessRange range =
2078 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002079 current_context_->UpdateAccessState(*buf_state, sync_index, range, tag);
2080 break;
2081 }
2082 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2083 default:
2084 break;
2085 }
2086 }
2087 }
2088 }
2089}
2090
2091bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2092 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002093 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2094 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002095 return skip;
2096 }
2097
2098 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2099 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002100 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002101
2102 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002103 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002104 if (binding_description.binding < binding_buffers_size) {
2105 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002106 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002107
locke-lunarg1ae57d62020-11-18 10:49:19 -07002108 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002109 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2110 vertexCount, binding_description.stride);
locke-lunarg61870c22020-06-09 14:51:50 -06002111 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range);
2112 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002113 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002114 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 -06002115 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(),
John Zulauf37ceaed2020-07-03 16:18:15 -06002116 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), string_UsageTag(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002117 }
2118 }
2119 }
2120 return skip;
2121}
2122
2123void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002124 const auto *pipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS);
2125 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002126 return;
2127 }
2128 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2129 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002130 const auto &binding_descriptions_size = pipe->vertex_binding_descriptions_.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002131
2132 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002133 const auto &binding_description = pipe->vertex_binding_descriptions_[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002134 if (binding_description.binding < binding_buffers_size) {
2135 const auto &binding_buffer = binding_buffers[binding_description.binding];
locke-lunarg1ae57d62020-11-18 10:49:19 -07002136 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->destroyed) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002137
locke-lunarg1ae57d62020-11-18 10:49:19 -07002138 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002139 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2140 vertexCount, binding_description.stride);
locke-lunarg61870c22020-06-09 14:51:50 -06002141 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range, tag);
2142 }
2143 }
2144}
2145
2146bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2147 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002148 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->destroyed) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002149 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002150 }
locke-lunarg61870c22020-06-09 14:51:50 -06002151
locke-lunarg1ae57d62020-11-18 10:49:19 -07002152 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002153 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002154 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2155 firstIndex, indexCount, index_size);
locke-lunarg61870c22020-06-09 14:51:50 -06002156 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range);
2157 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002158 skip |= sync_state_->LogError(
John Zulauf59e25072020-07-17 10:55:21 -06002159 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 -06002160 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer).c_str(),
John Zulauf37ceaed2020-07-03 16:18:15 -06002161 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), string_UsageTag(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002162 }
2163
2164 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2165 // We will detect more accurate range in the future.
2166 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2167 return skip;
2168}
2169
2170void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag &tag) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002171 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 -06002172
locke-lunarg1ae57d62020-11-18 10:49:19 -07002173 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002174 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002175 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2176 firstIndex, indexCount, index_size);
locke-lunarg61870c22020-06-09 14:51:50 -06002177 current_context_->UpdateAccessState(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range, tag);
2178
2179 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2180 // We will detect more accurate range in the future.
2181 RecordDrawVertex(UINT32_MAX, 0, tag);
2182}
2183
2184bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002185 bool skip = false;
2186 if (!current_renderpass_context_) return skip;
2187 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(*sync_state_, *cb_state_.get(),
2188 cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
2189 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002190}
2191
2192void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002193 if (current_renderpass_context_) {
locke-lunarg7077d502020-06-18 21:37:26 -06002194 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea,
2195 tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002196 }
locke-lunarg61870c22020-06-09 14:51:50 -06002197}
2198
John Zulauf355e49b2020-04-24 15:11:15 -06002199bool CommandBufferAccessContext::ValidateNextSubpass(const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002200 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002201 if (!current_renderpass_context_) return skip;
John Zulauf1507ee42020-05-18 11:33:09 -06002202 skip |=
2203 current_renderpass_context_->ValidateNextSubpass(*sync_state_, cb_state_->activeRenderPassBeginInfo.renderArea, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002204
2205 return skip;
2206}
2207
2208bool CommandBufferAccessContext::ValidateEndRenderpass(const char *func_name) const {
2209 // TODO: Things to add here.
John Zulauf7635de32020-05-29 17:14:15 -06002210 // Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002211 bool skip = false;
locke-lunarg7077d502020-06-18 21:37:26 -06002212 if (!current_renderpass_context_) return skip;
John Zulauf7635de32020-05-29 17:14:15 -06002213 skip |= current_renderpass_context_->ValidateEndRenderPass(*sync_state_, cb_state_->activeRenderPassBeginInfo.renderArea,
2214 func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002215
2216 return skip;
2217}
2218
2219void CommandBufferAccessContext::RecordBeginRenderPass(const ResourceUsageTag &tag) {
2220 assert(sync_state_);
2221 if (!cb_state_) return;
2222
2223 // Create an access context the current renderpass.
John Zulauf1a224292020-06-30 14:52:13 -06002224 render_pass_contexts_.emplace_back();
John Zulauf16adfc92020-04-08 10:28:33 -06002225 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf1a224292020-06-30 14:52:13 -06002226 current_renderpass_context_->RecordBeginRenderPass(*sync_state_, *cb_state_, &cb_access_context_, queue_flags_, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002227 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf16adfc92020-04-08 10:28:33 -06002228}
2229
John Zulauf355e49b2020-04-24 15:11:15 -06002230void CommandBufferAccessContext::RecordNextSubpass(const RENDER_PASS_STATE &rp_state, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06002231 assert(current_renderpass_context_);
John Zulauf1507ee42020-05-18 11:33:09 -06002232 current_renderpass_context_->RecordNextSubpass(cb_state_->activeRenderPassBeginInfo.renderArea, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002233 current_context_ = &current_renderpass_context_->CurrentContext();
2234}
2235
John Zulauf355e49b2020-04-24 15:11:15 -06002236void CommandBufferAccessContext::RecordEndRenderPass(const RENDER_PASS_STATE &render_pass, const ResourceUsageTag &tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06002237 assert(current_renderpass_context_);
2238 if (!current_renderpass_context_) return;
2239
John Zulauf1a224292020-06-30 14:52:13 -06002240 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, cb_state_->activeRenderPassBeginInfo.renderArea, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002241 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002242 current_renderpass_context_ = nullptr;
2243}
2244
John Zulauf49beb112020-11-04 16:06:31 -07002245bool CommandBufferAccessContext::ValidateSetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2246 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002247 // I'll put this here just in case we need to pass this in for future extension support
2248 const auto cmd = CMD_SETEVENT;
2249 bool skip = false;
2250 const auto *sync_event = GetEventState(event);
2251 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2252
2253 const char *const reset_set =
2254 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2255 "hazards.";
2256 const char *const wait =
2257 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
2258
2259 const auto exec_scope = WithEarlierPipelineStages(ExpandPipelineStages(GetQueueFlags(), stageMask));
2260 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2261 const char *vuid = nullptr;
2262 const char *message = nullptr;
2263 switch (sync_event->last_command) {
2264 case CMD_RESETEVENT:
2265 // Needs a barrier between reset and set
2266 vuid = "SYNC-vkCmdSetEvent-missingbarrier-reset";
2267 message = reset_set;
2268 break;
2269 case CMD_SETEVENT:
2270 // Needs a barrier between set and set
2271 vuid = "SYNC-vkCmdSetEvent-missingbarrier-set";
2272 message = reset_set;
2273 break;
2274 case CMD_WAITEVENTS:
2275 // Needs a barrier or is in second execution scope
2276 vuid = "SYNC-vkCmdSetEvent-missingbarrier-wait";
2277 message = wait;
2278 break;
2279 default:
2280 // The only other valid last command that wasn't one.
2281 assert(sync_event->last_command == CMD_NONE);
2282 break;
2283 }
2284 if (vuid) {
2285 assert(nullptr != message);
2286 const char *const cmd_name = CommandTypeString(cmd);
2287 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2288 cmd_name, CommandTypeString(sync_event->last_command));
2289 }
2290 }
2291
2292 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002293}
2294
John Zulauf4a6105a2020-11-17 15:11:05 -07002295void CommandBufferAccessContext::RecordSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask,
2296 const ResourceUsageTag &tag) {
2297 auto *sync_event = GetEventState(event);
2298 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
2299
2300 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
2301 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
2302 // any issues caused by naive scope setting here.
2303
2304 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
2305 // Given:
2306 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
2307 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
2308
2309 const auto stage_mask = ExpandPipelineStages(GetQueueFlags(), stageMask);
2310 const auto exec_scope = WithEarlierPipelineStages(stage_mask);
2311
2312 sync_event->stage_mask_param = stageMask;
2313
2314 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2315 sync_event->unsynchronized_set = sync_event->last_command;
2316 sync_event->ResetFirstScope();
2317 } else if (sync_event->exec_scope == 0) {
2318 // We only set the scope if there isn't one
2319 sync_event->stage_mask = stage_mask;
2320 sync_event->exec_scope = exec_scope;
2321 sync_event->stage_accesses = SyncStageAccess::AccessScopeByStage(sync_event->stage_mask);
2322
2323 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
2324 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
2325 if (access.second.InSourceScopeOrChain(sync_event->exec_scope, sync_event->stage_accesses)) {
2326 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
2327 }
2328 };
2329 GetCurrentAccessContext()->ForAll(set_scope);
2330 sync_event->unsynchronized_set = CMD_NONE;
2331 sync_event->first_scope_tag = tag;
2332 }
2333 sync_event->last_command = CMD_SETEVENT;
2334 sync_event->barriers = 0U;
2335}
John Zulauf49beb112020-11-04 16:06:31 -07002336
2337bool CommandBufferAccessContext::ValidateResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
2338 VkPipelineStageFlags stageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002339 // I'll put this here just in case we need to pass this in for future extension support
2340 const auto cmd = CMD_RESETEVENT;
2341
2342 bool skip = false;
2343 // TODO: EVENTS:
2344 // What is it we need to check... that we've had a reset since a set? Set/Set seems ill formed...
2345 const auto *sync_event = GetEventState(event);
2346 if (!sync_event) return false; // Core, Lifetimes, or Param check needs to catch invalid events.
2347
2348 const char *const set_wait =
2349 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
2350 "hazards.";
2351 const char *message = set_wait; // Only one message this call.
2352 const auto exec_scope = WithEarlierPipelineStages(ExpandPipelineStages(GetQueueFlags(), stageMask));
2353 if (!sync_event->HasBarrier(stageMask, exec_scope)) {
2354 const char *vuid = nullptr;
2355 switch (sync_event->last_command) {
2356 case CMD_SETEVENT:
2357 // Needs a barrier between set and reset
2358 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
2359 break;
2360 case CMD_WAITEVENTS: {
2361 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
2362 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
2363 break;
2364 }
2365 default:
2366 // The only other valid last command that wasn't one.
2367 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT));
2368 break;
2369 }
2370 if (vuid) {
2371 const char *const cmd_name = CommandTypeString(cmd);
2372 skip |= sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2373 cmd_name, CommandTypeString(sync_event->last_command));
2374 }
2375 }
2376 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002377}
2378
John Zulauf4a6105a2020-11-17 15:11:05 -07002379void CommandBufferAccessContext::RecordResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
2380 const auto cmd = CMD_RESETEVENT;
2381 auto *sync_event = GetEventState(event);
2382 if (!sync_event) return;
John Zulauf49beb112020-11-04 16:06:31 -07002383
John Zulauf4a6105a2020-11-17 15:11:05 -07002384 // Clear out the first sync scope, any races vs. wait or set are reported, so we'll keep the bookkeeping simple assuming
2385 // the safe case
2386 for (const auto address_type : kAddressTypes) {
2387 sync_event->first_scope[static_cast<size_t>(address_type)].clear();
2388 }
2389
2390 // Update the event state
2391 sync_event->last_command = cmd;
2392 sync_event->unsynchronized_set = CMD_NONE;
2393 sync_event->ResetFirstScope();
2394 sync_event->barriers = 0U;
2395}
2396
2397bool CommandBufferAccessContext::ValidateWaitEvents(uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
2398 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
2399 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
John Zulauf49beb112020-11-04 16:06:31 -07002400 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
2401 uint32_t imageMemoryBarrierCount,
2402 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07002403 const auto cmd = CMD_WAITEVENTS;
2404 const char *const ignored = "Wait operation is ignored for this event.";
2405 bool skip = false;
2406
2407 if (srcStageMask & VK_PIPELINE_STAGE_HOST_BIT) {
2408 const char *const cmd_name = CommandTypeString(cmd);
2409 const char *const vuid = "SYNC-vkCmdWaitEvents-hostevent-unsupported";
2410 skip = sync_state_->LogWarning(cb_state_->commandBuffer, vuid,
2411 "%s, srcStageMask includes %s, unsupported by synchronization validaton.", cmd_name,
2412 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT), ignored);
2413 }
2414
2415 VkPipelineStageFlags event_stage_masks = 0U;
2416 for (uint32_t event_index = 0; event_index < eventCount; event_index++) {
2417 const auto event = pEvents[event_index];
2418 const auto *sync_event = GetEventState(event);
2419 if (!sync_event) continue; // Core, Lifetimes, or Param check needs to catch invalid events.
2420
2421 event_stage_masks |= sync_event->stage_mask_param;
2422 const auto ignore_reason = sync_event->IsIgnoredByWait(srcStageMask);
2423 if (ignore_reason) {
2424 switch (ignore_reason) {
2425 case SyncEventState::ResetWaitRace: {
2426 const char *const cmd_name = CommandTypeString(cmd);
2427 const char *const vuid = "SYNC-vkCmdWaitEvents-missingbarrier-reset";
2428 const char *const message =
2429 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
2430 skip |=
2431 sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2432 cmd_name, CommandTypeString(sync_event->last_command), ignored);
2433 break;
2434 }
2435 case SyncEventState::SetRace: {
2436 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for this
2437 // event
2438 const char *const cmd_name = CommandTypeString(cmd);
2439 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
2440 const char *const message =
2441 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, % %s";
2442 const char *const reason = "First synchronization scope is undefined.";
2443 skip |=
2444 sync_state_->LogError(event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2445 CommandTypeString(sync_event->last_command), reason, ignored);
2446 break;
2447 }
2448 case SyncEventState::MissingStageBits: {
2449 const VkPipelineStageFlags missing_bits = sync_event->stage_mask_param & ~srcStageMask;
2450 // Issue error message that event waited for is not in wait events scope
2451 const char *const cmd_name = CommandTypeString(cmd);
2452 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
2453 const char *const message =
2454 "%s: %s stageMask 0x%" PRIx32 " includes bits not present in srcStageMask 0x%" PRIx32
2455 ". Bits missing from srcStageMask %s. %s";
2456 skip |= sync_state_->LogError(
2457 event, vuid, message, cmd_name, sync_state_->report_data->FormatHandle(event).c_str(),
2458 sync_event->stage_mask_param, srcStageMask, string_VkPipelineStageFlags(missing_bits).c_str(), ignored);
2459 break;
2460 }
2461 default:
2462 assert(ignore_reason == SyncEventState::NotIgnored);
2463 }
2464 } else if (imageMemoryBarrierCount) {
2465 const auto *context = GetCurrentAccessContext();
2466 assert(context);
2467 for (uint32_t barrier_index = 0; barrier_index < imageMemoryBarrierCount; barrier_index++) {
2468 const auto &barrier = pImageMemoryBarriers[barrier_index];
2469 if (barrier.oldLayout == barrier.newLayout) continue;
2470 const auto *image_state = sync_state_->Get<IMAGE_STATE>(barrier.image);
2471 if (!image_state) continue;
2472 auto subresource_range = NormalizeSubresourceRange(image_state->createInfo, barrier.subresourceRange);
2473 const auto src_access_scope = SyncStageAccess::AccessScope(sync_event->stage_accesses, barrier.srcAccessMask);
2474 const auto hazard =
2475 context->DetectImageBarrierHazard(*image_state, sync_event->exec_scope, src_access_scope, subresource_range,
2476 *sync_event, AccessContext::DetectOptions::kDetectAll);
2477 if (hazard.hazard) {
2478 const char *const cmd_name = CommandTypeString(cmd);
2479 skip |= sync_state_->LogError(barrier.image, string_SyncHazardVUID(hazard.hazard),
2480 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", cmd_name,
2481 string_SyncHazard(hazard.hazard), barrier_index,
2482 sync_state_->report_data->FormatHandle(barrier.image).c_str(),
2483 string_UsageTag(hazard).c_str());
2484 break;
2485 }
2486 }
2487 }
2488 }
2489
2490 // Note that we can't check for HOST in pEvents as we don't track that set event type
2491 const auto extra_stage_bits = (srcStageMask & ~VK_PIPELINE_STAGE_HOST_BIT) & ~event_stage_masks;
2492 if (extra_stage_bits) {
2493 // Issue error message that event waited for is not in wait events scope
2494 const char *const cmd_name = CommandTypeString(cmd);
2495 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
2496 const char *const message =
2497 "%s: srcStageMask 0x%" PRIx32 " contains stages not present in pEvents stageMask. Extra stages are %s.";
2498 skip |= sync_state_->LogError(cb_state_->commandBuffer, vuid, message, cmd_name, srcStageMask,
2499 string_VkPipelineStageFlags(extra_stage_bits).c_str());
2500 }
2501 return skip;
John Zulauf49beb112020-11-04 16:06:31 -07002502}
2503
2504void CommandBufferAccessContext::RecordWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
2505 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
2506 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
2507 uint32_t bufferMemoryBarrierCount,
2508 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
2509 uint32_t imageMemoryBarrierCount,
John Zulauf4a6105a2020-11-17 15:11:05 -07002510 const VkImageMemoryBarrier *pImageMemoryBarriers, const ResourceUsageTag &tag) {
2511 auto *access_context = GetCurrentAccessContext();
2512 assert(access_context);
2513 if (!access_context) return;
2514
2515 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
2516 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
2517 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
2518 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here
2519 access_context->ResolvePreviousAccesses();
2520
2521 const auto dst_stage_mask = ExpandPipelineStages(GetQueueFlags(), dstStageMask);
2522 auto dst_stage_accesses = SyncStageAccess::AccessScopeByStage(dst_stage_mask);
2523 const auto dst_exec_scope = WithLaterPipelineStages(dst_stage_mask);
2524 for (uint32_t event_index = 0; event_index < eventCount; event_index++) {
2525 const auto event = pEvents[event_index];
2526 auto *sync_event = GetEventState(event);
2527 if (!sync_event) continue;
2528
2529 sync_event->last_command = CMD_WAITEVENTS;
2530
2531 if (!sync_event->IsIgnoredByWait(srcStageMask)) {
2532 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
2533 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
2534 // of the barriers is maintained.
2535 ApplyBufferBarriers(*sync_event, dst_exec_scope, dst_stage_accesses, bufferMemoryBarrierCount, pBufferMemoryBarriers);
2536 ApplyImageBarriers(*sync_event, dst_exec_scope, dst_stage_accesses, imageMemoryBarrierCount, pImageMemoryBarriers, tag);
2537 ApplyGlobalBarriers(*sync_event, dstStageMask, dst_exec_scope, dst_stage_accesses, memoryBarrierCount, pMemoryBarriers,
2538 tag);
2539 } else {
2540 // We ignored this wait, so we don't have any effective synchronization barriers for it.
2541 sync_event->barriers = 0U;
2542 }
2543 }
2544
2545 // Apply the pending barriers
2546 ResolvePendingBarrierFunctor apply_pending_action(tag);
2547 access_context->ApplyGlobalBarriers(apply_pending_action);
2548}
2549
2550void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2551 // Erase is okay with the key not being
2552 event_state_.erase(event);
2553}
2554
2555SyncEventState *CommandBufferAccessContext::GetEventState(VkEvent event) {
2556 auto &event_up = event_state_[event];
2557 if (!event_up) {
2558 auto event_atate = sync_state_->GetShared<EVENT_STATE>(event);
2559 event_up.reset(new SyncEventState(event_atate));
2560 }
2561 return event_up.get();
2562}
2563
2564const SyncEventState *CommandBufferAccessContext::GetEventState(VkEvent event) const {
2565 auto event_it = event_state_.find(event);
2566 if (event_it == event_state_.cend()) {
2567 return nullptr;
2568 }
2569 return event_it->second.get();
2570}
John Zulauf49beb112020-11-04 16:06:31 -07002571
locke-lunarg61870c22020-06-09 14:51:50 -06002572bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const SyncValidator &sync_state, const CMD_BUFFER_STATE &cmd,
2573 const VkRect2D &render_area, const char *func_name) const {
2574 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002575 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2576 if (!pipe ||
2577 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002578 return skip;
2579 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002580 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002581 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2582 VkExtent3D extent = CastTo3D(render_area.extent);
2583 VkOffset3D offset = CastTo3D(render_area.offset);
locke-lunarg37047832020-06-12 13:44:45 -06002584
John Zulauf1a224292020-06-30 14:52:13 -06002585 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002586 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002587 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2588 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002589 if (location >= subpass.colorAttachmentCount ||
2590 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002591 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002592 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002593 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf1a224292020-06-30 14:52:13 -06002594 HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
2595 kColorAttachmentRasterOrder, offset, extent);
locke-lunarg96dc9632020-06-10 17:22:18 -06002596 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002597 skip |= sync_state.LogError(img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002598 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002599 func_name, string_SyncHazard(hazard.hazard),
2600 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2601 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauf37ceaed2020-07-03 16:18:15 -06002602 location, string_UsageTag(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002603 }
2604 }
2605 }
locke-lunarg37047832020-06-12 13:44:45 -06002606
2607 // PHASE1 TODO: Add layout based read/vs. write selection.
2608 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002609 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002610 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002611 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002612 bool depth_write = false, stencil_write = false;
2613
2614 // PHASE1 TODO: These validation should be in core_checks.
2615 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002616 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2617 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002618 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2619 depth_write = true;
2620 }
2621 // PHASE1 TODO: It needs to check if stencil is writable.
2622 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2623 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2624 // PHASE1 TODO: These validation should be in core_checks.
2625 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002626 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002627 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2628 stencil_write = true;
2629 }
2630
2631 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2632 if (depth_write) {
2633 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002634 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2635 kDepthStencilAttachmentRasterOrder, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002636 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002637 skip |= sync_state.LogError(
2638 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002639 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002640 func_name, string_SyncHazard(hazard.hazard),
2641 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2642 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauf37ceaed2020-07-03 16:18:15 -06002643 string_UsageTag(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002644 }
2645 }
2646 if (stencil_write) {
2647 HazardResult hazard =
John Zulauf1a224292020-06-30 14:52:13 -06002648 current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2649 kDepthStencilAttachmentRasterOrder, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002650 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002651 skip |= sync_state.LogError(
2652 img_view_state->image_view, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002653 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002654 func_name, string_SyncHazard(hazard.hazard),
2655 sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(),
2656 sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass,
John Zulauf37ceaed2020-07-03 16:18:15 -06002657 string_UsageTag(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002658 }
locke-lunarg61870c22020-06-09 14:51:50 -06002659 }
2660 }
2661 return skip;
2662}
2663
locke-lunarg96dc9632020-06-10 17:22:18 -06002664void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area,
2665 const ResourceUsageTag &tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002666 const auto *pipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS);
2667 if (!pipe ||
2668 (pipe->graphicsPipelineCI.pRasterizationState && pipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002669 return;
2670 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002671 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002672 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
2673 VkExtent3D extent = CastTo3D(render_area.extent);
2674 VkOffset3D offset = CastTo3D(render_area.offset);
2675
John Zulauf1a224292020-06-30 14:52:13 -06002676 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002677 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002678 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2679 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002680 if (location >= subpass.colorAttachmentCount ||
2681 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002682 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002683 }
locke-lunarg96dc9632020-06-10 17:22:18 -06002684 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment];
John Zulauf1a224292020-06-30 14:52:13 -06002685 current_context.UpdateAccessState(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, offset, extent,
2686 0, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002687 }
2688 }
locke-lunarg37047832020-06-12 13:44:45 -06002689
2690 // PHASE1 TODO: Add layout based read/vs. write selection.
2691 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002692 if (pipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment &&
locke-lunarg37047832020-06-12 13:44:45 -06002693 subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) {
locke-lunarg61870c22020-06-09 14:51:50 -06002694 const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment];
locke-lunarg37047832020-06-12 13:44:45 -06002695 bool depth_write = false, stencil_write = false;
2696
2697 // PHASE1 TODO: These validation should be in core_checks.
2698 if (!FormatIsStencilOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002699 pipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable &&
2700 pipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002701 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2702 depth_write = true;
2703 }
2704 // PHASE1 TODO: It needs to check if stencil is writable.
2705 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2706 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2707 // PHASE1 TODO: These validation should be in core_checks.
2708 if (!FormatIsDepthOnly(img_view_state->create_info.format) &&
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002709 pipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002710 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2711 stencil_write = true;
2712 }
2713
2714 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2715 if (depth_write) {
John Zulauf1a224292020-06-30 14:52:13 -06002716 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, offset,
2717 extent, VK_IMAGE_ASPECT_DEPTH_BIT, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002718 }
2719 if (stencil_write) {
John Zulauf1a224292020-06-30 14:52:13 -06002720 current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, offset,
2721 extent, VK_IMAGE_ASPECT_STENCIL_BIT, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002722 }
locke-lunarg61870c22020-06-09 14:51:50 -06002723 }
2724}
2725
John Zulauf1507ee42020-05-18 11:33:09 -06002726bool RenderPassAccessContext::ValidateNextSubpass(const SyncValidator &sync_state, const VkRect2D &render_area,
2727 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002728 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002729 bool skip = false;
John Zulaufb027cdb2020-05-21 14:25:22 -06002730 skip |= CurrentContext().ValidateResolveOperations(sync_state, *rp_state_, render_area, attachment_views_, func_name,
2731 current_subpass_);
John Zulaufaff20662020-06-01 14:07:58 -06002732 skip |= CurrentContext().ValidateStoreOperation(sync_state, *rp_state_, render_area, current_subpass_, attachment_views_,
2733 func_name);
2734
John Zulauf355e49b2020-04-24 15:11:15 -06002735 const auto next_subpass = current_subpass_ + 1;
John Zulauf1507ee42020-05-18 11:33:09 -06002736 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf7635de32020-05-29 17:14:15 -06002737 skip |= next_context.ValidateLayoutTransitions(sync_state, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002738 if (!skip) {
2739 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2740 // on a copy of the (empty) next context.
2741 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2742 AccessContext temp_context(next_context);
2743 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kCurrentCommandTag);
2744 skip |= temp_context.ValidateLoadOperation(sync_state, *rp_state_, render_area, next_subpass, attachment_views_, func_name);
2745 }
John Zulauf7635de32020-05-29 17:14:15 -06002746 return skip;
2747}
2748bool RenderPassAccessContext::ValidateEndRenderPass(const SyncValidator &sync_state, const VkRect2D &render_area,
2749 const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002750 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002751 bool skip = false;
2752 skip |= CurrentContext().ValidateResolveOperations(sync_state, *rp_state_, render_area, attachment_views_, func_name,
2753 current_subpass_);
John Zulaufaff20662020-06-01 14:07:58 -06002754 skip |= CurrentContext().ValidateStoreOperation(sync_state, *rp_state_, render_area, current_subpass_, attachment_views_,
2755 func_name);
John Zulauf7635de32020-05-29 17:14:15 -06002756 skip |= ValidateFinalSubpassLayoutTransitions(sync_state, render_area, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002757 return skip;
2758}
2759
John Zulauf7635de32020-05-29 17:14:15 -06002760AccessContext *RenderPassAccessContext::CreateStoreResolveProxy(const VkRect2D &render_area) const {
2761 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, render_area, attachment_views_);
2762}
2763
2764bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const SyncValidator &sync_state, const VkRect2D &render_area,
2765 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002766 bool skip = false;
2767
John Zulauf7635de32020-05-29 17:14:15 -06002768 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2769 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2770 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2771 // to apply and only copy then, if this proves a hot spot.
2772 std::unique_ptr<AccessContext> proxy_for_current;
2773
John Zulauf355e49b2020-04-24 15:11:15 -06002774 // Validate the "finalLayout" transitions to external
2775 // Get them from where there we're hidding in the extra entry.
2776 const auto &final_transitions = rp_state_->subpass_transitions.back();
2777 for (const auto &transition : final_transitions) {
2778 const auto &attach_view = attachment_views_[transition.attachment];
2779 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
2780 assert(trackback.context); // Transitions are given implicit transitions if the StateTracker is working correctly
John Zulauf7635de32020-05-29 17:14:15 -06002781 auto *context = trackback.context;
2782
2783 if (transition.prev_pass == current_subpass_) {
2784 if (!proxy_for_current) {
2785 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
2786 proxy_for_current.reset(CreateStoreResolveProxy(render_area));
2787 }
2788 context = proxy_for_current.get();
2789 }
2790
John Zulaufa0a98292020-09-18 09:30:10 -06002791 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2792 const auto merged_barrier = MergeBarriers(trackback.barriers);
2793 auto hazard = context->DetectImageBarrierHazard(*attach_view->image_state, merged_barrier.src_exec_scope,
2794 merged_barrier.src_access_scope, attach_view->normalized_subresource_range,
2795 AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002796 if (hazard.hazard) {
2797 skip |= sync_state.LogError(rp_state_->renderPass, string_SyncHazardVUID(hazard.hazard),
2798 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf389c34b2020-07-28 11:19:35 -06002799 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06002800 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
John Zulauf389c34b2020-07-28 11:19:35 -06002801 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf37ceaed2020-07-03 16:18:15 -06002802 string_UsageTag(hazard).c_str());
John Zulauf355e49b2020-04-24 15:11:15 -06002803 }
2804 }
2805 return skip;
2806}
2807
2808void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag &tag) {
2809 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002810 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002811}
2812
John Zulauf1507ee42020-05-18 11:33:09 -06002813void RenderPassAccessContext::RecordLoadOperations(const VkRect2D &render_area, const ResourceUsageTag &tag) {
2814 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2815 auto &subpass_context = subpass_contexts_[current_subpass_];
2816 VkExtent3D extent = CastTo3D(render_area.extent);
2817 VkOffset3D offset = CastTo3D(render_area.offset);
2818
2819 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2820 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
2821 if (attachment_views_[i] == nullptr) continue; // UNUSED
2822 const auto &view = *attachment_views_[i];
2823 const IMAGE_STATE *image = view.image_state.get();
2824 if (image == nullptr) continue;
2825
2826 const auto &ci = attachment_ci[i];
2827 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002828 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002829 const bool is_color = !(has_depth || has_stencil);
2830
2831 if (is_color) {
2832 subpass_context.UpdateAccessState(*image, ColorLoadUsage(ci.loadOp), view.normalized_subresource_range, offset,
2833 extent, tag);
2834 } else {
2835 auto update_range = view.normalized_subresource_range;
2836 if (has_depth) {
2837 update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
2838 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.loadOp), update_range, offset, extent, tag);
2839 }
2840 if (has_stencil) {
2841 update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
2842 subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.stencilLoadOp), update_range, offset, extent,
2843 tag);
2844 }
2845 }
2846 }
2847 }
2848}
2849
John Zulauf355e49b2020-04-24 15:11:15 -06002850void RenderPassAccessContext::RecordBeginRenderPass(const SyncValidator &state, const CMD_BUFFER_STATE &cb_state,
John Zulauf1a224292020-06-30 14:52:13 -06002851 const AccessContext *external_context, VkQueueFlags queue_flags,
2852 const ResourceUsageTag &tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002853 current_subpass_ = 0;
locke-lunargaecf2152020-05-12 17:15:41 -06002854 rp_state_ = cb_state.activeRenderPass.get();
John Zulauf355e49b2020-04-24 15:11:15 -06002855 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
2856 // Add this for all subpasses here so that they exsist during next subpass validation
2857 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002858 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulauf355e49b2020-04-24 15:11:15 -06002859 }
2860 attachment_views_ = state.GetCurrentAttachmentViews(cb_state);
2861
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07002862 subpass_contexts_[current_subpass_].SetStartTag(tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002863 RecordLayoutTransitions(tag);
John Zulauf1507ee42020-05-18 11:33:09 -06002864 RecordLoadOperations(cb_state.activeRenderPassBeginInfo.renderArea, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002865}
John Zulauf1507ee42020-05-18 11:33:09 -06002866
2867void RenderPassAccessContext::RecordNextSubpass(const VkRect2D &render_area, const ResourceUsageTag &tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002868 // Resolves are against *prior* subpass context and thus *before* the subpass increment
2869 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulaufaff20662020-06-01 14:07:58 -06002870 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulauf7635de32020-05-29 17:14:15 -06002871
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002872 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2873 // subpass, so their tag needs to be different from the layout and load operations below.
2874 ResourceUsageTag next_tag = tag;
2875 next_tag.index++;
John Zulauf355e49b2020-04-24 15:11:15 -06002876 current_subpass_++;
2877 assert(current_subpass_ < subpass_contexts_.size());
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002878 subpass_contexts_[current_subpass_].SetStartTag(next_tag);
2879 RecordLayoutTransitions(next_tag);
2880 RecordLoadOperations(render_area, next_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002881}
2882
John Zulauf1a224292020-06-30 14:52:13 -06002883void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const VkRect2D &render_area,
2884 const ResourceUsageTag &tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002885 // Add the resolve and store accesses
John Zulauf7635de32020-05-29 17:14:15 -06002886 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulaufaff20662020-06-01 14:07:58 -06002887 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag);
John Zulauf7635de32020-05-29 17:14:15 -06002888
John Zulauf355e49b2020-04-24 15:11:15 -06002889 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002890 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002891
2892 // Add the "finalLayout" transitions to external
2893 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002894 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2895 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2896 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002897 const auto &final_transitions = rp_state_->subpass_transitions.back();
2898 for (const auto &transition : final_transitions) {
2899 const auto &attachment = attachment_views_[transition.attachment];
2900 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufaa97d8b2020-07-14 10:58:13 -06002901 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.context);
John Zulauf1e331ec2020-12-04 18:29:38 -07002902 std::vector<PipelineBarrierOp> barrier_ops;
2903 barrier_ops.reserve(last_trackback.barriers.size());
2904 for (const auto &barrier : last_trackback.barriers) {
2905 barrier_ops.emplace_back(barrier, true);
2906 }
2907 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, barrier_ops, tag);
2908 external_context->UpdateResourceAccess(*attachment->image_state, attachment->normalized_subresource_range, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002909 }
2910}
2911
John Zulauf3d84f1b2020-03-09 13:33:25 -06002912SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &barrier) {
2913 const auto src_stage_mask = ExpandPipelineStages(queue_flags, barrier.srcStageMask);
2914 src_exec_scope = WithEarlierPipelineStages(src_stage_mask);
2915 src_access_scope = SyncStageAccess::AccessScope(src_stage_mask, barrier.srcAccessMask);
2916 const auto dst_stage_mask = ExpandPipelineStages(queue_flags, barrier.dstStageMask);
2917 dst_exec_scope = WithLaterPipelineStages(dst_stage_mask);
2918 dst_access_scope = SyncStageAccess::AccessScope(dst_stage_mask, barrier.dstAccessMask);
2919}
2920
John Zulaufb02c1eb2020-10-06 16:33:36 -06002921// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2922void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
2923 for (const auto &barrier : barriers) {
2924 ApplyBarrier(barrier, layout_transition);
2925 }
2926}
2927
John Zulauf89311b42020-09-29 16:28:47 -06002928// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2929// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2930// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufb02c1eb2020-10-06 16:33:36 -06002931void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, const ResourceUsageTag &tag) {
2932 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002933 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002934 assert(!pending_write_dep_chain);
John Zulaufa0a98292020-09-18 09:30:10 -06002935 for (const auto &barrier : barriers) {
John Zulauf89311b42020-09-29 16:28:47 -06002936 ApplyBarrier(barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002937 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002938 ApplyPendingBarriers(tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002939}
John Zulauf9cb530d2019-09-30 14:14:10 -06002940HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2941 HazardResult hazard;
2942 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002943 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002944 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002945 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002946 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002947 }
2948 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002949 // Write operation:
2950 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2951 // If reads exists -- test only against them because either:
2952 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2953 // * 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
2954 // the current write happens after the reads, so just test the write against the reades
2955 // Otherwise test against last_write
2956 //
2957 // Look for casus belli for WAR
2958 if (last_read_count) {
2959 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
2960 const auto &read_access = last_reads[read_index];
2961 if (IsReadHazard(usage_stage, read_access)) {
2962 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2963 break;
2964 }
2965 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002966 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002967 // Write-After-Write check -- if we have a previous write to test against
2968 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002969 }
2970 }
2971 return hazard;
2972}
2973
John Zulauf69133422020-05-20 14:55:53 -06002974HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrderingBarrier &ordering) const {
2975 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2976 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002977 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002978 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002979 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2980 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002981 if (IsRead(usage_bit)) {
2982 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2983 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2984 if (is_raw_hazard) {
2985 // NOTE: we know last_write is non-zero
2986 // See if the ordering rules save us from the simple RAW check above
2987 // First check to see if the current usage is covered by the ordering rules
2988 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2989 const bool usage_is_ordered =
2990 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2991 if (usage_is_ordered) {
2992 // Now see of the most recent write (or a subsequent read) are ordered
2993 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2994 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002995 }
2996 }
John Zulauf4285ee92020-09-23 10:20:52 -06002997 if (is_raw_hazard) {
2998 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
2999 }
John Zulauf361fb532020-07-22 10:45:39 -06003000 } else {
3001 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003002 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulauf361fb532020-07-22 10:45:39 -06003003 if (last_read_count) {
John Zulauf361fb532020-07-22 10:45:39 -06003004 // Look for any WAR hazards outside the ordered set of stages
John Zulauf4285ee92020-09-23 10:20:52 -06003005 VkPipelineStageFlags ordered_stages = 0;
3006 if (usage_write_is_ordered) {
3007 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
3008 ordered_stages = GetOrderedStages(ordering);
3009 }
3010 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3011 if ((ordered_stages & last_read_stages) != last_read_stages) {
3012 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
3013 const auto &read_access = last_reads[read_index];
3014 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3015 if (IsReadHazard(usage_stage, read_access)) {
3016 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3017 break;
3018 }
John Zulaufd14743a2020-07-03 09:42:39 -06003019 }
3020 }
John Zulauf4285ee92020-09-23 10:20:52 -06003021 } else if (!(last_write_is_ordered && usage_write_is_ordered)) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003022 if (last_write.any() && IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003023 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003024 }
John Zulauf69133422020-05-20 14:55:53 -06003025 }
3026 }
3027 return hazard;
3028}
3029
John Zulauf2f952d22020-02-10 11:34:51 -07003030// Asynchronous Hazards occur between subpasses with no connection through the DAG
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003031HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag &start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003032 HazardResult hazard;
3033 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003034 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3035 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3036 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003037 if (IsRead(usage)) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003038 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06003039 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003040 }
3041 } else {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003042 if (last_write.any() && (write_tag.index >= start_tag.index)) {
John Zulauf59e25072020-07-17 10:55:21 -06003043 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003044 } else if (last_read_count > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003045 // Any reads during the other subpass will conflict with this write, so we need to check them all.
3046 for (uint32_t i = 0; i < last_read_count; i++) {
3047 if (last_reads[i].tag.index >= start_tag.index) {
3048 hazard.Set(this, usage_index, WRITE_RACING_READ, last_reads[i].access, last_reads[i].tag);
3049 break;
3050 }
3051 }
John Zulauf2f952d22020-02-10 11:34:51 -07003052 }
3053 }
3054 return hazard;
3055}
3056
John Zulauf36bcf6a2020-02-03 15:12:52 -07003057HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003058 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003059 // Only supporting image layout transitions for now
3060 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3061 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003062 // only test for WAW if there no intervening read operations.
3063 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3064 if (last_read_count) {
John Zulauf355e49b2020-04-24 15:11:15 -06003065 // Look at the reads if any
John Zulauf0cb5be22020-01-23 12:18:22 -07003066 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
John Zulauf36bcf6a2020-02-03 15:12:52 -07003067 const auto &read_access = last_reads[read_index];
John Zulauf4a6105a2020-11-17 15:11:05 -07003068 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003069 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003070 break;
3071 }
3072 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003073 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3074 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3075 }
3076
3077 return hazard;
3078}
3079
3080HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope,
3081 const SyncStageAccessFlags &src_access_scope,
3082 const ResourceUsageTag &event_tag) const {
3083 // Only supporting image layout transitions for now
3084 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3085 HazardResult hazard;
3086 // only test for WAW if there no intervening read operations.
3087 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3088
3089 if (last_read_count) {
3090 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
3091 // first scope, or they are a hazard.
3092 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
3093 const auto &read_access = last_reads[read_index];
3094 if (read_access.tag.IsBefore(event_tag)) {
3095 // The read is in the events first synchronization scope, so we use a barrier hazard check
3096 // If the read stage is not in the src sync scope
3097 // *AND* not execution chained with an existing sync barrier (that's the or)
3098 // then the barrier access is unsafe (R/W after R)
3099 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
3100 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3101 break;
3102 }
3103 } else {
3104 // The read not in the event first sync scope and so is a hazard vs. the layout transition
3105 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3106 }
3107 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003108 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003109 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
3110 if (write_tag.IsBefore(event_tag)) {
3111 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3112 // So do a normal barrier hazard check
3113 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3114 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3115 }
3116 } else {
3117 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06003118 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3119 }
John Zulaufd14743a2020-07-03 09:42:39 -06003120 }
John Zulauf361fb532020-07-22 10:45:39 -06003121
John Zulauf0cb5be22020-01-23 12:18:22 -07003122 return hazard;
3123}
3124
John Zulauf5f13a792020-03-10 07:31:21 -06003125// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3126// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3127// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3128void ResourceAccessState::Resolve(const ResourceAccessState &other) {
3129 if (write_tag.IsBefore(other.write_tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003130 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3131 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003132 *this = other;
3133 } else if (!other.write_tag.IsBefore(write_tag)) {
3134 // This is the *equals* case for write operations, we merged the write barriers and the read state (but without the
3135 // dependency chaining logic or any stage expansion)
3136 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003137 pending_write_barriers |= other.pending_write_barriers;
3138 pending_layout_transition |= other.pending_layout_transition;
3139 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003140
John Zulaufd14743a2020-07-03 09:42:39 -06003141 // Merge the read states
John Zulauf4285ee92020-09-23 10:20:52 -06003142 const auto pre_merge_count = last_read_count;
3143 const auto pre_merge_stages = last_read_stages;
John Zulauf5f13a792020-03-10 07:31:21 -06003144 for (uint32_t other_read_index = 0; other_read_index < other.last_read_count; other_read_index++) {
3145 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003146 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003147 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003148 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3149 // but we should wait on profiling data for that.
3150 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003151 auto &my_read = last_reads[my_read_index];
3152 if (other_read.stage == my_read.stage) {
3153 if (my_read.tag.IsBefore(other_read.tag)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003154 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003155 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003156 my_read.tag = other_read.tag;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003157 my_read.pending_dep_chain = other_read.pending_dep_chain;
3158 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3159 // May require tracking more than one access per stage.
3160 my_read.barriers = other_read.barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003161 if (my_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
3162 // Since I'm overwriting the fragement stage read, also update the input attachment info
3163 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003164 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003165 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003166 } else if (other_read.tag.IsBefore(my_read.tag)) {
3167 // The read tags match so merge the barriers
3168 my_read.barriers |= other_read.barriers;
3169 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003170 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003171
John Zulauf5f13a792020-03-10 07:31:21 -06003172 break;
3173 }
3174 }
3175 } else {
3176 // The other read stage doesn't exist in this, so add it.
3177 last_reads[last_read_count] = other_read;
3178 last_read_count++;
3179 last_read_stages |= other_read.stage;
John Zulauf4285ee92020-09-23 10:20:52 -06003180 if (other_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003181 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003182 }
John Zulauf5f13a792020-03-10 07:31:21 -06003183 }
3184 }
John Zulauf361fb532020-07-22 10:45:39 -06003185 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003186 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3187 // ignore it.
John Zulauf5f13a792020-03-10 07:31:21 -06003188}
3189
John Zulauf9cb530d2019-09-30 14:14:10 -06003190void ResourceAccessState::Update(SyncStageAccessIndex usage_index, const ResourceUsageTag &tag) {
3191 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3192 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003193 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003194 // Mulitple outstanding reads may be of interest and do dependency chains independently
3195 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3196 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003197 uint32_t update_index = kStageCount;
John Zulauf9cb530d2019-09-30 14:14:10 -06003198 if (usage_stage & last_read_stages) {
3199 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
John Zulauf4285ee92020-09-23 10:20:52 -06003200 if (last_reads[read_index].stage == usage_stage) {
3201 update_index = read_index;
John Zulauf9cb530d2019-09-30 14:14:10 -06003202 break;
3203 }
3204 }
John Zulauf4285ee92020-09-23 10:20:52 -06003205 assert(update_index < last_read_count);
John Zulauf9cb530d2019-09-30 14:14:10 -06003206 } else {
John Zulauf9cb530d2019-09-30 14:14:10 -06003207 assert(last_read_count < last_reads.size());
John Zulauf4285ee92020-09-23 10:20:52 -06003208 update_index = last_read_count++;
John Zulauf9cb530d2019-09-30 14:14:10 -06003209 last_read_stages |= usage_stage;
3210 }
John Zulauf4285ee92020-09-23 10:20:52 -06003211 last_reads[update_index].Set(usage_stage, usage_bit, 0, tag);
3212
3213 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
3214 if (usage_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) {
John Zulauff51fbb62020-10-02 14:43:24 -06003215 // TODO Revisit re: multiple reads for a given stage
3216 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003217 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003218 } else {
3219 // Assume write
3220 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003221 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003222 }
3223}
John Zulauf5f13a792020-03-10 07:31:21 -06003224
John Zulauf89311b42020-09-29 16:28:47 -06003225// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3226// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3227// We can overwrite them as *this* write is now after them.
3228//
3229// 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 -07003230void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag &tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003231 last_read_count = 0;
3232 last_read_stages = 0;
3233 read_execution_barriers = 0;
John Zulauff51fbb62020-10-02 14:43:24 -06003234 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
John Zulauf89311b42020-09-29 16:28:47 -06003235
3236 write_barriers = 0;
3237 write_dependency_chain = 0;
3238 write_tag = tag;
3239 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003240}
3241
John Zulauf89311b42020-09-29 16:28:47 -06003242// Apply the memory barrier without updating the existing barriers. The execution barrier
3243// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3244// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3245// replace the current write barriers or add to them, so accumulate to pending as well.
3246void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) {
3247 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3248 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003249 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
3250 // transistion, under the theory of "most recent access". If the read/write *isn't* safe
3251 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3252 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulauf4a6105a2020-11-17 15:11:05 -07003253 if (layout_transition || WriteInSourceScopeOrChain(barrier.src_exec_scope, barrier.src_access_scope)) {
John Zulauf89311b42020-09-29 16:28:47 -06003254 pending_write_barriers |= barrier.dst_access_scope;
3255 pending_write_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003256 }
John Zulauf89311b42020-09-29 16:28:47 -06003257 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3258 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003259
John Zulauf89311b42020-09-29 16:28:47 -06003260 if (!pending_layout_transition) {
3261 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3262 // don't need to be tracked as we're just going to zero them.
John Zulaufa0a98292020-09-18 09:30:10 -06003263 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
John Zulauf89311b42020-09-29 16:28:47 -06003264 ReadState &access = last_reads[read_index];
3265 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
3266 if (barrier.src_exec_scope & (access.stage | access.barriers)) {
3267 access.pending_dep_chain |= barrier.dst_exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003268 }
3269 }
John Zulaufa0a98292020-09-18 09:30:10 -06003270 }
John Zulaufa0a98292020-09-18 09:30:10 -06003271}
3272
John Zulauf4a6105a2020-11-17 15:11:05 -07003273// Apply the tag scoped memory barrier without updating the existing barriers. The execution barrier
3274// changes the "chaining" state, but to keep barriers independent. See discussion above.
3275void ResourceAccessState::ApplyBarrier(const ResourceUsageTag &scope_tag, const SyncBarrier &barrier, bool layout_transition) {
3276 // The scope logic for events is, if we're here, the resource usage was flagged as "in the first execution scope" at
3277 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3278 // in order to know if it's in the excecution scope
3279 // Notice that the layout transition sets the pending barriers *regardless*, as any lack of src_access_scope to
3280 // guard against the layout transition should be reported in the detect barrier hazard phase, and we only report
3281 // errors w.r.t. "most recent" accesses.
3282 if (layout_transition || ((write_tag.IsBefore(scope_tag)) && (barrier.src_access_scope & last_write).any())) {
3283 pending_write_barriers |= barrier.dst_access_scope;
3284 pending_write_dep_chain |= barrier.dst_exec_scope;
3285 }
3286 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3287 pending_layout_transition |= layout_transition;
3288
3289 if (!pending_layout_transition) {
3290 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains
3291 // don't need to be tracked as we're just going to zero them.
3292 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
3293 ReadState &access = last_reads[read_index];
3294 // If this read is the same one we included in the set event and in scope, then apply the execution barrier...
3295 // NOTE: That's not really correct... this read stage might *not* have been included in the setevent, and the barriers
3296 // representing the chain might have changed since then (that would be an odd usage), so as a first approximation
3297 // we'll assume the barriers *haven't* been changed since (if the tag hasn't), and while this could be a false
3298 // positive in the case of Set; SomeBarrier; Wait; we'll live with it until we can add more state to the first scope
3299 // capture (the specific write and read stages that *were* in scope at the moment of SetEvents.
3300 // TODO: eliminate the false positive by including write/read-stages "in scope" information in SetEvents first_scope
3301 if (access.tag.IsBefore(scope_tag) && (barrier.src_exec_scope & (access.stage | access.barriers))) {
3302 access.pending_dep_chain |= barrier.dst_exec_scope;
3303 }
3304 }
3305 }
3306}
John Zulauf89311b42020-09-29 16:28:47 -06003307void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag &tag) {
3308 if (pending_layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003309 // SetWrite clobbers the read count, and thus we don't have to clear the read_state out.
3310 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
3311 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003312 }
John Zulauf89311b42020-09-29 16:28:47 -06003313
3314 // Apply the accumulate execution barriers (and thus update chaining information)
3315 // for layout transition, read count is zeroed by SetWrite, so this will be skipped.
3316 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
3317 ReadState &access = last_reads[read_index];
3318 access.barriers |= access.pending_dep_chain;
3319 read_execution_barriers |= access.barriers;
3320 access.pending_dep_chain = 0;
3321 }
3322
3323 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3324 write_dependency_chain |= pending_write_dep_chain;
3325 write_barriers |= pending_write_barriers;
3326 pending_write_dep_chain = 0;
3327 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003328}
3329
John Zulauf59e25072020-07-17 10:55:21 -06003330// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003331VkPipelineStageFlags ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
John Zulauf59e25072020-07-17 10:55:21 -06003332 VkPipelineStageFlags barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003333
3334 for (uint32_t read_index = 0; read_index < last_read_count; read_index++) {
3335 const auto &read_access = last_reads[read_index];
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003336 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003337 barriers = read_access.barriers;
3338 break;
John Zulauf59e25072020-07-17 10:55:21 -06003339 }
3340 }
John Zulauf4285ee92020-09-23 10:20:52 -06003341
John Zulauf59e25072020-07-17 10:55:21 -06003342 return barriers;
3343}
3344
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003345inline bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlagBits usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003346 assert(IsRead(usage));
3347 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3348 // * the previous reads are not hazards, and thus last_write must be visible and available to
3349 // any reads that happen after.
3350 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3351 // 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 -07003352 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003353}
3354
John Zulauf4285ee92020-09-23 10:20:52 -06003355VkPipelineStageFlags ResourceAccessState::GetOrderedStages(const SyncOrderingBarrier &ordering) const {
3356 // Whether the stage are in the ordering scope only matters if the current write is ordered
3357 VkPipelineStageFlags ordered_stages = last_read_stages & ordering.exec_scope;
3358 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003359 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003360 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003361 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
3362 ordered_stages |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
3363 }
3364
3365 return ordered_stages;
3366}
3367
3368inline ResourceAccessState::ReadState *ResourceAccessState::GetReadStateForStage(VkPipelineStageFlagBits stage,
3369 uint32_t search_limit) {
3370 ReadState *read_state = nullptr;
3371 search_limit = std::min(search_limit, last_read_count);
3372 for (uint32_t i = 0; i < search_limit; i++) {
3373 if (last_reads[i].stage == stage) {
3374 read_state = &last_reads[i];
3375 break;
3376 }
3377 }
3378 return read_state;
3379}
3380
John Zulaufd1f85d42020-04-15 12:23:15 -06003381void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003382 auto *access_context = GetAccessContextNoInsert(command_buffer);
3383 if (access_context) {
3384 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003385 }
3386}
3387
John Zulaufd1f85d42020-04-15 12:23:15 -06003388void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3389 auto access_found = cb_access_state.find(command_buffer);
3390 if (access_found != cb_access_state.end()) {
3391 access_found->second->Reset();
3392 cb_access_state.erase(access_found);
3393 }
3394}
3395
John Zulauf89311b42020-09-29 16:28:47 -06003396void SyncValidator::ApplyGlobalBarriers(AccessContext *context, VkPipelineStageFlags src_exec_scope,
3397 VkPipelineStageFlags dst_exec_scope, SyncStageAccessFlags src_access_scope,
3398 SyncStageAccessFlags dst_access_scope, uint32_t memory_barrier_count,
3399 const VkMemoryBarrier *pMemoryBarriers, const ResourceUsageTag &tag) {
John Zulauf1e331ec2020-12-04 18:29:38 -07003400 std::vector<PipelineBarrierOp> barrier_ops;
3401 barrier_ops.reserve(std::min<uint32_t>(1, memory_barrier_count));
John Zulauf89311b42020-09-29 16:28:47 -06003402 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
3403 const auto &barrier = pMemoryBarriers[barrier_index];
3404 SyncBarrier sync_barrier(src_exec_scope, SyncStageAccess::AccessScope(src_access_scope, barrier.srcAccessMask),
3405 dst_exec_scope, SyncStageAccess::AccessScope(dst_access_scope, barrier.dstAccessMask));
John Zulauf1e331ec2020-12-04 18:29:38 -07003406 barrier_ops.emplace_back(sync_barrier, false);
John Zulauf89311b42020-09-29 16:28:47 -06003407 }
3408 if (0 == memory_barrier_count) {
3409 // If there are no global memory barriers, force an exec barrier
John Zulauf1e331ec2020-12-04 18:29:38 -07003410 barrier_ops.emplace_back(SyncBarrier(src_exec_scope, 0, dst_exec_scope, 0), false);
John Zulauf89311b42020-09-29 16:28:47 -06003411 }
John Zulauf1e331ec2020-12-04 18:29:38 -07003412 ApplyBarrierOpsFunctor<PipelineBarrierOp> barriers_functor(true /* resolve */, barrier_ops, tag);
John Zulauf540266b2020-04-06 18:54:53 -06003413 context->ApplyGlobalBarriers(barriers_functor);
John Zulauf9cb530d2019-09-30 14:14:10 -06003414}
3415
John Zulauf540266b2020-04-06 18:54:53 -06003416void SyncValidator::ApplyBufferBarriers(AccessContext *context, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003417 const SyncStageAccessFlags &src_stage_accesses, VkPipelineStageFlags dst_exec_scope,
3418 const SyncStageAccessFlags &dst_stage_accesses, uint32_t barrier_count,
John Zulauf9cb530d2019-09-30 14:14:10 -06003419 const VkBufferMemoryBarrier *barriers) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003420 for (uint32_t index = 0; index < barrier_count; index++) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003421 auto barrier = barriers[index]; // barrier is a copy
John Zulauf9cb530d2019-09-30 14:14:10 -06003422 const auto *buffer = Get<BUFFER_STATE>(barrier.buffer);
3423 if (!buffer) continue;
John Zulauf3e86bf02020-09-12 10:47:57 -06003424 barrier.size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
3425 const ResourceAccessRange range = MakeRange(barrier);
John Zulauf540266b2020-04-06 18:54:53 -06003426 const auto src_access_scope = AccessScope(src_stage_accesses, barrier.srcAccessMask);
3427 const auto dst_access_scope = AccessScope(dst_stage_accesses, barrier.dstAccessMask);
John Zulauf89311b42020-09-29 16:28:47 -06003428 const SyncBarrier sync_barrier(src_exec_scope, src_access_scope, dst_exec_scope, dst_access_scope);
John Zulauf4a6105a2020-11-17 15:11:05 -07003429 const ApplyBarrierFunctor<PipelineBarrierOp> update_action({sync_barrier, false /* layout_transition */});
John Zulauf89311b42020-09-29 16:28:47 -06003430 context->UpdateResourceAccess(*buffer, range, update_action);
John Zulauf9cb530d2019-09-30 14:14:10 -06003431 }
3432}
3433
John Zulauf540266b2020-04-06 18:54:53 -06003434void SyncValidator::ApplyImageBarriers(AccessContext *context, VkPipelineStageFlags src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003435 const SyncStageAccessFlags &src_stage_accesses, VkPipelineStageFlags dst_exec_scope,
3436 const SyncStageAccessFlags &dst_stage_accesses, uint32_t barrier_count,
John Zulauf355e49b2020-04-24 15:11:15 -06003437 const VkImageMemoryBarrier *barriers, const ResourceUsageTag &tag) {
John Zulauf5c5e88d2019-12-26 11:22:02 -07003438 for (uint32_t index = 0; index < barrier_count; index++) {
3439 const auto &barrier = barriers[index];
3440 const auto *image = Get<IMAGE_STATE>(barrier.image);
3441 if (!image) continue;
John Zulauf540266b2020-04-06 18:54:53 -06003442 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
John Zulauf355e49b2020-04-24 15:11:15 -06003443 bool layout_transition = barrier.oldLayout != barrier.newLayout;
3444 const auto src_access_scope = AccessScope(src_stage_accesses, barrier.srcAccessMask);
3445 const auto dst_access_scope = AccessScope(dst_stage_accesses, barrier.dstAccessMask);
John Zulauf89311b42020-09-29 16:28:47 -06003446 const SyncBarrier sync_barrier(src_exec_scope, src_access_scope, dst_exec_scope, dst_access_scope);
John Zulauf4a6105a2020-11-17 15:11:05 -07003447 const ApplyBarrierFunctor<PipelineBarrierOp> barrier_action({sync_barrier, layout_transition});
John Zulauf89311b42020-09-29 16:28:47 -06003448 context->UpdateResourceAccess(*image, subresource_range, barrier_action);
John Zulauf9cb530d2019-09-30 14:14:10 -06003449 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003450}
3451
3452bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3453 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3454 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003455 const auto *cb_context = GetAccessContext(commandBuffer);
3456 assert(cb_context);
3457 if (!cb_context) return skip;
3458 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003459
John Zulauf3d84f1b2020-03-09 13:33:25 -06003460 // If we have no previous accesses, we have no hazards
John Zulauf3d84f1b2020-03-09 13:33:25 -06003461 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003462 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003463
3464 for (uint32_t region = 0; region < regionCount; region++) {
3465 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003466 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003467 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003468 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003469 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003470 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003471 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003472 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06003473 string_UsageTag(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003474 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003475 }
John Zulauf16adfc92020-04-08 10:28:33 -06003476 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003477 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf355e49b2020-04-24 15:11:15 -06003478 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003479 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003480 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003481 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003482 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06003483 string_UsageTag(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003484 }
3485 }
3486 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003487 }
3488 return skip;
3489}
3490
3491void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3492 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003493 auto *cb_context = GetAccessContext(commandBuffer);
3494 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003495 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003496 auto *context = cb_context->GetCurrentAccessContext();
3497
John Zulauf9cb530d2019-09-30 14:14:10 -06003498 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003499 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003500
3501 for (uint32_t region = 0; region < regionCount; region++) {
3502 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003503 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003504 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003505 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003506 }
John Zulauf16adfc92020-04-08 10:28:33 -06003507 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003508 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
John Zulauf16adfc92020-04-08 10:28:33 -06003509 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003510 }
3511 }
3512}
3513
John Zulauf4a6105a2020-11-17 15:11:05 -07003514void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3515 // Clear out events from the command buffer contexts
3516 for (auto &cb_context : cb_access_state) {
3517 cb_context.second->RecordDestroyEvent(event);
3518 }
3519}
3520
Jeff Leger178b1e52020-10-05 12:22:23 -04003521bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3522 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3523 bool skip = false;
3524 const auto *cb_context = GetAccessContext(commandBuffer);
3525 assert(cb_context);
3526 if (!cb_context) return skip;
3527 const auto *context = cb_context->GetCurrentAccessContext();
3528
3529 // If we have no previous accesses, we have no hazards
3530 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3531 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3532
3533 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3534 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3535 if (src_buffer) {
3536 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
3537 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
3538 if (hazard.hazard) {
3539 // TODO -- add tag information to log msg when useful.
3540 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
3541 "vkCmdCopyBuffer2KHR(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
3542 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
3543 region, string_UsageTag(hazard).c_str());
3544 }
3545 }
3546 if (dst_buffer && !skip) {
3547 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
3548 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
3549 if (hazard.hazard) {
3550 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
3551 "vkCmdCopyBuffer2KHR(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
3552 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
3553 region, string_UsageTag(hazard).c_str());
3554 }
3555 }
3556 if (skip) break;
3557 }
3558 return skip;
3559}
3560
3561void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3562 auto *cb_context = GetAccessContext(commandBuffer);
3563 assert(cb_context);
3564 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER2KHR);
3565 auto *context = cb_context->GetCurrentAccessContext();
3566
3567 const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3568 const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
3569
3570 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3571 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3572 if (src_buffer) {
3573 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
3574 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range, tag);
3575 }
3576 if (dst_buffer) {
3577 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
3578 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range, tag);
3579 }
3580 }
3581}
3582
John Zulauf5c5e88d2019-12-26 11:22:02 -07003583bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3584 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3585 const VkImageCopy *pRegions) const {
3586 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003587 const auto *cb_access_context = GetAccessContext(commandBuffer);
3588 assert(cb_access_context);
3589 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003590
John Zulauf3d84f1b2020-03-09 13:33:25 -06003591 const auto *context = cb_access_context->GetCurrentAccessContext();
3592 assert(context);
3593 if (!context) return skip;
3594
3595 const auto *src_image = Get<IMAGE_STATE>(srcImage);
3596 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003597 for (uint32_t region = 0; region < regionCount; region++) {
3598 const auto &copy_region = pRegions[region];
3599 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003600 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003601 copy_region.srcOffset, copy_region.extent);
3602 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003603 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003604 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003605 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06003606 string_UsageTag(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003607 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003608 }
3609
3610 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003611 VkExtent3D dst_copy_extent =
3612 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf540266b2020-04-06 18:54:53 -06003613 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
locke-lunarg1df1f882020-03-02 16:42:08 -07003614 copy_region.dstOffset, dst_copy_extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003615 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003616 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003617 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003618 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06003619 string_UsageTag(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003620 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07003621 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003622 }
3623 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003624
John Zulauf5c5e88d2019-12-26 11:22:02 -07003625 return skip;
3626}
3627
3628void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3629 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3630 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003631 auto *cb_access_context = GetAccessContext(commandBuffer);
3632 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003633 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003634 auto *context = cb_access_context->GetCurrentAccessContext();
3635 assert(context);
3636
John Zulauf5c5e88d2019-12-26 11:22:02 -07003637 auto *src_image = Get<IMAGE_STATE>(srcImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003638 auto *dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003639
3640 for (uint32_t region = 0; region < regionCount; region++) {
3641 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06003642 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06003643 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource, copy_region.srcOffset,
3644 copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003645 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003646 if (dst_image) {
locke-lunarg1df1f882020-03-02 16:42:08 -07003647 VkExtent3D dst_copy_extent =
3648 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
John Zulauf540266b2020-04-06 18:54:53 -06003649 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource, copy_region.dstOffset,
3650 dst_copy_extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003651 }
3652 }
3653}
3654
Jeff Leger178b1e52020-10-05 12:22:23 -04003655bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
3656 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
3657 bool skip = false;
3658 const auto *cb_access_context = GetAccessContext(commandBuffer);
3659 assert(cb_access_context);
3660 if (!cb_access_context) return skip;
3661
3662 const auto *context = cb_access_context->GetCurrentAccessContext();
3663 assert(context);
3664 if (!context) return skip;
3665
3666 const auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3667 const auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3668 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3669 const auto &copy_region = pCopyImageInfo->pRegions[region];
3670 if (src_image) {
3671 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource,
3672 copy_region.srcOffset, copy_region.extent);
3673 if (hazard.hazard) {
3674 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
3675 "vkCmdCopyImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
3676 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
3677 region, string_UsageTag(hazard).c_str());
3678 }
3679 }
3680
3681 if (dst_image) {
3682 VkExtent3D dst_copy_extent =
3683 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
3684 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource,
3685 copy_region.dstOffset, dst_copy_extent);
3686 if (hazard.hazard) {
3687 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
3688 "vkCmdCopyImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
3689 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
3690 region, string_UsageTag(hazard).c_str());
3691 }
3692 if (skip) break;
3693 }
3694 }
3695
3696 return skip;
3697}
3698
3699void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
3700 auto *cb_access_context = GetAccessContext(commandBuffer);
3701 assert(cb_access_context);
3702 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE2KHR);
3703 auto *context = cb_access_context->GetCurrentAccessContext();
3704 assert(context);
3705
3706 auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
3707 auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
3708
3709 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
3710 const auto &copy_region = pCopyImageInfo->pRegions[region];
3711 if (src_image) {
3712 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource, copy_region.srcOffset,
3713 copy_region.extent, tag);
3714 }
3715 if (dst_image) {
3716 VkExtent3D dst_copy_extent =
3717 GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent);
3718 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource, copy_region.dstOffset,
3719 dst_copy_extent, tag);
3720 }
3721 }
3722}
3723
John Zulauf9cb530d2019-09-30 14:14:10 -06003724bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3725 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3726 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3727 uint32_t bufferMemoryBarrierCount,
3728 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3729 uint32_t imageMemoryBarrierCount,
3730 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
3731 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003732 const auto *cb_access_context = GetAccessContext(commandBuffer);
3733 assert(cb_access_context);
3734 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07003735
John Zulauf3d84f1b2020-03-09 13:33:25 -06003736 const auto *context = cb_access_context->GetCurrentAccessContext();
3737 assert(context);
3738 if (!context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07003739
John Zulauf3d84f1b2020-03-09 13:33:25 -06003740 const auto src_stage_mask = ExpandPipelineStages(cb_access_context->GetQueueFlags(), srcStageMask);
John Zulauf36bcf6a2020-02-03 15:12:52 -07003741 const auto src_exec_scope = WithEarlierPipelineStages(src_stage_mask);
3742 auto src_stage_accesses = AccessScopeByStage(src_stage_mask);
John Zulauf0cb5be22020-01-23 12:18:22 -07003743 // Validate Image Layout transitions
3744 for (uint32_t index = 0; index < imageMemoryBarrierCount; index++) {
3745 const auto &barrier = pImageMemoryBarriers[index];
3746 if (barrier.newLayout == barrier.oldLayout) continue; // Only interested in layout transitions at this point.
3747 const auto *image_state = Get<IMAGE_STATE>(barrier.image);
3748 if (!image_state) continue;
John Zulauf16adfc92020-04-08 10:28:33 -06003749 const auto hazard = context->DetectImageBarrierHazard(*image_state, src_exec_scope, src_stage_accesses, barrier);
John Zulauf0cb5be22020-01-23 12:18:22 -07003750 if (hazard.hazard) {
John Zulauf7635de32020-05-29 17:14:15 -06003751 // PHASE1 TODO -- add tag information to log msg when useful.
locke-lunarga0003652020-03-10 11:38:51 -06003752 skip |= LogError(barrier.image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003753 "vkCmdPipelineBarrier: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003754 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(barrier.image).c_str(),
John Zulauf37ceaed2020-07-03 16:18:15 -06003755 string_UsageTag(hazard).c_str());
John Zulauf0cb5be22020-01-23 12:18:22 -07003756 }
3757 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003758
3759 return skip;
3760}
3761
3762void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3763 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3764 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
3765 uint32_t bufferMemoryBarrierCount,
3766 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
3767 uint32_t imageMemoryBarrierCount,
3768 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003769 auto *cb_access_context = GetAccessContext(commandBuffer);
3770 assert(cb_access_context);
3771 if (!cb_access_context) return;
John Zulauf2b151bf2020-04-24 15:37:44 -06003772 const auto tag = cb_access_context->NextCommandTag(CMD_PIPELINEBARRIER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003773 auto access_context = cb_access_context->GetCurrentAccessContext();
3774 assert(access_context);
3775 if (!access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06003776
John Zulauf3d84f1b2020-03-09 13:33:25 -06003777 const auto src_stage_mask = ExpandPipelineStages(cb_access_context->GetQueueFlags(), srcStageMask);
John Zulauf36bcf6a2020-02-03 15:12:52 -07003778 auto src_stage_accesses = AccessScopeByStage(src_stage_mask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003779 const auto dst_stage_mask = ExpandPipelineStages(cb_access_context->GetQueueFlags(), dstStageMask);
John Zulauf36bcf6a2020-02-03 15:12:52 -07003780 auto dst_stage_accesses = AccessScopeByStage(dst_stage_mask);
3781 const auto src_exec_scope = WithEarlierPipelineStages(src_stage_mask);
3782 const auto dst_exec_scope = WithLaterPipelineStages(dst_stage_mask);
John Zulauf89311b42020-09-29 16:28:47 -06003783
3784 // These two apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
3785 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
3786 // of the barriers is maintained.
John Zulauf3d84f1b2020-03-09 13:33:25 -06003787 ApplyBufferBarriers(access_context, src_exec_scope, src_stage_accesses, dst_exec_scope, dst_stage_accesses,
3788 bufferMemoryBarrierCount, pBufferMemoryBarriers);
John Zulauf540266b2020-04-06 18:54:53 -06003789 ApplyImageBarriers(access_context, src_exec_scope, src_stage_accesses, dst_exec_scope, dst_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06003790 imageMemoryBarrierCount, pImageMemoryBarriers, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003791
John Zulauf89311b42020-09-29 16:28:47 -06003792 // Apply the global barriers last as is it walks all memory, it can also clean up the "pending" state without requiring an
3793 // additional pass, updating the dependency chains *last* as it goes along.
3794 // This is needed to guarantee order independence of the three lists.
John Zulauf3d84f1b2020-03-09 13:33:25 -06003795 ApplyGlobalBarriers(access_context, src_exec_scope, dst_exec_scope, src_stage_accesses, dst_stage_accesses, memoryBarrierCount,
John Zulauf89311b42020-09-29 16:28:47 -06003796 pMemoryBarriers, tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003797
3798 // Need to pass the unexpanded stage masks as the ALL_COMMANDS bit is removed during expansion.
3799 cb_access_context->ApplyGlobalBarriersToEvents(srcStageMask, src_exec_scope, dstStageMask, dst_exec_scope);
John Zulauf9cb530d2019-09-30 14:14:10 -06003800}
3801
3802void SyncValidator::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo,
3803 const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) {
3804 // The state tracker sets up the device state
3805 StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result);
3806
John Zulauf5f13a792020-03-10 07:31:21 -06003807 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
3808 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06003809 // TODO: Find a good way to do this hooklessly.
3810 ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map);
3811 ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeSyncValidation);
3812 SyncValidator *sync_device_state = static_cast<SyncValidator *>(validation_data);
3813
John Zulaufd1f85d42020-04-15 12:23:15 -06003814 sync_device_state->SetCommandBufferResetCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3815 sync_device_state->ResetCommandBufferCallback(command_buffer);
3816 });
3817 sync_device_state->SetCommandBufferFreeCallback([sync_device_state](VkCommandBuffer command_buffer) -> void {
3818 sync_device_state->FreeCommandBufferCallback(command_buffer);
3819 });
John Zulauf9cb530d2019-09-30 14:14:10 -06003820}
John Zulauf3d84f1b2020-03-09 13:33:25 -06003821
John Zulauf355e49b2020-04-24 15:11:15 -06003822bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003823 const VkSubpassBeginInfo *pSubpassBeginInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003824 bool skip = false;
3825 const auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
3826 auto cb_context = GetAccessContext(commandBuffer);
3827
3828 if (rp_state && cb_context) {
3829 skip |= cb_context->ValidateBeginRenderPass(*rp_state, pRenderPassBegin, pSubpassBeginInfo, func_name);
3830 }
3831
3832 return skip;
3833}
3834
3835bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3836 VkSubpassContents contents) const {
3837 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
3838 auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>();
3839 subpass_begin_info.contents = contents;
3840 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, "vkCmdBeginRenderPass");
3841 return skip;
3842}
3843
3844bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003845 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003846 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3847 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2");
3848 return skip;
3849}
3850
3851bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3852 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003853 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003854 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
3855 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2KHR");
3856 return skip;
3857}
3858
John Zulauf3d84f1b2020-03-09 13:33:25 -06003859void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
3860 VkResult result) {
3861 // The state tracker sets up the command buffer state
3862 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
3863
3864 // Create/initialize the structure that trackers accesses at the command buffer scope.
3865 auto cb_access_context = GetAccessContext(commandBuffer);
3866 assert(cb_access_context);
3867 cb_access_context->Reset();
3868}
3869
3870void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
John Zulauf355e49b2020-04-24 15:11:15 -06003871 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003872 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06003873 if (cb_context) {
3874 cb_context->RecordBeginRenderPass(cb_context->NextCommandTag(command));
John Zulauf3d84f1b2020-03-09 13:33:25 -06003875 }
3876}
3877
3878void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3879 VkSubpassContents contents) {
3880 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
3881 auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>();
3882 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003883 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003884}
3885
3886void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
3887 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3888 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003889 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003890}
3891
3892void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
3893 const VkRenderPassBeginInfo *pRenderPassBegin,
3894 const VkSubpassBeginInfo *pSubpassBeginInfo) {
3895 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003896 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
3897}
3898
Mike Schuchardt2df08912020-12-15 16:28:09 -08003899bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3900 const VkSubpassEndInfo *pSubpassEndInfo, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003901 bool skip = false;
3902
3903 auto cb_context = GetAccessContext(commandBuffer);
3904 assert(cb_context);
3905 auto cb_state = cb_context->GetCommandBufferState();
3906 if (!cb_state) return skip;
3907
3908 auto rp_state = cb_state->activeRenderPass;
3909 if (!rp_state) return skip;
3910
3911 skip |= cb_context->ValidateNextSubpass(func_name);
3912
3913 return skip;
3914}
3915
3916bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
3917 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
3918 auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>();
3919 subpass_begin_info.contents = contents;
3920 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, "vkCmdNextSubpass");
3921 return skip;
3922}
3923
Mike Schuchardt2df08912020-12-15 16:28:09 -08003924bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3925 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003926 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3927 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2KHR");
3928 return skip;
3929}
3930
3931bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3932 const VkSubpassEndInfo *pSubpassEndInfo) const {
3933 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
3934 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2");
3935 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003936}
3937
3938void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003939 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003940 auto cb_context = GetAccessContext(commandBuffer);
3941 assert(cb_context);
3942 auto cb_state = cb_context->GetCommandBufferState();
3943 if (!cb_state) return;
3944
3945 auto rp_state = cb_state->activeRenderPass;
3946 if (!rp_state) return;
3947
John Zulauf355e49b2020-04-24 15:11:15 -06003948 cb_context->RecordNextSubpass(*rp_state, cb_context->NextCommandTag(command));
John Zulauf3d84f1b2020-03-09 13:33:25 -06003949}
3950
3951void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
3952 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
3953 auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>();
3954 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06003955 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003956}
3957
3958void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3959 const VkSubpassEndInfo *pSubpassEndInfo) {
3960 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003961 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003962}
3963
3964void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
3965 const VkSubpassEndInfo *pSubpassEndInfo) {
3966 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06003967 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003968}
3969
Mike Schuchardt2df08912020-12-15 16:28:09 -08003970bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
John Zulauf355e49b2020-04-24 15:11:15 -06003971 const char *func_name) const {
3972 bool skip = false;
3973
3974 auto cb_context = GetAccessContext(commandBuffer);
3975 assert(cb_context);
3976 auto cb_state = cb_context->GetCommandBufferState();
3977 if (!cb_state) return skip;
3978
3979 auto rp_state = cb_state->activeRenderPass;
3980 if (!rp_state) return skip;
3981
3982 skip |= cb_context->ValidateEndRenderpass(func_name);
3983 return skip;
3984}
3985
3986bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3987 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
3988 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, "vkEndRenderPass");
3989 return skip;
3990}
3991
Mike Schuchardt2df08912020-12-15 16:28:09 -08003992bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06003993 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3994 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2");
3995 return skip;
3996}
3997
3998bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08003999 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004000 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
4001 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2KHR");
4002 return skip;
4003}
4004
4005void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4006 CMD_TYPE command) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004007 // Resolve the all subpass contexts to the command buffer contexts
4008 auto cb_context = GetAccessContext(commandBuffer);
4009 assert(cb_context);
4010 auto cb_state = cb_context->GetCommandBufferState();
4011 if (!cb_state) return;
4012
locke-lunargaecf2152020-05-12 17:15:41 -06004013 const auto *rp_state = cb_state->activeRenderPass.get();
John Zulaufe5da6e52020-03-18 15:32:18 -06004014 if (!rp_state) return;
4015
John Zulauf355e49b2020-04-24 15:11:15 -06004016 cb_context->RecordEndRenderPass(*rp_state, cb_context->NextCommandTag(command));
John Zulaufe5da6e52020-03-18 15:32:18 -06004017}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004018
John Zulauf33fc1d52020-07-17 11:01:10 -06004019// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4020// updates to a resource which do not conflict at the byte level.
4021// TODO: Revisit this rule to see if it needs to be tighter or looser
4022// TODO: Add programatic control over suppression heuristics
4023bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4024 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4025}
4026
John Zulauf3d84f1b2020-03-09 13:33:25 -06004027void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004028 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004029 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004030}
4031
4032void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004033 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004034 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004035}
4036
4037void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004038 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004039 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004040}
locke-lunarga19c71d2020-03-02 18:17:04 -07004041
Jeff Leger178b1e52020-10-05 12:22:23 -04004042template <typename BufferImageCopyRegionType>
4043bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4044 VkImageLayout dstImageLayout, uint32_t regionCount,
4045 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004046 bool skip = false;
4047 const auto *cb_access_context = GetAccessContext(commandBuffer);
4048 assert(cb_access_context);
4049 if (!cb_access_context) return skip;
4050
Jeff Leger178b1e52020-10-05 12:22:23 -04004051 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
4052 const char *func_name = is_2khr ? "vkCmdCopyBufferToImage2KHR()" : "vkCmdCopyBufferToImage()";
4053
locke-lunarga19c71d2020-03-02 18:17:04 -07004054 const auto *context = cb_access_context->GetCurrentAccessContext();
4055 assert(context);
4056 if (!context) return skip;
4057
4058 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
locke-lunarga19c71d2020-03-02 18:17:04 -07004059 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4060
4061 for (uint32_t region = 0; region < regionCount; region++) {
4062 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004063 if (src_buffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004064 ResourceAccessRange src_range =
4065 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
John Zulauf16adfc92020-04-08 10:28:33 -06004066 auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range);
locke-lunarga19c71d2020-03-02 18:17:04 -07004067 if (hazard.hazard) {
John Zulauf7635de32020-05-29 17:14:15 -06004068 // PHASE1 TODO -- add tag information to log msg when useful.
locke-lunarga0003652020-03-10 11:38:51 -06004069 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004070 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004071 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06004072 string_UsageTag(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004073 }
4074 }
4075 if (dst_image) {
John Zulauf540266b2020-04-06 18:54:53 -06004076 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07004077 copy_region.imageOffset, copy_region.imageExtent);
4078 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004079 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004080 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004081 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06004082 string_UsageTag(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004083 }
4084 if (skip) break;
4085 }
4086 if (skip) break;
4087 }
4088 return skip;
4089}
4090
Jeff Leger178b1e52020-10-05 12:22:23 -04004091bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4092 VkImageLayout dstImageLayout, uint32_t regionCount,
4093 const VkBufferImageCopy *pRegions) const {
4094 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
4095 COPY_COMMAND_VERSION_1);
4096}
4097
4098bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4099 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4100 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4101 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4102 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
4103}
4104
4105template <typename BufferImageCopyRegionType>
4106void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4107 VkImageLayout dstImageLayout, uint32_t regionCount,
4108 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004109 auto *cb_access_context = GetAccessContext(commandBuffer);
4110 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004111
4112 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
4113 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYBUFFERTOIMAGE2KHR : CMD_COPYBUFFERTOIMAGE;
4114
4115 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004116 auto *context = cb_access_context->GetCurrentAccessContext();
4117 assert(context);
4118
4119 const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer);
John Zulauf16adfc92020-04-08 10:28:33 -06004120 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004121
4122 for (uint32_t region = 0; region < regionCount; region++) {
4123 const auto &copy_region = pRegions[region];
4124 if (src_buffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004125 ResourceAccessRange src_range =
4126 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
John Zulauf16adfc92020-04-08 10:28:33 -06004127 context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004128 }
4129 if (dst_image) {
John Zulauf540266b2020-04-06 18:54:53 -06004130 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource,
John Zulauf5f13a792020-03-10 07:31:21 -06004131 copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004132 }
4133 }
4134}
4135
Jeff Leger178b1e52020-10-05 12:22:23 -04004136void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4137 VkImageLayout dstImageLayout, uint32_t regionCount,
4138 const VkBufferImageCopy *pRegions) {
4139 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
4140 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1);
4141}
4142
4143void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4144 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4145 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4146 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4147 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4148 pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2);
4149}
4150
4151template <typename BufferImageCopyRegionType>
4152bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4153 VkBuffer dstBuffer, uint32_t regionCount,
4154 const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004155 bool skip = false;
4156 const auto *cb_access_context = GetAccessContext(commandBuffer);
4157 assert(cb_access_context);
4158 if (!cb_access_context) return skip;
4159
Jeff Leger178b1e52020-10-05 12:22:23 -04004160 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
4161 const char *func_name = is_2khr ? "vkCmdCopyImageToBuffer2KHR()" : "vkCmdCopyImageToBuffer()";
4162
locke-lunarga19c71d2020-03-02 18:17:04 -07004163 const auto *context = cb_access_context->GetCurrentAccessContext();
4164 assert(context);
4165 if (!context) return skip;
4166
4167 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4168 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4169 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE;
4170 for (uint32_t region = 0; region < regionCount; region++) {
4171 const auto &copy_region = pRegions[region];
4172 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06004173 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07004174 copy_region.imageOffset, copy_region.imageExtent);
4175 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004176 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004177 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004178 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06004179 string_UsageTag(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004180 }
4181 }
4182 if (dst_mem) {
John Zulauf355e49b2020-04-24 15:11:15 -06004183 ResourceAccessRange dst_range =
4184 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
John Zulauf16adfc92020-04-08 10:28:33 -06004185 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range);
locke-lunarga19c71d2020-03-02 18:17:04 -07004186 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004187 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004188 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004189 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06004190 string_UsageTag(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004191 }
4192 }
4193 if (skip) break;
4194 }
4195 return skip;
4196}
4197
Jeff Leger178b1e52020-10-05 12:22:23 -04004198bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4199 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4200 const VkBufferImageCopy *pRegions) const {
4201 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
4202 COPY_COMMAND_VERSION_1);
4203}
4204
4205bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4206 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4207 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4208 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4209 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
4210}
4211
4212template <typename BufferImageCopyRegionType>
4213void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4214 VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions,
4215 CopyCommandVersion version) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004216 auto *cb_access_context = GetAccessContext(commandBuffer);
4217 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004218
4219 const bool is_2khr = (version == COPY_COMMAND_VERSION_2);
4220 const CMD_TYPE cmd_type = is_2khr ? CMD_COPYIMAGETOBUFFER2KHR : CMD_COPYIMAGETOBUFFER;
4221
4222 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004223 auto *context = cb_access_context->GetCurrentAccessContext();
4224 assert(context);
4225
4226 const auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004227 auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4228 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 -06004229 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004230
4231 for (uint32_t region = 0; region < regionCount; region++) {
4232 const auto &copy_region = pRegions[region];
4233 if (src_image) {
John Zulauf540266b2020-04-06 18:54:53 -06004234 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource,
John Zulauf5f13a792020-03-10 07:31:21 -06004235 copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004236 }
4237 if (dst_buffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004238 ResourceAccessRange dst_range =
4239 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
John Zulauf16adfc92020-04-08 10:28:33 -06004240 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004241 }
4242 }
4243}
4244
Jeff Leger178b1e52020-10-05 12:22:23 -04004245void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4246 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4247 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
4248 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1);
4249}
4250
4251void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4252 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4253 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4254 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4255 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4256 pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2);
4257}
4258
4259template <typename RegionType>
4260bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4261 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4262 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004263 bool skip = false;
4264 const auto *cb_access_context = GetAccessContext(commandBuffer);
4265 assert(cb_access_context);
4266 if (!cb_access_context) return skip;
4267
4268 const auto *context = cb_access_context->GetCurrentAccessContext();
4269 assert(context);
4270 if (!context) return skip;
4271
4272 const auto *src_image = Get<IMAGE_STATE>(srcImage);
4273 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
4274
4275 for (uint32_t region = 0; region < regionCount; region++) {
4276 const auto &blit_region = pRegions[region];
4277 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004278 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4279 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4280 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4281 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4282 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4283 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
4284 auto hazard =
4285 context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004286 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004287 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004288 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004289 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06004290 string_UsageTag(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004291 }
4292 }
4293
4294 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004295 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4296 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4297 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4298 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4299 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4300 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
4301 auto hazard =
4302 context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004303 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004304 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004305 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004306 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06004307 string_UsageTag(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004308 }
4309 if (skip) break;
4310 }
4311 }
4312
4313 return skip;
4314}
4315
Jeff Leger178b1e52020-10-05 12:22:23 -04004316bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4317 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4318 const VkImageBlit *pRegions, VkFilter filter) const {
4319 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4320 "vkCmdBlitImage");
4321}
4322
4323bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4324 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4325 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4326 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4327 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4328}
4329
4330template <typename RegionType>
4331void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4332 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4333 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004334 auto *cb_access_context = GetAccessContext(commandBuffer);
4335 assert(cb_access_context);
4336 auto *context = cb_access_context->GetCurrentAccessContext();
4337 assert(context);
4338
4339 auto *src_image = Get<IMAGE_STATE>(srcImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004340 auto *dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004341
4342 for (uint32_t region = 0; region < regionCount; region++) {
4343 const auto &blit_region = pRegions[region];
4344 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004345 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4346 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4347 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4348 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4349 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4350 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
4351 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004352 }
4353 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004354 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4355 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4356 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4357 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4358 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4359 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
4360 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004361 }
4362 }
4363}
locke-lunarg36ba2592020-04-03 09:42:04 -06004364
Jeff Leger178b1e52020-10-05 12:22:23 -04004365void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4366 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4367 const VkImageBlit *pRegions, VkFilter filter) {
4368 auto *cb_access_context = GetAccessContext(commandBuffer);
4369 assert(cb_access_context);
4370 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4371 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4372 pRegions, filter);
4373 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4374}
4375
4376void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4377 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4378 auto *cb_access_context = GetAccessContext(commandBuffer);
4379 assert(cb_access_context);
4380 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4381 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4382 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4383 pBlitImageInfo->filter, tag);
4384}
4385
locke-lunarg61870c22020-06-09 14:51:50 -06004386bool SyncValidator::ValidateIndirectBuffer(const AccessContext &context, VkCommandBuffer commandBuffer,
4387 const VkDeviceSize struct_size, const VkBuffer buffer, const VkDeviceSize offset,
4388 const uint32_t drawCount, const uint32_t stride, const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004389 bool skip = false;
4390 if (drawCount == 0) return skip;
4391
4392 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4393 VkDeviceSize size = struct_size;
4394 if (drawCount == 1 || stride == size) {
4395 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004396 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004397 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4398 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004399 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004400 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004401 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf37ceaed2020-07-03 16:18:15 -06004402 string_UsageTag(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004403 }
4404 } else {
4405 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004406 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004407 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4408 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004409 skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004410 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4411 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
4412 string_UsageTag(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004413 break;
4414 }
4415 }
4416 }
4417 return skip;
4418}
4419
locke-lunarg61870c22020-06-09 14:51:50 -06004420void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag &tag, const VkDeviceSize struct_size,
4421 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4422 uint32_t stride) {
locke-lunargff255f92020-05-13 18:53:52 -06004423 const auto *buf_state = Get<BUFFER_STATE>(buffer);
4424 VkDeviceSize size = struct_size;
4425 if (drawCount == 1 || stride == size) {
4426 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004427 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004428 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range, tag);
4429 } else {
4430 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004431 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004432 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range, tag);
4433 }
4434 }
4435}
4436
locke-lunarg61870c22020-06-09 14:51:50 -06004437bool SyncValidator::ValidateCountBuffer(const AccessContext &context, VkCommandBuffer commandBuffer, VkBuffer buffer,
4438 VkDeviceSize offset, const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004439 bool skip = false;
4440
4441 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004442 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004443 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4444 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004445 skip |= LogError(count_buf_state->buffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004446 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004447 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf37ceaed2020-07-03 16:18:15 -06004448 string_UsageTag(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004449 }
4450 return skip;
4451}
4452
locke-lunarg61870c22020-06-09 14:51:50 -06004453void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag &tag, VkBuffer buffer, VkDeviceSize offset) {
locke-lunargff255f92020-05-13 18:53:52 -06004454 const auto *count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004455 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004456 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range, tag);
4457}
4458
locke-lunarg36ba2592020-04-03 09:42:04 -06004459bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004460 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004461 const auto *cb_access_context = GetAccessContext(commandBuffer);
4462 assert(cb_access_context);
4463 if (!cb_access_context) return skip;
4464
locke-lunarg61870c22020-06-09 14:51:50 -06004465 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004466 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004467}
4468
4469void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004470 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004471 auto *cb_access_context = GetAccessContext(commandBuffer);
4472 assert(cb_access_context);
4473 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004474
locke-lunarg61870c22020-06-09 14:51:50 -06004475 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004476}
locke-lunarge1a67022020-04-29 00:15:36 -06004477
4478bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004479 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004480 const auto *cb_access_context = GetAccessContext(commandBuffer);
4481 assert(cb_access_context);
4482 if (!cb_access_context) return skip;
4483
4484 const auto *context = cb_access_context->GetCurrentAccessContext();
4485 assert(context);
4486 if (!context) return skip;
4487
locke-lunarg61870c22020-06-09 14:51:50 -06004488 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
4489 skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset, 1,
4490 sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004491 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004492}
4493
4494void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004495 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004496 auto *cb_access_context = GetAccessContext(commandBuffer);
4497 assert(cb_access_context);
4498 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4499 auto *context = cb_access_context->GetCurrentAccessContext();
4500 assert(context);
4501
locke-lunarg61870c22020-06-09 14:51:50 -06004502 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4503 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004504}
4505
4506bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4507 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004508 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004509 const auto *cb_access_context = GetAccessContext(commandBuffer);
4510 assert(cb_access_context);
4511 if (!cb_access_context) return skip;
4512
locke-lunarg61870c22020-06-09 14:51:50 -06004513 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4514 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4515 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004516 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004517}
4518
4519void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4520 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004521 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004522 auto *cb_access_context = GetAccessContext(commandBuffer);
4523 assert(cb_access_context);
4524 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004525
locke-lunarg61870c22020-06-09 14:51:50 -06004526 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4527 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4528 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004529}
4530
4531bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4532 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004533 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004534 const auto *cb_access_context = GetAccessContext(commandBuffer);
4535 assert(cb_access_context);
4536 if (!cb_access_context) return skip;
4537
locke-lunarg61870c22020-06-09 14:51:50 -06004538 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4539 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4540 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004541 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004542}
4543
4544void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4545 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004546 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004547 auto *cb_access_context = GetAccessContext(commandBuffer);
4548 assert(cb_access_context);
4549 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004550
locke-lunarg61870c22020-06-09 14:51:50 -06004551 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4552 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4553 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004554}
4555
4556bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4557 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004558 bool skip = false;
4559 if (drawCount == 0) return skip;
4560
locke-lunargff255f92020-05-13 18:53:52 -06004561 const auto *cb_access_context = GetAccessContext(commandBuffer);
4562 assert(cb_access_context);
4563 if (!cb_access_context) return skip;
4564
4565 const auto *context = cb_access_context->GetCurrentAccessContext();
4566 assert(context);
4567 if (!context) return skip;
4568
locke-lunarg61870c22020-06-09 14:51:50 -06004569 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4570 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
4571 skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride,
4572 "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004573
4574 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4575 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4576 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004577 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004578 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004579}
4580
4581void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4582 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004583 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004584 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06004585 auto *cb_access_context = GetAccessContext(commandBuffer);
4586 assert(cb_access_context);
4587 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
4588 auto *context = cb_access_context->GetCurrentAccessContext();
4589 assert(context);
4590
locke-lunarg61870c22020-06-09 14:51:50 -06004591 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4592 cb_access_context->RecordDrawSubpassAttachment(tag);
4593 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004594
4595 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4596 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4597 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004598 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004599}
4600
4601bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4602 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004603 bool skip = false;
4604 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06004605 const auto *cb_access_context = GetAccessContext(commandBuffer);
4606 assert(cb_access_context);
4607 if (!cb_access_context) return skip;
4608
4609 const auto *context = cb_access_context->GetCurrentAccessContext();
4610 assert(context);
4611 if (!context) return skip;
4612
locke-lunarg61870c22020-06-09 14:51:50 -06004613 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
4614 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
4615 skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride,
4616 "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004617
4618 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4619 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4620 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004621 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004622 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004623}
4624
4625void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4626 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004627 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004628 auto *cb_access_context = GetAccessContext(commandBuffer);
4629 assert(cb_access_context);
4630 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
4631 auto *context = cb_access_context->GetCurrentAccessContext();
4632 assert(context);
4633
locke-lunarg61870c22020-06-09 14:51:50 -06004634 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4635 cb_access_context->RecordDrawSubpassAttachment(tag);
4636 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004637
4638 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4639 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4640 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004641 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004642}
4643
4644bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4645 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4646 uint32_t stride, const char *function) const {
4647 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004648 const auto *cb_access_context = GetAccessContext(commandBuffer);
4649 assert(cb_access_context);
4650 if (!cb_access_context) return skip;
4651
4652 const auto *context = cb_access_context->GetCurrentAccessContext();
4653 assert(context);
4654 if (!context) return skip;
4655
locke-lunarg61870c22020-06-09 14:51:50 -06004656 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4657 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
4658 skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset, maxDrawCount, stride,
4659 function);
4660 skip |= ValidateCountBuffer(*context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004661
4662 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4663 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4664 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004665 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004666 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004667}
4668
4669bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4670 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4671 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004672 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4673 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004674}
4675
4676void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4677 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4678 uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004679 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4680 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004681 auto *cb_access_context = GetAccessContext(commandBuffer);
4682 assert(cb_access_context);
4683 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECTCOUNT);
4684 auto *context = cb_access_context->GetCurrentAccessContext();
4685 assert(context);
4686
locke-lunarg61870c22020-06-09 14:51:50 -06004687 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4688 cb_access_context->RecordDrawSubpassAttachment(tag);
4689 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
4690 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004691
4692 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4693 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4694 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004695 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004696}
4697
4698bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4699 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4700 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004701 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4702 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004703}
4704
4705void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4706 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4707 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004708 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4709 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004710 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004711}
4712
4713bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4714 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4715 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004716 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4717 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004718}
4719
4720void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4721 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4722 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004723 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
4724 stride);
locke-lunargff255f92020-05-13 18:53:52 -06004725 PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4726}
4727
4728bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4729 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4730 uint32_t stride, const char *function) const {
4731 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004732 const auto *cb_access_context = GetAccessContext(commandBuffer);
4733 assert(cb_access_context);
4734 if (!cb_access_context) return skip;
4735
4736 const auto *context = cb_access_context->GetCurrentAccessContext();
4737 assert(context);
4738 if (!context) return skip;
4739
locke-lunarg61870c22020-06-09 14:51:50 -06004740 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
4741 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
4742 skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, maxDrawCount,
4743 stride, function);
4744 skip |= ValidateCountBuffer(*context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06004745
4746 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
4747 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
4748 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004749 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06004750 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004751}
4752
4753bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4754 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4755 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004756 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4757 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06004758}
4759
4760void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4761 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4762 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004763 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4764 maxDrawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004765 auto *cb_access_context = GetAccessContext(commandBuffer);
4766 assert(cb_access_context);
4767 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECTCOUNT);
4768 auto *context = cb_access_context->GetCurrentAccessContext();
4769 assert(context);
4770
locke-lunarg61870c22020-06-09 14:51:50 -06004771 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4772 cb_access_context->RecordDrawSubpassAttachment(tag);
4773 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
4774 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06004775
4776 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
4777 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06004778 // We will update the index and vertex buffer in SubmitQueue in the future.
4779 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004780}
4781
4782bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
4783 VkDeviceSize offset, VkBuffer countBuffer,
4784 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4785 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004786 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4787 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06004788}
4789
4790void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4791 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4792 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004793 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4794 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004795 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4796}
4797
4798bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
4799 VkDeviceSize offset, VkBuffer countBuffer,
4800 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
4801 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004802 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
4803 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06004804}
4805
4806void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4807 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
4808 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004809 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
4810 maxDrawCount, stride);
locke-lunarge1a67022020-04-29 00:15:36 -06004811 PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride);
4812}
4813
4814bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4815 const VkClearColorValue *pColor, uint32_t rangeCount,
4816 const VkImageSubresourceRange *pRanges) const {
4817 bool skip = false;
4818 const auto *cb_access_context = GetAccessContext(commandBuffer);
4819 assert(cb_access_context);
4820 if (!cb_access_context) return skip;
4821
4822 const auto *context = cb_access_context->GetCurrentAccessContext();
4823 assert(context);
4824 if (!context) return skip;
4825
4826 const auto *image_state = Get<IMAGE_STATE>(image);
4827
4828 for (uint32_t index = 0; index < rangeCount; index++) {
4829 const auto &range = pRanges[index];
4830 if (image_state) {
4831 auto hazard =
4832 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4833 if (hazard.hazard) {
4834 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004835 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004836 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf37ceaed2020-07-03 16:18:15 -06004837 string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004838 }
4839 }
4840 }
4841 return skip;
4842}
4843
4844void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4845 const VkClearColorValue *pColor, uint32_t rangeCount,
4846 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004847 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004848 auto *cb_access_context = GetAccessContext(commandBuffer);
4849 assert(cb_access_context);
4850 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
4851 auto *context = cb_access_context->GetCurrentAccessContext();
4852 assert(context);
4853
4854 const auto *image_state = Get<IMAGE_STATE>(image);
4855
4856 for (uint32_t index = 0; index < rangeCount; index++) {
4857 const auto &range = pRanges[index];
4858 if (image_state) {
4859 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent,
4860 tag);
4861 }
4862 }
4863}
4864
4865bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4866 VkImageLayout imageLayout,
4867 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4868 const VkImageSubresourceRange *pRanges) const {
4869 bool skip = false;
4870 const auto *cb_access_context = GetAccessContext(commandBuffer);
4871 assert(cb_access_context);
4872 if (!cb_access_context) return skip;
4873
4874 const auto *context = cb_access_context->GetCurrentAccessContext();
4875 assert(context);
4876 if (!context) return skip;
4877
4878 const auto *image_state = Get<IMAGE_STATE>(image);
4879
4880 for (uint32_t index = 0; index < rangeCount; index++) {
4881 const auto &range = pRanges[index];
4882 if (image_state) {
4883 auto hazard =
4884 context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent);
4885 if (hazard.hazard) {
4886 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004887 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004888 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf37ceaed2020-07-03 16:18:15 -06004889 string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004890 }
4891 }
4892 }
4893 return skip;
4894}
4895
4896void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4897 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
4898 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004899 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06004900 auto *cb_access_context = GetAccessContext(commandBuffer);
4901 assert(cb_access_context);
4902 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
4903 auto *context = cb_access_context->GetCurrentAccessContext();
4904 assert(context);
4905
4906 const auto *image_state = Get<IMAGE_STATE>(image);
4907
4908 for (uint32_t index = 0; index < rangeCount; index++) {
4909 const auto &range = pRanges[index];
4910 if (image_state) {
4911 context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent,
4912 tag);
4913 }
4914 }
4915}
4916
4917bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
4918 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
4919 VkDeviceSize dstOffset, VkDeviceSize stride,
4920 VkQueryResultFlags flags) const {
4921 bool skip = false;
4922 const auto *cb_access_context = GetAccessContext(commandBuffer);
4923 assert(cb_access_context);
4924 if (!cb_access_context) return skip;
4925
4926 const auto *context = cb_access_context->GetCurrentAccessContext();
4927 assert(context);
4928 if (!context) return skip;
4929
4930 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4931
4932 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004933 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
locke-lunarge1a67022020-04-29 00:15:36 -06004934 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4935 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06004936 skip |=
4937 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4938 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
4939 report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004940 }
4941 }
locke-lunargff255f92020-05-13 18:53:52 -06004942
4943 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004944 return skip;
4945}
4946
4947void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
4948 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4949 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004950 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
4951 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06004952 auto *cb_access_context = GetAccessContext(commandBuffer);
4953 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06004954 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06004955 auto *context = cb_access_context->GetCurrentAccessContext();
4956 assert(context);
4957
4958 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4959
4960 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004961 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
locke-lunarge1a67022020-04-29 00:15:36 -06004962 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag);
4963 }
locke-lunargff255f92020-05-13 18:53:52 -06004964
4965 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06004966}
4967
4968bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4969 VkDeviceSize size, uint32_t data) const {
4970 bool skip = false;
4971 const auto *cb_access_context = GetAccessContext(commandBuffer);
4972 assert(cb_access_context);
4973 if (!cb_access_context) return skip;
4974
4975 const auto *context = cb_access_context->GetCurrentAccessContext();
4976 assert(context);
4977 if (!context) return skip;
4978
4979 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
4980
4981 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004982 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
locke-lunarge1a67022020-04-29 00:15:36 -06004983 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
4984 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06004985 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004986 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf37ceaed2020-07-03 16:18:15 -06004987 report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06004988 }
4989 }
4990 return skip;
4991}
4992
4993void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
4994 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004995 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06004996 auto *cb_access_context = GetAccessContext(commandBuffer);
4997 assert(cb_access_context);
4998 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
4999 auto *context = cb_access_context->GetCurrentAccessContext();
5000 assert(context);
5001
5002 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5003
5004 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005005 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
locke-lunarge1a67022020-04-29 00:15:36 -06005006 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag);
5007 }
5008}
5009
5010bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5011 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5012 const VkImageResolve *pRegions) const {
5013 bool skip = false;
5014 const auto *cb_access_context = GetAccessContext(commandBuffer);
5015 assert(cb_access_context);
5016 if (!cb_access_context) return skip;
5017
5018 const auto *context = cb_access_context->GetCurrentAccessContext();
5019 assert(context);
5020 if (!context) return skip;
5021
5022 const auto *src_image = Get<IMAGE_STATE>(srcImage);
5023 const auto *dst_image = Get<IMAGE_STATE>(dstImage);
5024
5025 for (uint32_t region = 0; region < regionCount; region++) {
5026 const auto &resolve_region = pRegions[region];
5027 if (src_image) {
5028 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
5029 resolve_region.srcOffset, resolve_region.extent);
5030 if (hazard.hazard) {
5031 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005032 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005033 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06005034 string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005035 }
5036 }
5037
5038 if (dst_image) {
5039 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
5040 resolve_region.dstOffset, resolve_region.extent);
5041 if (hazard.hazard) {
5042 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005043 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005044 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf37ceaed2020-07-03 16:18:15 -06005045 string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005046 }
5047 if (skip) break;
5048 }
5049 }
5050
5051 return skip;
5052}
5053
5054void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5055 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5056 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005057 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5058 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005059 auto *cb_access_context = GetAccessContext(commandBuffer);
5060 assert(cb_access_context);
5061 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5062 auto *context = cb_access_context->GetCurrentAccessContext();
5063 assert(context);
5064
5065 auto *src_image = Get<IMAGE_STATE>(srcImage);
5066 auto *dst_image = Get<IMAGE_STATE>(dstImage);
5067
5068 for (uint32_t region = 0; region < regionCount; region++) {
5069 const auto &resolve_region = pRegions[region];
5070 if (src_image) {
5071 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
5072 resolve_region.srcOffset, resolve_region.extent, tag);
5073 }
5074 if (dst_image) {
5075 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
5076 resolve_region.dstOffset, resolve_region.extent, tag);
5077 }
5078 }
5079}
5080
Jeff Leger178b1e52020-10-05 12:22:23 -04005081bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5082 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5083 bool skip = false;
5084 const auto *cb_access_context = GetAccessContext(commandBuffer);
5085 assert(cb_access_context);
5086 if (!cb_access_context) return skip;
5087
5088 const auto *context = cb_access_context->GetCurrentAccessContext();
5089 assert(context);
5090 if (!context) return skip;
5091
5092 const auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5093 const auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
5094
5095 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5096 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5097 if (src_image) {
5098 auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
5099 resolve_region.srcOffset, resolve_region.extent);
5100 if (hazard.hazard) {
5101 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
5102 "vkCmdResolveImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
5103 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
5104 region, string_UsageTag(hazard).c_str());
5105 }
5106 }
5107
5108 if (dst_image) {
5109 auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
5110 resolve_region.dstOffset, resolve_region.extent);
5111 if (hazard.hazard) {
5112 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
5113 "vkCmdResolveImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
5114 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
5115 region, string_UsageTag(hazard).c_str());
5116 }
5117 if (skip) break;
5118 }
5119 }
5120
5121 return skip;
5122}
5123
5124void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5125 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5126 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5127 auto *cb_access_context = GetAccessContext(commandBuffer);
5128 assert(cb_access_context);
5129 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE2KHR);
5130 auto *context = cb_access_context->GetCurrentAccessContext();
5131 assert(context);
5132
5133 auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5134 auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
5135
5136 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5137 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5138 if (src_image) {
5139 context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource,
5140 resolve_region.srcOffset, resolve_region.extent, tag);
5141 }
5142 if (dst_image) {
5143 context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource,
5144 resolve_region.dstOffset, resolve_region.extent, tag);
5145 }
5146 }
5147}
5148
locke-lunarge1a67022020-04-29 00:15:36 -06005149bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5150 VkDeviceSize dataSize, const void *pData) const {
5151 bool skip = false;
5152 const auto *cb_access_context = GetAccessContext(commandBuffer);
5153 assert(cb_access_context);
5154 if (!cb_access_context) return skip;
5155
5156 const auto *context = cb_access_context->GetCurrentAccessContext();
5157 assert(context);
5158 if (!context) return skip;
5159
5160 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5161
5162 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005163 // VK_WHOLE_SIZE not allowed
5164 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
locke-lunarge1a67022020-04-29 00:15:36 -06005165 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
5166 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005167 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005168 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf37ceaed2020-07-03 16:18:15 -06005169 report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005170 }
5171 }
5172 return skip;
5173}
5174
5175void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5176 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005177 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005178 auto *cb_access_context = GetAccessContext(commandBuffer);
5179 assert(cb_access_context);
5180 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5181 auto *context = cb_access_context->GetCurrentAccessContext();
5182 assert(context);
5183
5184 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5185
5186 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005187 // VK_WHOLE_SIZE not allowed
5188 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
locke-lunarge1a67022020-04-29 00:15:36 -06005189 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag);
5190 }
5191}
locke-lunargff255f92020-05-13 18:53:52 -06005192
5193bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5194 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5195 bool skip = false;
5196 const auto *cb_access_context = GetAccessContext(commandBuffer);
5197 assert(cb_access_context);
5198 if (!cb_access_context) return skip;
5199
5200 const auto *context = cb_access_context->GetCurrentAccessContext();
5201 assert(context);
5202 if (!context) return skip;
5203
5204 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5205
5206 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005207 const ResourceAccessRange range = MakeRange(dstOffset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005208 auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range);
5209 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005210 skip |=
5211 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5212 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
5213 report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005214 }
5215 }
5216 return skip;
5217}
5218
5219void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5220 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005221 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005222 auto *cb_access_context = GetAccessContext(commandBuffer);
5223 assert(cb_access_context);
5224 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5225 auto *context = cb_access_context->GetCurrentAccessContext();
5226 assert(context);
5227
5228 const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer);
5229
5230 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005231 const ResourceAccessRange range = MakeRange(dstOffset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005232 context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag);
5233 }
5234}
John Zulauf49beb112020-11-04 16:06:31 -07005235
5236bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5237 bool skip = false;
5238 const auto *cb_context = GetAccessContext(commandBuffer);
5239 assert(cb_context);
5240 if (!cb_context) return skip;
5241
5242 return cb_context->ValidateSetEvent(commandBuffer, event, stageMask);
5243}
5244
5245void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5246 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5247 auto *cb_context = GetAccessContext(commandBuffer);
5248 assert(cb_context);
5249 if (!cb_context) return;
John Zulauf4a6105a2020-11-17 15:11:05 -07005250 const auto tag = cb_context->NextCommandTag(CMD_SETEVENT);
5251 cb_context->RecordSetEvent(commandBuffer, event, stageMask, tag);
John Zulauf49beb112020-11-04 16:06:31 -07005252}
5253
5254bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5255 VkPipelineStageFlags stageMask) const {
5256 bool skip = false;
5257 const auto *cb_context = GetAccessContext(commandBuffer);
5258 assert(cb_context);
5259 if (!cb_context) return skip;
5260
5261 return cb_context->ValidateResetEvent(commandBuffer, event, stageMask);
5262}
5263
5264void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5265 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5266 auto *cb_context = GetAccessContext(commandBuffer);
5267 assert(cb_context);
5268 if (!cb_context) return;
5269
5270 cb_context->RecordResetEvent(commandBuffer, event, stageMask);
5271}
5272
5273bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5274 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5275 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5276 uint32_t bufferMemoryBarrierCount,
5277 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5278 uint32_t imageMemoryBarrierCount,
5279 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5280 bool skip = false;
5281 const auto *cb_context = GetAccessContext(commandBuffer);
5282 assert(cb_context);
5283 if (!cb_context) return skip;
5284
John Zulauf4a6105a2020-11-17 15:11:05 -07005285 return cb_context->ValidateWaitEvents(eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers,
5286 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
John Zulauf49beb112020-11-04 16:06:31 -07005287 pImageMemoryBarriers);
5288}
5289
5290void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5291 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5292 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5293 uint32_t bufferMemoryBarrierCount,
5294 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5295 uint32_t imageMemoryBarrierCount,
5296 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5297 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5298 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5299 imageMemoryBarrierCount, pImageMemoryBarriers);
5300
5301 auto *cb_context = GetAccessContext(commandBuffer);
5302 assert(cb_context);
5303 if (!cb_context) return;
5304
John Zulauf4a6105a2020-11-17 15:11:05 -07005305 const auto tag = cb_context->NextCommandTag(CMD_WAITEVENTS);
John Zulauf49beb112020-11-04 16:06:31 -07005306 cb_context->RecordWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5307 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
John Zulauf4a6105a2020-11-17 15:11:05 -07005308 pImageMemoryBarriers, tag);
5309}
5310
5311void SyncEventState::ResetFirstScope() {
5312 for (const auto address_type : kAddressTypes) {
5313 first_scope[static_cast<size_t>(address_type)].clear();
5314 }
5315 stage_mask = 0U;
5316 exec_scope = 0U;
5317 stage_accesses.reset();
5318}
5319
5320// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
5321SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(VkPipelineStageFlags srcStageMask) const {
5322 IgnoreReason reason = NotIgnored;
5323
5324 if (last_command == CMD_RESETEVENT && !HasBarrier(0U, 0U)) {
5325 reason = ResetWaitRace;
5326 } else if (unsynchronized_set) {
5327 reason = SetRace;
5328 } else {
5329 const VkPipelineStageFlags missing_bits = stage_mask_param & ~srcStageMask;
5330 if (missing_bits) reason = MissingStageBits;
5331 }
5332
5333 return reason;
5334}
5335
5336bool SyncEventState::HasBarrier(VkPipelineStageFlags stageMask, VkPipelineStageFlags exec_scope_arg) const {
5337 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5338 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5339 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005340}