blob: 41c0b62df27fc09eb2553d8d3b62c6c0e4056947 [file] [log] [blame]
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001/* Copyright (c) 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2019-2022 Valve Corporation
3 * Copyright (c) 2019-2022 LunarG, Inc.
John Zulauf9cb530d2019-09-30 14:14:10 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: John Zulauf <jzulauf@lunarg.com>
John Zulaufab7756b2020-12-29 16:10:16 -070018 * Author: Locke Lin <locke@lunarg.com>
19 * Author: Jeremy Gebben <jeremyg@lunarg.com>
John Zulauf9cb530d2019-09-30 14:14:10 -060020 */
21
22#include <limits>
23#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060024#include <memory>
25#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060026#include "synchronization_validation.h"
Jeremy Gebben5f585ae2021-02-02 09:03:06 -070027#include "sync_utils.h"
John Zulauf9cb530d2019-09-30 14:14:10 -060028
John Zulaufea943c52022-02-22 11:05:17 -070029// Utilities to DRY up Get... calls
30template <typename Map, typename Key = typename Map::key_type, typename RetVal = layer_data::optional<typename Map::mapped_type>>
31RetVal GetMappedOptional(const Map &map, const Key &key) {
32 RetVal ret_val;
33 auto it = map.find(key);
34 if (it != map.cend()) {
35 ret_val.emplace(it->second);
36 }
37 return ret_val;
38}
39template <typename Map, typename Fn>
40typename Map::mapped_type GetMapped(const Map &map, const typename Map::key_type &key, Fn &&default_factory) {
41 auto value = GetMappedOptional(map, key);
42 return (value) ? *value : default_factory();
43}
44
45template <typename Map, typename Fn>
John Zulauf397e68b2022-04-19 11:44:07 -060046typename Map::mapped_type GetMappedInsert(Map &map, const typename Map::key_type &key, Fn &&emplace_factory) {
John Zulaufea943c52022-02-22 11:05:17 -070047 auto value = GetMappedOptional(map, key);
48 if (value) {
49 return *value;
50 }
John Zulauf397e68b2022-04-19 11:44:07 -060051 auto insert_it = map.emplace(std::make_pair(key, emplace_factory()));
John Zulaufea943c52022-02-22 11:05:17 -070052 assert(insert_it.second);
53
54 return insert_it.first->second;
55}
56
57template <typename Map, typename Key = typename Map::key_type, typename Mapped = typename Map::mapped_type,
58 typename Value = typename Mapped::element_type>
59Value *GetMappedPlainFromShared(const Map &map, const Key &key) {
60 auto value = GetMappedOptional<Map, Key>(map, key);
61 if (value) return value->get();
62 return nullptr;
63}
64
Jeremy Gebben6fbf8242021-06-21 09:14:46 -060065static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.Binding(); }
John Zulauf264cce02021-02-05 14:40:47 -070066
John Zulauf29d00532021-03-04 13:28:54 -070067static bool SimpleBinding(const IMAGE_STATE &image_state) {
Jeremy Gebben62c3bf42021-07-21 15:38:24 -060068 bool simple =
Jeremy Gebben82e11d52021-07-26 09:19:37 -060069 SimpleBinding(static_cast<const BINDABLE &>(image_state)) || image_state.IsSwapchainImage() || image_state.bind_swapchain;
John Zulauf29d00532021-03-04 13:28:54 -070070
71 // If it's not simple we must have an encoder.
72 assert(!simple || image_state.fragment_encoder.get());
73 return simple;
74}
75
John Zulauf4fa68462021-04-26 21:04:22 -060076static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
77static const std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
John Zulauf43cc7462020-12-03 12:33:12 -070078 AccessAddressType::kLinear, AccessAddressType::kIdealized};
79
John Zulaufd5115702021-01-18 12:34:33 -070080static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
John Zulauf264cce02021-02-05 14:40:47 -070081static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
82 return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
83}
John Zulaufd5115702021-01-18 12:34:33 -070084
John Zulauf9cb530d2019-09-30 14:14:10 -060085static const char *string_SyncHazardVUID(SyncHazard hazard) {
86 switch (hazard) {
87 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070088 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060089 break;
90 case SyncHazard::READ_AFTER_WRITE:
91 return "SYNC-HAZARD-READ_AFTER_WRITE";
92 break;
93 case SyncHazard::WRITE_AFTER_READ:
94 return "SYNC-HAZARD-WRITE_AFTER_READ";
95 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
97 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
98 break;
John Zulauf2f952d22020-02-10 11:34:51 -070099 case SyncHazard::READ_RACING_WRITE:
100 return "SYNC-HAZARD-READ-RACING-WRITE";
101 break;
102 case SyncHazard::WRITE_RACING_WRITE:
103 return "SYNC-HAZARD-WRITE-RACING-WRITE";
104 break;
105 case SyncHazard::WRITE_RACING_READ:
106 return "SYNC-HAZARD-WRITE-RACING-READ";
107 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600108 default:
109 assert(0);
110 }
111 return "SYNC-HAZARD-INVALID";
112}
113
John Zulauf59e25072020-07-17 10:55:21 -0600114static bool IsHazardVsRead(SyncHazard hazard) {
115 switch (hazard) {
116 case SyncHazard::NONE:
117 return false;
118 break;
119 case SyncHazard::READ_AFTER_WRITE:
120 return false;
121 break;
122 case SyncHazard::WRITE_AFTER_READ:
123 return true;
124 break;
125 case SyncHazard::WRITE_AFTER_WRITE:
126 return false;
127 break;
128 case SyncHazard::READ_RACING_WRITE:
129 return false;
130 break;
131 case SyncHazard::WRITE_RACING_WRITE:
132 return false;
133 break;
134 case SyncHazard::WRITE_RACING_READ:
135 return true;
136 break;
137 default:
138 assert(0);
139 }
140 return false;
141}
142
John Zulauf9cb530d2019-09-30 14:14:10 -0600143static const char *string_SyncHazard(SyncHazard hazard) {
144 switch (hazard) {
145 case SyncHazard::NONE:
146 return "NONR";
147 break;
148 case SyncHazard::READ_AFTER_WRITE:
149 return "READ_AFTER_WRITE";
150 break;
151 case SyncHazard::WRITE_AFTER_READ:
152 return "WRITE_AFTER_READ";
153 break;
154 case SyncHazard::WRITE_AFTER_WRITE:
155 return "WRITE_AFTER_WRITE";
156 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700157 case SyncHazard::READ_RACING_WRITE:
158 return "READ_RACING_WRITE";
159 break;
160 case SyncHazard::WRITE_RACING_WRITE:
161 return "WRITE_RACING_WRITE";
162 break;
163 case SyncHazard::WRITE_RACING_READ:
164 return "WRITE_RACING_READ";
165 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600166 default:
167 assert(0);
168 }
169 return "INVALID HAZARD";
170}
171
John Zulauf37ceaed2020-07-03 16:18:15 -0600172static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
173 // Return the info for the first bit found
174 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700175 for (size_t i = 0; i < flags.size(); i++) {
176 if (flags.test(i)) {
177 info = &syncStageAccessInfoByStageAccessIndex[i];
178 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600179 }
180 }
181 return info;
182}
183
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700184static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600185 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700186 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600187 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700188 } else {
189 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
190 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
191 if ((flags & info.stage_access_bit).any()) {
192 if (!out_str.empty()) {
193 out_str.append(sep);
194 }
195 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600196 }
John Zulauf59e25072020-07-17 10:55:21 -0600197 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700198 if (out_str.length() == 0) {
199 out_str.append("Unhandled SyncStageAccess");
200 }
John Zulauf59e25072020-07-17 10:55:21 -0600201 }
202 return out_str;
203}
204
John Zulauf397e68b2022-04-19 11:44:07 -0600205std::ostream &operator<<(std::ostream &out, const ResourceUsageRecord &record) {
206 out << "command: " << CommandTypeString(record.command);
207 out << ", seq_no: " << record.seq_num;
208 if (record.sub_command != 0) {
209 out << ", subcmd: " << record.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700210 }
John Zulauf397e68b2022-04-19 11:44:07 -0600211 return out;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700212}
John Zulauf397e68b2022-04-19 11:44:07 -0600213
John Zulauf4fa68462021-04-26 21:04:22 -0600214static std::string string_UsageIndex(SyncStageAccessIndex usage_index) {
215 const char *stage_access_name = "INVALID_STAGE_ACCESS";
216 if (usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())) {
217 stage_access_name = syncStageAccessInfoByStageAccessIndex[usage_index].name;
218 }
219 return std::string(stage_access_name);
220}
221
John Zulauf397e68b2022-04-19 11:44:07 -0600222struct SyncNodeFormatter {
223 const debug_report_data *report_data;
224 const BASE_NODE *node;
225 const char *label;
226
227 SyncNodeFormatter(const SyncValidator &sync_state, const CMD_BUFFER_STATE *cb_state)
228 : report_data(sync_state.report_data), node(cb_state), label("command_buffer") {}
229 SyncNodeFormatter(const SyncValidator &sync_state, const QUEUE_STATE *q_state)
230 : report_data(sync_state.report_data), node(q_state), label("queue") {}
231};
232
233std::ostream &operator<<(std::ostream &out, const SyncNodeFormatter &formater) {
234 if (formater.node) {
235 out << ", " << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
240 out << ", " << formater.label << ": null handle";
241 }
242 return out;
243}
244
245std::ostream &operator<<(std::ostream &out, const HazardResult &hazard) {
246 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
247 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
248 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
249 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
250 out << "(";
251 if (!hazard.recorded_access.get()) {
252 // if we have a recorded usage the usage is reported from the recorded contexts point of view
253 out << "usage: " << usage_info.name << ", ";
254 }
255 out << "prior_usage: " << stage_access_name;
256 if (IsHazardVsRead(hazard.hazard)) {
257 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
258 out << ", read_barriers: " << string_VkPipelineStageFlags2KHR(barriers);
259 } else {
260 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
261 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
262 }
263 return out;
264}
265
John Zulauf4fa68462021-04-26 21:04:22 -0600266struct NoopBarrierAction {
267 explicit NoopBarrierAction() {}
268 void operator()(ResourceAccessState *access) const {}
John Zulauf5c628d02021-05-04 15:46:36 -0600269 const bool layout_transition = false;
John Zulauf4fa68462021-04-26 21:04:22 -0600270};
271
272// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
273CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
274 : CommandBufferAccessContext(from.sync_state_) {
275 // Copy only the needed fields out of from for a temporary, proxy command buffer context
276 cb_state_ = from.cb_state_;
277 queue_flags_ = from.queue_flags_;
278 destroyed_ = from.destroyed_;
279 access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
280 command_number_ = from.command_number_;
281 subcommand_number_ = from.subcommand_number_;
282 reset_count_ = from.reset_count_;
283
284 const auto *from_context = from.GetCurrentAccessContext();
285 assert(from_context);
286
287 // Construct a fully resolved single access context out of from
288 const NoopBarrierAction noop_barrier;
289 for (AccessAddressType address_type : kAddressTypes) {
290 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
291 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
292 }
293 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
294 cb_access_context_.ImportAsyncContexts(*from_context);
295
296 events_context_ = from.events_context_;
297
298 // We don't want to copy the full render_pass_context_ history just for the proxy.
299}
300
301std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf397e68b2022-04-19 11:44:07 -0600302 if (tag >= access_log_.size()) return std::string();
303
John Zulauf4fa68462021-04-26 21:04:22 -0600304 std::stringstream out;
305 assert(tag < access_log_.size());
306 const auto &record = access_log_[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600307 out << record;
308 if (cb_state_.get() != record.cb_state) {
309 out << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600310 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600311 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600312 return out.str();
313}
John Zulauf397e68b2022-04-19 11:44:07 -0600314
John Zulauf4fa68462021-04-26 21:04:22 -0600315std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
316 std::stringstream out;
317 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
318 out << ", " << FormatUsage(access.tag) << ")";
319 return out.str();
320}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700321
John Zulauf397e68b2022-04-19 11:44:07 -0600322std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600323 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600324 out << hazard;
325 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600326 return out.str();
327}
328
John Zulaufd14743a2020-07-03 09:42:39 -0600329// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
330// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
331// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700332static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700333static const SyncStageAccessFlags kColorAttachmentAccessScope =
334 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
335 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
336 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
337 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700338static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
339 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700340static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
341 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
342 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
343 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700344static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700345static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600346
John Zulauf8e3c3e92021-01-06 11:19:36 -0700347ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700348 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700349 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
350 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
351 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
352
John Zulaufee984022022-04-13 16:39:50 -0600353// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
354static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600355
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600356static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600357
John Zulaufcb7e1672022-05-04 13:46:08 -0600358VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600359 if (size == VK_WHOLE_SIZE) {
360 return (whole_size - offset);
361 }
362 return size;
363}
364
John Zulauf3e86bf02020-09-12 10:47:57 -0600365static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
366 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
367}
368
John Zulauf16adfc92020-04-08 10:28:33 -0600369template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600370static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600371 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
372}
373
John Zulauf355e49b2020-04-24 15:11:15 -0600374static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600375
John Zulauf3e86bf02020-09-12 10:47:57 -0600376static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
377 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
378}
379
380static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
381 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
382}
383
John Zulauf4a6105a2020-11-17 15:11:05 -0700384// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
385//
John Zulauf10f1f522020-12-18 12:00:35 -0700386// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
387//
John Zulauf4a6105a2020-11-17 15:11:05 -0700388// Usage:
389// Constructor() -- initializes the generator to point to the begin of the space declared.
390// * -- the current range of the generator empty signfies end
391// ++ -- advance to the next non-empty range (or end)
392
393// A wrapper for a single range with the same semantics as the actual generators below
394template <typename KeyType>
395class SingleRangeGenerator {
396 public:
397 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700398 const KeyType &operator*() const { return current_; }
399 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700400 SingleRangeGenerator &operator++() {
401 current_ = KeyType(); // just one real range
402 return *this;
403 }
404
405 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
406
407 private:
408 SingleRangeGenerator() = default;
409 const KeyType range_;
410 KeyType current_;
411};
412
John Zulaufae842002021-04-15 18:20:55 -0600413// Generate the ranges that are the intersection of range and the entries in the RangeMap
414template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
415class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700416 public:
John Zulaufd5115702021-01-18 12:34:33 -0700417 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600418 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700419 // Default construction for KeyType *must* be empty range
420 assert(current_.empty());
421 }
John Zulaufae842002021-04-15 18:20:55 -0600422 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700423 SeekBegin();
424 }
John Zulaufae842002021-04-15 18:20:55 -0600425 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700426
John Zulauf4a6105a2020-11-17 15:11:05 -0700427 const KeyType &operator*() const { return current_; }
428 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600429 MapRangesRangeGenerator &operator++() {
430 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700431 UpdateCurrent();
432 return *this;
433 }
434
John Zulaufae842002021-04-15 18:20:55 -0600435 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700436
John Zulaufae842002021-04-15 18:20:55 -0600437 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700438 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600439 if (map_pos_ != map_->cend()) {
440 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 } else {
442 current_ = KeyType();
443 }
444 }
445 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600446 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700447 UpdateCurrent();
448 }
John Zulaufae842002021-04-15 18:20:55 -0600449
450 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
451 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
452 template <typename Pred>
453 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
454 do {
455 ++map_pos_;
456 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
457 UpdateCurrent();
458 return *this;
459 }
460
John Zulauf4a6105a2020-11-17 15:11:05 -0700461 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600462 const RangeMap *map_;
463 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700464 KeyType current_;
465};
John Zulaufd5115702021-01-18 12:34:33 -0700466using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600467using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700468
John Zulaufae842002021-04-15 18:20:55 -0600469// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
470template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
471class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
472 public:
473 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
474 // Default constructed is safe to dereference for "empty" test, but for no other operation.
475 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
476 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
477 : Base(filter, range), pred_(pred) {}
478 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
479
480 PredicatedMapRangesRangeGenerator &operator++() {
481 Base::PredicatedIncrement(pred_);
482 return *this;
483 }
484
485 protected:
486 Predicate pred_;
487};
John Zulauf4a6105a2020-11-17 15:11:05 -0700488
489// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600490// Templated to allow for different Range generators or map sources...
491template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700492class FilteredGeneratorGenerator {
493 public:
John Zulaufd5115702021-01-18 12:34:33 -0700494 // Default constructed is safe to dereference for "empty" test, but for no other operation.
495 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
496 // Default construction for KeyType *must* be empty range
497 assert(current_.empty());
498 }
John Zulaufae842002021-04-15 18:20:55 -0600499 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700500 SeekBegin();
501 }
John Zulaufd5115702021-01-18 12:34:33 -0700502 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700503 const KeyType &operator*() const { return current_; }
504 const KeyType *operator->() const { return &current_; }
505 FilteredGeneratorGenerator &operator++() {
506 KeyType gen_range = GenRange();
507 KeyType filter_range = FilterRange();
508 current_ = KeyType();
509 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
510 if (gen_range.end > filter_range.end) {
511 // if the generated range is beyond the filter_range, advance the filter range
512 filter_range = AdvanceFilter();
513 } else {
514 gen_range = AdvanceGen();
515 }
516 current_ = gen_range & filter_range;
517 }
518 return *this;
519 }
520
521 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
522
523 private:
524 KeyType AdvanceFilter() {
525 ++filter_pos_;
526 auto filter_range = FilterRange();
527 if (filter_range.valid()) {
528 FastForwardGen(filter_range);
529 }
530 return filter_range;
531 }
532 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700533 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700534 auto gen_range = GenRange();
535 if (gen_range.valid()) {
536 FastForwardFilter(gen_range);
537 }
538 return gen_range;
539 }
540
541 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700542 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700543
544 KeyType FastForwardFilter(const KeyType &range) {
545 auto filter_range = FilterRange();
546 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700547 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700548 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
549 if (retry_count < kRetryLimit) {
550 ++filter_pos_;
551 filter_range = FilterRange();
552 retry_count++;
553 } else {
554 // Okay we've tried walking, do a seek.
555 filter_pos_ = filter_->lower_bound(range);
556 break;
557 }
558 }
559 return FilterRange();
560 }
561
562 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
563 // faster.
564 KeyType FastForwardGen(const KeyType &range) {
565 auto gen_range = GenRange();
566 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700567 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700568 gen_range = GenRange();
569 }
570 return gen_range;
571 }
572
573 void SeekBegin() {
574 auto gen_range = GenRange();
575 if (gen_range.empty()) {
576 current_ = KeyType();
577 filter_pos_ = filter_->cend();
578 } else {
579 filter_pos_ = filter_->lower_bound(gen_range);
580 current_ = gen_range & FilterRange();
581 }
582 }
583
John Zulaufae842002021-04-15 18:20:55 -0600584 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700585 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600586 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700587 KeyType current_;
588};
589
590using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
591
John Zulauf5c5e88d2019-12-26 11:22:02 -0700592
John Zulauf3e86bf02020-09-12 10:47:57 -0600593ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
594 VkDeviceSize stride) {
595 VkDeviceSize range_start = offset + first_index * stride;
596 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600597 if (count == UINT32_MAX) {
598 range_size = buf_whole_size - range_start;
599 } else {
600 range_size = count * stride;
601 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600602 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600603}
604
locke-lunarg654e3692020-06-04 17:19:15 -0600605SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
606 VkShaderStageFlagBits stage_flag) {
607 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
608 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
609 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
610 }
611 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
612 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
613 assert(0);
614 }
615 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
616 return stage_access->second.uniform_read;
617 }
618
619 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
620 // Because if write hazard happens, read hazard might or might not happen.
621 // But if write hazard doesn't happen, read hazard is impossible to happen.
622 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700623 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600624 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700625 // TODO: sampled_read
626 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600627}
628
locke-lunarg37047832020-06-12 13:44:45 -0600629bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
630 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
631 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
632 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
633 ? true
634 : false;
635}
636
637bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
638 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
639 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
640 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
641 ? true
642 : false;
643}
644
John Zulauf355e49b2020-04-24 15:11:15 -0600645// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600646template <typename Action>
647static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
648 Action &action) {
649 // At this point the "apply over range" logic only supports a single memory binding
650 if (!SimpleBinding(image_state)) return;
651 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600652 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700653 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
654 image_state.createInfo.extent, base_address);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600655 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700656 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600657 }
658}
659
John Zulauf7635de32020-05-29 17:14:15 -0600660// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
661// Used by both validation and record operations
662//
663// The signature for Action() reflect the needs of both uses.
664template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700665void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
666 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600667 const auto &rp_ci = rp_state.createInfo;
668 const auto *attachment_ci = rp_ci.pAttachments;
669 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
670
671 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
672 const auto *color_attachments = subpass_ci.pColorAttachments;
673 const auto *color_resolve = subpass_ci.pResolveAttachments;
674 if (color_resolve && color_attachments) {
675 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
676 const auto &color_attach = color_attachments[i].attachment;
677 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
678 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
679 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700680 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
681 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600682 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
684 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600685 }
686 }
687 }
688
689 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700690 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600691 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
692 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
693 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
694 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
695 const auto src_ci = attachment_ci[src_at];
696 // The formats are required to match so we can pick either
697 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
698 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
699 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600700
701 // Figure out which aspects are actually touched during resolve operations
702 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700703 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600704 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600705 aspect_string = "depth/stencil";
706 } else if (resolve_depth) {
707 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700708 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600709 aspect_string = "depth";
710 } else if (resolve_stencil) {
711 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700712 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600713 aspect_string = "stencil";
714 }
715
John Zulaufd0ec59f2021-03-13 14:25:08 -0700716 if (aspect_string) {
717 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
718 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
719 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
720 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600721 }
722 }
723}
724
725// Action for validating resolve operations
726class ValidateResolveAction {
727 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700728 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
John Zulaufbb890452021-12-14 11:30:18 -0700729 const CommandExecutionContext &exec_context, const char *func_name)
John Zulauf7635de32020-05-29 17:14:15 -0600730 : render_pass_(render_pass),
731 subpass_(subpass),
732 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700733 exec_context_(exec_context),
John Zulauf7635de32020-05-29 17:14:15 -0600734 func_name_(func_name),
735 skip_(false) {}
736 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulaufd0ec59f2021-03-13 14:25:08 -0700737 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
738 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600739 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700740 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600741 if (hazard.hazard) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700742 skip_ |=
John Zulaufbb890452021-12-14 11:30:18 -0700743 exec_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
744 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
745 " to resolve attachment %" PRIu32 ". Access info %s.",
746 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
John Zulauf397e68b2022-04-19 11:44:07 -0600747 attachment_name, src_at, dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600748 }
749 }
750 // Providing a mechanism for the constructing caller to get the result of the validation
751 bool GetSkip() const { return skip_; }
752
753 private:
754 VkRenderPass render_pass_;
755 const uint32_t subpass_;
756 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700757 const CommandExecutionContext &exec_context_;
John Zulauf7635de32020-05-29 17:14:15 -0600758 const char *func_name_;
759 bool skip_;
760};
761
762// Update action for resolve operations
763class UpdateStateResolveAction {
764 public:
John Zulauf14940722021-04-12 15:19:02 -0600765 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700766 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
767 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600768 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700769 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600770 }
771
772 private:
773 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600774 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600775};
776
John Zulauf59e25072020-07-17 10:55:21 -0600777void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600778 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600779 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600780 usage_index = usage_index_;
781 hazard = hazard_;
782 prior_access = prior_;
783 tag = tag_;
784}
785
John Zulauf4fa68462021-04-26 21:04:22 -0600786void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
787 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
788}
789
John Zulauf1d5f9c12022-05-13 14:51:08 -0600790void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
791
John Zulauf540266b2020-04-06 18:54:53 -0600792AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
793 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600794 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600795 Reset();
796 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700797 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
798 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600799 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600800 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600801 const auto prev_pass = prev_dep.first->pass;
802 const auto &prev_barriers = prev_dep.second;
803 assert(prev_dep.second.size());
804 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
805 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700806 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600807
808 async_.reserve(subpass_dep.async.size());
809 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700810 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600811 }
John Zulauf22aefed2021-03-11 18:14:35 -0700812 if (has_barrier_from_external) {
813 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
814 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
815 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600816 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600817 if (subpass_dep.barrier_to_external.size()) {
818 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600819 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700820}
821
John Zulauf5f13a792020-03-10 07:31:21 -0600822template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700823HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600824 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600825 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600826 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600827
828 HazardResult hazard;
829 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
830 hazard = detector.Detect(prev);
831 }
832 return hazard;
833}
834
John Zulauf4a6105a2020-11-17 15:11:05 -0700835template <typename Action>
836void AccessContext::ForAll(Action &&action) {
837 for (const auto address_type : kAddressTypes) {
838 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600839 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700840 action(address_type, access);
841 }
842 }
843}
844
John Zulauf3d84f1b2020-03-09 13:33:25 -0600845// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
846// the DAG of the contexts (for example subpasses)
847template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700848HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600849 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600850 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600851
John Zulauf1a224292020-06-30 14:52:13 -0600852 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600853 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
854 // so we'll check these first
855 for (const auto &async_context : async_) {
856 hazard = async_context->DetectAsyncHazard(type, detector, range);
857 if (hazard.hazard) return hazard;
858 }
John Zulauf5f13a792020-03-10 07:31:21 -0600859 }
860
John Zulauf1a224292020-06-30 14:52:13 -0600861 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600862
John Zulauf69133422020-05-20 14:55:53 -0600863 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600864 const auto the_end = accesses.cend(); // End is not invalidated
865 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600866 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600867
John Zulauf3cafbf72021-03-26 16:55:19 -0600868 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600869 // Cover any leading gap, or gap between entries
870 if (detect_prev) {
871 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
872 // Cover any leading gap, or gap between entries
873 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600874 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600875 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600876 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600877 if (hazard.hazard) return hazard;
878 }
John Zulauf69133422020-05-20 14:55:53 -0600879 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
880 gap.begin = pos->first.end;
881 }
882
883 hazard = detector.Detect(pos);
884 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600885 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600886 }
887
888 if (detect_prev) {
889 // Detect in the trailing empty as needed
890 gap.end = range.end;
891 if (gap.non_empty()) {
892 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600893 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600894 }
895
896 return hazard;
897}
898
899// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
900template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700901HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
902 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600903 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600904 auto pos = accesses.lower_bound(range);
905 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600906
John Zulauf3d84f1b2020-03-09 13:33:25 -0600907 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600908 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700909 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600910 if (hazard.hazard) break;
911 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600912 }
John Zulauf16adfc92020-04-08 10:28:33 -0600913
John Zulauf3d84f1b2020-03-09 13:33:25 -0600914 return hazard;
915}
916
John Zulaufb02c1eb2020-10-06 16:33:36 -0600917struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700918 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600919 void operator()(ResourceAccessState *access) const {
920 assert(access);
921 access->ApplyBarriers(barriers, true);
922 }
923 const std::vector<SyncBarrier> &barriers;
924};
925
John Zulauf22aefed2021-03-11 18:14:35 -0700926struct ApplyTrackbackStackAction {
927 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
928 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
929 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600930 void operator()(ResourceAccessState *access) const {
931 assert(access);
932 assert(!access->HasPendingState());
933 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600934 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
935 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700936 if (previous_barrier) {
937 assert(bool(*previous_barrier));
938 (*previous_barrier)(access);
939 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600940 }
941 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700942 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600943};
944
945// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
946// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
947// *different* map from dest.
948// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
949// range [first, last)
950template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600951static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
952 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600953 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600954 auto at = entry;
955 for (auto pos = first; pos != last; ++pos) {
956 // Every member of the input iterator range must fit within the remaining portion of entry
957 assert(at->first.includes(pos->first));
958 assert(at != dest->end());
959 // Trim up at to the same size as the entry to resolve
960 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600961 auto access = pos->second; // intentional copy
962 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600963 at->second.Resolve(access);
964 ++at; // Go to the remaining unused section of entry
965 }
966}
967
John Zulaufa0a98292020-09-18 09:30:10 -0600968static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
969 SyncBarrier merged = {};
970 for (const auto &barrier : barriers) {
971 merged.Merge(barrier);
972 }
973 return merged;
974}
975
John Zulaufb02c1eb2020-10-06 16:33:36 -0600976template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700977void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600978 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
979 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600980 if (!range.non_empty()) return;
981
John Zulauf355e49b2020-04-24 15:11:15 -0600982 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
983 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600984 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600985 if (current->pos_B->valid) {
986 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600987 auto access = src_pos->second; // intentional copy
988 barrier_action(&access);
989
John Zulauf16adfc92020-04-08 10:28:33 -0600990 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600991 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
992 trimmed->second.Resolve(access);
993 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600994 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600995 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600996 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600997 }
John Zulauf16adfc92020-04-08 10:28:33 -0600998 } else {
999 // we have to descend to fill this gap
1000 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001001 ResourceAccessRange recurrence_range = current_range;
1002 // The current context is empty for the current range, so recur to fill the gap.
1003 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1004 // is not valid, to minimize that recurrence
1005 if (current->pos_B.at_end()) {
1006 // Do the remainder here....
1007 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001008 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001009 // Recur only over the range until B becomes valid (within the limits of range).
1010 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001011 }
John Zulauf22aefed2021-03-11 18:14:35 -07001012 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1013
John Zulauf355e49b2020-04-24 15:11:15 -06001014 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1015 // iterator of the outer while.
1016
1017 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1018 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1019 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001020 const auto seek_to = recurrence_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
locke-lunarg88dbb542020-06-23 22:05:42 -06001021 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001022 current.seek(seek_to);
1023 } else if (!current->pos_A->valid && infill_state) {
1024 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1025 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1026 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001027 }
John Zulauf5f13a792020-03-10 07:31:21 -06001028 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001029 if (current->range.non_empty()) {
1030 ++current;
1031 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001032 }
John Zulauf1a224292020-06-30 14:52:13 -06001033
1034 // Infill if range goes passed both the current and resolve map prior contents
1035 if (recur_to_infill && (current->range.end < range.end)) {
1036 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001037 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001038 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001039}
1040
John Zulauf22aefed2021-03-11 18:14:35 -07001041template <typename BarrierAction>
1042void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1043 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1044 const BarrierAction &previous_barrier) const {
1045 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1046 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1047}
1048
John Zulauf43cc7462020-12-03 12:33:12 -07001049void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001050 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1051 const ResourceAccessStateFunction *previous_barrier) const {
1052 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001053 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001054 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1055 ResourceAccessState state_copy;
1056 if (previous_barrier) {
1057 assert(bool(*previous_barrier));
1058 state_copy = *infill_state;
1059 (*previous_barrier)(&state_copy);
1060 infill_state = &state_copy;
1061 }
1062 sparse_container::update_range_value(*descent_map, range, *infill_state,
1063 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001064 }
1065 } else {
1066 // Look for something to fill the gap further along.
1067 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001068 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001069 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001070 }
John Zulauf5f13a792020-03-10 07:31:21 -06001071 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001072}
1073
John Zulauf4a6105a2020-11-17 15:11:05 -07001074// Non-lazy import of all accesses, WaitEvents needs this.
1075void AccessContext::ResolvePreviousAccesses() {
1076 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001077 if (!prev_.size()) return; // If no previous contexts, nothing to do
1078
John Zulauf4a6105a2020-11-17 15:11:05 -07001079 for (const auto address_type : kAddressTypes) {
1080 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1081 }
1082}
1083
John Zulauf43cc7462020-12-03 12:33:12 -07001084AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1085 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001086}
1087
John Zulauf1507ee42020-05-18 11:33:09 -06001088static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001089 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1090 ? SYNC_ACCESS_INDEX_NONE
1091 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1092 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001093 return stage_access;
1094}
1095static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001096 const auto stage_access =
1097 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1098 ? SYNC_ACCESS_INDEX_NONE
1099 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1100 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001101 return stage_access;
1102}
1103
John Zulauf7635de32020-05-29 17:14:15 -06001104// Caller must manage returned pointer
1105static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001106 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001107 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001108 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1109 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001110 return proxy;
1111}
1112
John Zulaufb02c1eb2020-10-06 16:33:36 -06001113template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001114void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1115 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1116 const ResourceAccessState *infill_state) const {
1117 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1118 if (!attachment_gen) return;
1119
1120 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1121 const AccessAddressType address_type = view_gen.GetAddressType();
1122 for (; range_gen->non_empty(); ++range_gen) {
1123 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001124 }
John Zulauf62f10592020-04-03 12:20:02 -06001125}
1126
John Zulauf1d5f9c12022-05-13 14:51:08 -06001127template <typename ResolveOp>
1128void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1129 const ResourceAccessState *infill_state, bool recur_to_infill) {
1130 for (auto address_type : kAddressTypes) {
1131 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1132 recur_to_infill);
1133 }
1134}
1135
John Zulauf7635de32020-05-29 17:14:15 -06001136// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001137bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001138 const VkRect2D &render_area, uint32_t subpass,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001139 const AttachmentViewGenVector &attachment_views, const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001140 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001141 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1142 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1143 // those affects have not been recorded yet.
1144 //
1145 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1146 // to apply and only copy then, if this proves a hot spot.
1147 std::unique_ptr<AccessContext> proxy_for_prev;
1148 TrackBack proxy_track_back;
1149
John Zulauf355e49b2020-04-24 15:11:15 -06001150 const auto &transitions = rp_state.subpass_transitions[subpass];
1151 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001152 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1153
1154 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001155 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001156 if (prev_needs_proxy) {
1157 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001158 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001159 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001160 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001161 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001162 }
1163 track_back = &proxy_track_back;
1164 }
1165 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001166 if (hazard.hazard) {
John Zulaufee984022022-04-13 16:39:50 -06001167 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001168 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001169 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1170 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1171 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1172 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1173 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1174 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001175 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001176 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1177 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1178 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1179 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1180 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001181 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001182 }
John Zulauf355e49b2020-04-24 15:11:15 -06001183 }
1184 }
1185 return skip;
1186}
1187
John Zulaufbb890452021-12-14 11:30:18 -07001188bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001189 const VkRect2D &render_area, uint32_t subpass,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001190 const AttachmentViewGenVector &attachment_views, const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001191 bool skip = false;
1192 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001193
John Zulauf1507ee42020-05-18 11:33:09 -06001194 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1195 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001196 const auto &view_gen = attachment_views[i];
1197 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001198 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001199
1200 // Need check in the following way
1201 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1202 // vs. transition
1203 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1204 // for each aspect loaded.
1205
1206 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001207 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001208 const bool is_color = !(has_depth || has_stencil);
1209
1210 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001211 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001212
John Zulaufaff20662020-06-01 14:07:58 -06001213 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001214 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001215
John Zulaufb02c1eb2020-10-06 16:33:36 -06001216 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001217 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001218 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001219 aspect = "color";
1220 } else {
John Zulauf57261402021-08-13 11:32:06 -06001221 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001222 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1223 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001224 aspect = "depth";
1225 }
John Zulauf57261402021-08-13 11:32:06 -06001226 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001227 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1228 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001229 aspect = "stencil";
1230 checked_stencil = true;
1231 }
1232 }
1233
1234 if (hazard.hazard) {
1235 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001236 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001237 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001238 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001239 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001240 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1241 " aspect %s during load with loadOp %s.",
1242 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1243 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001244 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001245 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001246 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001247 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001248 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001249 }
1250 }
1251 }
1252 }
1253 return skip;
1254}
1255
John Zulaufaff20662020-06-01 14:07:58 -06001256// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1257// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1258// store is part of the same Next/End operation.
1259// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001260bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001261 const VkRect2D &render_area, uint32_t subpass,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001262 const AttachmentViewGenVector &attachment_views, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06001263 bool skip = false;
1264 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001265
1266 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1267 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001268 const AttachmentViewGen &view_gen = attachment_views[i];
1269 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001270 const auto &ci = attachment_ci[i];
1271
1272 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1273 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1274 // sake, we treat DONT_CARE as writing.
1275 const bool has_depth = FormatHasDepth(ci.format);
1276 const bool has_stencil = FormatHasStencil(ci.format);
1277 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001278 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001279 if (!has_stencil && !store_op_stores) continue;
1280
1281 HazardResult hazard;
1282 const char *aspect = nullptr;
1283 bool checked_stencil = false;
1284 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001285 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1286 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001287 aspect = "color";
1288 } else {
John Zulauf57261402021-08-13 11:32:06 -06001289 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001290 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001291 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1292 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001293 aspect = "depth";
1294 }
1295 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001296 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1297 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001298 aspect = "stencil";
1299 checked_stencil = true;
1300 }
1301 }
1302
1303 if (hazard.hazard) {
1304 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1305 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001306 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1307 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1308 " %s aspect during store with %s %s. Access info %s",
1309 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect,
1310 op_type_string, store_op_string,
1311 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001312 }
1313 }
1314 }
1315 return skip;
1316}
1317
John Zulaufbb890452021-12-14 11:30:18 -07001318bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001319 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
1320 const char *func_name, uint32_t subpass) const {
John Zulaufbb890452021-12-14 11:30:18 -07001321 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, func_name);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001322 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001323 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001324}
1325
John Zulauf06f6f1e2022-04-19 15:28:11 -06001326AccessContext::TrackBack *AccessContext::AddTrackBack(const AccessContext *context, const SyncBarrier &barrier) {
1327 prev_.emplace_back(context, barrier);
1328 return &prev_.back();
1329}
1330
1331void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1332
John Zulauf3d84f1b2020-03-09 13:33:25 -06001333class HazardDetector {
1334 SyncStageAccessIndex usage_index_;
1335
1336 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001337 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001338 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001339 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001340 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001341 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001342};
1343
John Zulauf69133422020-05-20 14:55:53 -06001344class HazardDetectorWithOrdering {
1345 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001346 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001347
1348 public:
1349 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001350 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001351 }
John Zulauf14940722021-04-12 15:19:02 -06001352 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001353 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001354 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001355 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001356};
1357
John Zulauf16adfc92020-04-08 10:28:33 -06001358HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001359 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001360 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001361 const auto base_address = ResourceBaseAddress(buffer);
1362 HazardDetector detector(usage_index);
1363 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001364}
1365
John Zulauf69133422020-05-20 14:55:53 -06001366template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001367HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1368 DetectOptions options) const {
1369 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1370 if (!attachment_gen) return HazardResult();
1371
1372 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1373 const auto address_type = view_gen.GetAddressType();
1374 for (; range_gen->non_empty(); ++range_gen) {
1375 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1376 if (hazard.hazard) return hazard;
1377 }
1378
1379 return HazardResult();
1380}
1381
1382template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001383HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1384 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1385 const VkExtent3D &extent, DetectOptions options) const {
1386 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001387 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001388 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1389 base_address);
1390 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001391 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001392 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001393 if (hazard.hazard) return hazard;
1394 }
1395 return HazardResult();
1396}
John Zulauf110413c2021-03-20 05:38:38 -06001397template <typename Detector>
1398HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1399 const VkImageSubresourceRange &subresource_range, DetectOptions options) const {
1400 if (!SimpleBinding(image)) return HazardResult();
1401 const auto base_address = ResourceBaseAddress(image);
1402 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
1403 const auto address_type = ImageAddressType(image);
1404 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001405 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1406 if (hazard.hazard) return hazard;
1407 }
1408 return HazardResult();
1409}
John Zulauf69133422020-05-20 14:55:53 -06001410
John Zulauf540266b2020-04-06 18:54:53 -06001411HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1412 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1413 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001414 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1415 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001416 HazardDetector detector(current_usage);
1417 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001418}
1419
1420HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf110413c2021-03-20 05:38:38 -06001421 const VkImageSubresourceRange &subresource_range) const {
John Zulauf69133422020-05-20 14:55:53 -06001422 HazardDetector detector(current_usage);
John Zulauf110413c2021-03-20 05:38:38 -06001423 return DetectHazard(detector, image, subresource_range, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001424}
1425
John Zulaufd0ec59f2021-03-13 14:25:08 -07001426HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1427 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1428 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1429 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1430}
1431
John Zulauf69133422020-05-20 14:55:53 -06001432HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001433 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
John Zulauf69133422020-05-20 14:55:53 -06001434 const VkOffset3D &offset, const VkExtent3D &extent) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001435 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06001436 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001437}
1438
John Zulauf3d84f1b2020-03-09 13:33:25 -06001439class BarrierHazardDetector {
1440 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001441 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001442 SyncStageAccessFlags src_access_scope)
1443 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1444
John Zulauf5f13a792020-03-10 07:31:21 -06001445 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1446 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001447 }
John Zulauf14940722021-04-12 15:19:02 -06001448 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001449 // 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 -07001450 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001451 }
1452
1453 private:
1454 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001455 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001456 SyncStageAccessFlags src_access_scope_;
1457};
1458
John Zulauf4a6105a2020-11-17 15:11:05 -07001459class EventBarrierHazardDetector {
1460 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001461 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001462 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
John Zulauf14940722021-04-12 15:19:02 -06001463 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001464 : usage_index_(usage_index),
1465 src_exec_scope_(src_exec_scope),
1466 src_access_scope_(src_access_scope),
1467 event_scope_(event_scope),
1468 scope_pos_(event_scope.cbegin()),
1469 scope_end_(event_scope.cend()),
1470 scope_tag_(scope_tag) {}
1471
1472 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1473 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1474 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1475 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1476 if (scope_pos_ == scope_end_) return HazardResult();
1477 if (!scope_pos_->first.intersects(pos->first)) {
1478 event_scope_.lower_bound(pos->first);
1479 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1480 }
1481
1482 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1483 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1484 }
John Zulauf14940722021-04-12 15:19:02 -06001485 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001486 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1487 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1488 }
1489
1490 private:
1491 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001492 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001493 SyncStageAccessFlags src_access_scope_;
1494 const SyncEventState::ScopeMap &event_scope_;
1495 SyncEventState::ScopeMap::const_iterator scope_pos_;
1496 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf14940722021-04-12 15:19:02 -06001497 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001498};
1499
Jeremy Gebben40a22942020-12-22 14:22:06 -07001500HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001501 const SyncStageAccessFlags &src_access_scope,
1502 const VkImageSubresourceRange &subresource_range,
1503 const SyncEventState &sync_event, DetectOptions options) const {
1504 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1505 // first access scope map to use, and there's no easy way to plumb it in below.
1506 const auto address_type = ImageAddressType(image);
1507 const auto &event_scope = sync_event.FirstScope(address_type);
1508
1509 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1510 event_scope, sync_event.first_scope_tag);
John Zulauf110413c2021-03-20 05:38:38 -06001511 return DetectHazard(detector, image, subresource_range, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001512}
1513
John Zulaufd0ec59f2021-03-13 14:25:08 -07001514HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1515 DetectOptions options) const {
1516 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1517 barrier.src_access_scope);
1518 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1519}
1520
Jeremy Gebben40a22942020-12-22 14:22:06 -07001521HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001522 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001523 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001524 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001525 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
John Zulauf110413c2021-03-20 05:38:38 -06001526 return DetectHazard(detector, image, subresource_range, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001527}
1528
Jeremy Gebben40a22942020-12-22 14:22:06 -07001529HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001530 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001531 const VkImageMemoryBarrier &barrier) const {
1532 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1533 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1534 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1535}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001536HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001537 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001538 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001539}
John Zulauf355e49b2020-04-24 15:11:15 -06001540
John Zulauf9cb530d2019-09-30 14:14:10 -06001541template <typename Flags, typename Map>
1542SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1543 SyncStageAccessFlags scope = 0;
1544 for (const auto &bit_scope : map) {
1545 if (flag_mask < bit_scope.first) break;
1546
1547 if (flag_mask & bit_scope.first) {
1548 scope |= bit_scope.second;
1549 }
1550 }
1551 return scope;
1552}
1553
Jeremy Gebben40a22942020-12-22 14:22:06 -07001554SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001555 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1556}
1557
Jeremy Gebben40a22942020-12-22 14:22:06 -07001558SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1559 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001560}
1561
Jeremy Gebben40a22942020-12-22 14:22:06 -07001562// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1563SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001564 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1565 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1566 // 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 -06001567 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1568}
1569
1570template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001571void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001572 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1573 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001574 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001575 auto pos = accesses->lower_bound(range);
1576 if (pos == accesses->end() || !pos->first.intersects(range)) {
1577 // The range is empty, fill it with a default value.
1578 pos = action.Infill(accesses, pos, range);
1579 } else if (range.begin < pos->first.begin) {
1580 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001581 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001582 } else if (pos->first.begin < range.begin) {
1583 // Trim the beginning if needed
1584 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1585 ++pos;
1586 }
1587
1588 const auto the_end = accesses->end();
1589 while ((pos != the_end) && pos->first.intersects(range)) {
1590 if (pos->first.end > range.end) {
1591 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1592 }
1593
1594 pos = action(accesses, pos);
1595 if (pos == the_end) break;
1596
1597 auto next = pos;
1598 ++next;
1599 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1600 // Need to infill if next is disjoint
1601 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001602 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001603 next = action.Infill(accesses, next, new_range);
1604 }
1605 pos = next;
1606 }
1607}
John Zulaufd5115702021-01-18 12:34:33 -07001608
1609// Give a comparable interface for range generators and ranges
1610template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001611void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001612 assert(range);
1613 UpdateMemoryAccessState(accesses, *range, action);
1614}
1615
John Zulauf4a6105a2020-11-17 15:11:05 -07001616template <typename Action, typename RangeGen>
1617void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1618 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001619 RangeGen &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
John Zulauf4a6105a2020-11-17 15:11:05 -07001620 for (; range_gen->non_empty(); ++range_gen) {
1621 UpdateMemoryAccessState(accesses, *range_gen, action);
1622 }
1623}
John Zulauf9cb530d2019-09-30 14:14:10 -06001624
John Zulaufd0ec59f2021-03-13 14:25:08 -07001625template <typename Action, typename RangeGen>
1626void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1627 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1628 for (; range_gen->non_empty(); ++range_gen) {
1629 UpdateMemoryAccessState(accesses, *range_gen, action);
1630 }
1631}
John Zulauf9cb530d2019-09-30 14:14:10 -06001632struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001633 using Iterator = ResourceAccessRangeMap::iterator;
1634 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001635 // this is only called on gaps, and never returns a gap.
1636 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001637 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001638 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001639 }
John Zulauf5f13a792020-03-10 07:31:21 -06001640
John Zulauf5c5e88d2019-12-26 11:22:02 -07001641 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001642 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001643 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001644 return pos;
1645 }
1646
John Zulauf43cc7462020-12-03 12:33:12 -07001647 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001648 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001649 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001650 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001651 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001652 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001653 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001654 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001655};
1656
John Zulauf4a6105a2020-11-17 15:11:05 -07001657// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001658struct PipelineBarrierOp {
1659 SyncBarrier barrier;
1660 bool layout_transition;
1661 PipelineBarrierOp(const SyncBarrier &barrier_, bool layout_transition_)
1662 : barrier(barrier_), layout_transition(layout_transition_) {}
1663 PipelineBarrierOp() = default;
John Zulaufd5115702021-01-18 12:34:33 -07001664 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf1e331ec2020-12-04 18:29:38 -07001665 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(barrier, layout_transition); }
1666};
John Zulauf4a6105a2020-11-17 15:11:05 -07001667// The barrier operation for wait events
1668struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001669 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001670 SyncBarrier barrier;
1671 bool layout_transition;
John Zulauf14940722021-04-12 15:19:02 -06001672 WaitEventBarrierOp(const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_, bool layout_transition_)
John Zulaufb7578302022-05-19 13:50:18 -06001673 : scope_ops(scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1674 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001675};
John Zulauf1e331ec2020-12-04 18:29:38 -07001676
John Zulauf4a6105a2020-11-17 15:11:05 -07001677// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1678// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1679// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001680template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001681class ApplyBarrierOpsFunctor {
1682 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001683 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001684 // Only called with a gap, and pos at the lower_bound(range)
1685 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1686 if (!infill_default_) {
1687 return pos;
1688 }
1689 ResourceAccessState default_state;
1690 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1691 return inserted;
1692 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001693
John Zulauf5c628d02021-05-04 15:46:36 -06001694 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001695 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001696 for (const auto &op : barrier_ops_) {
1697 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001698 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001699
John Zulauf89311b42020-09-29 16:28:47 -06001700 if (resolve_) {
1701 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1702 // another walk
1703 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001704 }
1705 return pos;
1706 }
1707
John Zulauf89311b42020-09-29 16:28:47 -06001708 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001709 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1710 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001711 barrier_ops_.reserve(size_hint);
1712 }
John Zulauf5c628d02021-05-04 15:46:36 -06001713 void EmplaceBack(const BarrierOp &op) {
1714 barrier_ops_.emplace_back(op);
1715 infill_default_ |= op.layout_transition;
1716 }
John Zulauf89311b42020-09-29 16:28:47 -06001717
1718 private:
1719 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001720 bool infill_default_;
1721 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001722 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001723};
1724
John Zulauf4a6105a2020-11-17 15:11:05 -07001725// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1726// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1727template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001728class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1729 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1730
John Zulauf4a6105a2020-11-17 15:11:05 -07001731 public:
John Zulaufee984022022-04-13 16:39:50 -06001732 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001733};
1734
John Zulauf1e331ec2020-12-04 18:29:38 -07001735// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001736class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1737 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1738
John Zulauf1e331ec2020-12-04 18:29:38 -07001739 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001740 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001741};
1742
John Zulauf8e3c3e92021-01-06 11:19:36 -07001743void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001744 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001745 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001746 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001747}
1748
John Zulauf8e3c3e92021-01-06 11:19:36 -07001749void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001750 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001751 if (!SimpleBinding(buffer)) return;
1752 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001753 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001754}
John Zulauf355e49b2020-04-24 15:11:15 -06001755
John Zulauf8e3c3e92021-01-06 11:19:36 -07001756void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001757 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1758 if (!SimpleBinding(image)) return;
1759 const auto base_address = ResourceBaseAddress(image);
1760 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
1761 const auto address_type = ImageAddressType(image);
1762 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1763 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1764}
1765void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001766 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001767 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001768 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001769 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001770 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1771 base_address);
1772 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001773 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001774 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001775}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001776
1777void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001778 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001779 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1780 if (!gen) return;
1781 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1782 const auto address_type = view_gen.GetAddressType();
1783 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1784 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001785}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001786
John Zulauf8e3c3e92021-01-06 11:19:36 -07001787void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001788 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001789 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001790 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1791 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001792 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001793}
1794
John Zulaufd0ec59f2021-03-13 14:25:08 -07001795template <typename Action, typename RangeGen>
1796void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1797 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1798 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001799}
1800
1801template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001802void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1803 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1804 if (!gen) return;
1805 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001806}
1807
John Zulaufd0ec59f2021-03-13 14:25:08 -07001808void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1809 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001810 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001811 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001812 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001813}
1814
John Zulaufd0ec59f2021-03-13 14:25:08 -07001815void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001816 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001817 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001818
1819 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1820 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001821 const auto &view_gen = attachment_views[i];
1822 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001823
1824 const auto &ci = attachment_ci[i];
1825 const bool has_depth = FormatHasDepth(ci.format);
1826 const bool has_stencil = FormatHasStencil(ci.format);
1827 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001828 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001829
1830 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001831 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1832 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001833 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001834 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001835 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1836 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001837 }
John Zulauf57261402021-08-13 11:32:06 -06001838 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001839 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001840 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1841 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001842 }
1843 }
1844 }
1845 }
1846}
1847
John Zulauf540266b2020-04-06 18:54:53 -06001848template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001849void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001850 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001851 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001852 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001853 }
1854}
1855
1856void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001857 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1858 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001859 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001860 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001861 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001862 }
1863 }
1864}
1865
John Zulauf4fa68462021-04-26 21:04:22 -06001866// Caller must ensure that lifespan of this is less than from
1867void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1868
John Zulauf355e49b2020-04-24 15:11:15 -06001869// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001870HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1871 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001872
John Zulauf355e49b2020-04-24 15:11:15 -06001873 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001874 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001875
1876 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001877 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1878 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001879 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001880 if (!hazard.hazard) {
1881 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001882 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001883 }
John Zulaufa0a98292020-09-18 09:30:10 -06001884
John Zulauf355e49b2020-04-24 15:11:15 -06001885 return hazard;
1886}
1887
John Zulaufb02c1eb2020-10-06 16:33:36 -06001888void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001889 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001890 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001891 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001892 for (const auto &transition : transitions) {
1893 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001894 const auto &view_gen = attachment_views[transition.attachment];
1895 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001896
1897 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1898 assert(trackback);
1899
1900 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001901 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001902 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001903 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001904 auto &target_map = GetAccessStateMap(address_type);
1905 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001906 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1907 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001908 }
1909
John Zulauf86356ca2020-10-19 11:46:41 -06001910 // If there were no transitions skip this global map walk
1911 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001912 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001913 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001914 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001915}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001916
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001917void CommandBufferAccessContext::ApplyGlobalBarriersToEvents(const SyncExecScope &src, const SyncExecScope &dst) {
John Zulauf669dfd52021-01-27 17:15:28 -07001918 auto *events_context = GetCurrentEventsContext();
1919 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06001920 events_context->ApplyBarrier(src, dst);
John Zulauf4a6105a2020-11-17 15:11:05 -07001921}
1922
locke-lunarg61870c22020-06-09 14:51:50 -06001923bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1924 const char *func_name) const {
1925 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001926 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001927 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001928 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001929 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001930 return skip;
1931 }
1932
1933 using DescriptorClass = cvdescriptorset::DescriptorClass;
1934 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1935 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06001936 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1937
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001938 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001939 const auto raster_state = pipe->RasterizationState();
1940 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001941 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001942 }
locke-lunarg61870c22020-06-09 14:51:50 -06001943 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001944 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06001945 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001946 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06001947 const auto descriptor_type = binding_it.GetType();
1948 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1949 auto array_idx = 0;
1950
1951 if (binding_it.IsVariableDescriptorCount()) {
1952 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1953 }
1954 SyncStageAccessIndex sync_index =
1955 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1956
1957 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1958 uint32_t index = i - index_range.start;
1959 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1960 switch (descriptor->GetClass()) {
1961 case DescriptorClass::ImageSampler:
1962 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07001963 if (descriptor->Invalid()) {
1964 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06001965 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07001966
1967 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
1968 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1969 const auto *img_view_state = image_descriptor->GetImageViewState();
1970 VkImageLayout image_layout = image_descriptor->GetImageLayout();
1971
John Zulauf361fb532020-07-22 10:45:39 -06001972 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06001973 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
1974 // Descriptors, so we do not have to worry about depth slicing here.
1975 // See: VUID 00343
1976 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06001977 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06001978 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06001979
1980 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1981 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1982 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06001983 // Input attachments are subject to raster ordering rules
1984 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001985 SyncOrdering::kRaster, offset, extent);
John Zulauf361fb532020-07-22 10:45:39 -06001986 } else {
John Zulauf110413c2021-03-20 05:38:38 -06001987 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range);
John Zulauf361fb532020-07-22 10:45:39 -06001988 }
John Zulauf110413c2021-03-20 05:38:38 -06001989
John Zulauf33fc1d52020-07-17 11:01:10 -06001990 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001991 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001992 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001993 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1994 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001995 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001996 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
1997 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
1998 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001999 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2000 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002001 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002002 }
2003 break;
2004 }
2005 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002006 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2007 if (texel_descriptor->Invalid()) {
2008 continue;
2009 }
2010 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2011 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002012 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002013 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002014 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002015 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002016 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002017 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
2018 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002019 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2020 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2021 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002022 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002023 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002024 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002025 }
2026 break;
2027 }
2028 case DescriptorClass::GeneralBuffer: {
2029 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002030 if (buffer_descriptor->Invalid()) {
2031 continue;
2032 }
2033 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002034 const ResourceAccessRange range =
2035 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002036 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002037 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002038 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002039 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002040 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
2041 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002042 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2043 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2044 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002045 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002046 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002047 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002048 }
2049 break;
2050 }
2051 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2052 default:
2053 break;
2054 }
2055 }
2056 }
2057 }
2058 return skip;
2059}
2060
2061void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002062 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002063 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002064 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002065 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002066 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002067 return;
2068 }
2069
2070 using DescriptorClass = cvdescriptorset::DescriptorClass;
2071 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2072 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002073 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2074
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002075 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002076 const auto raster_state = pipe->RasterizationState();
2077 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002078 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002079 }
locke-lunarg61870c22020-06-09 14:51:50 -06002080 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002081 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002082 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002083 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06002084 const auto descriptor_type = binding_it.GetType();
2085 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2086 auto array_idx = 0;
2087
2088 if (binding_it.IsVariableDescriptorCount()) {
2089 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2090 }
2091 SyncStageAccessIndex sync_index =
2092 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2093
2094 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2095 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2096 switch (descriptor->GetClass()) {
2097 case DescriptorClass::ImageSampler:
2098 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002099 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2100 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2101 if (image_descriptor->Invalid()) {
2102 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002103 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002104 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002105 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2106 // Descriptors, so we do not have to worry about depth slicing here.
2107 // See: VUID 00343
2108 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002109 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002110 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002111 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2112 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2113 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2114 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002115 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002116 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2117 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002118 }
locke-lunarg61870c22020-06-09 14:51:50 -06002119 break;
2120 }
2121 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002122 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2123 if (texel_descriptor->Invalid()) {
2124 continue;
2125 }
2126 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2127 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002128 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002129 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002130 break;
2131 }
2132 case DescriptorClass::GeneralBuffer: {
2133 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002134 if (buffer_descriptor->Invalid()) {
2135 continue;
2136 }
2137 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002138 const ResourceAccessRange range =
2139 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002140 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002141 break;
2142 }
2143 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2144 default:
2145 break;
2146 }
2147 }
2148 }
2149 }
2150}
2151
2152bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2153 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002154 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002155 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002156 return skip;
2157 }
2158
2159 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2160 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002161 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002162
2163 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002164 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002165 if (binding_description.binding < binding_buffers_size) {
2166 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002167 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002168
locke-lunarg1ae57d62020-11-18 10:49:19 -07002169 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002170 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2171 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002172 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002173 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002174 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002175 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
John Zulauf397e68b2022-04-19 11:44:07 -06002176 func_name, string_SyncHazard(hazard.hazard),
2177 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2178 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002179 }
2180 }
2181 }
2182 return skip;
2183}
2184
John Zulauf14940722021-04-12 15:19:02 -06002185void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002186 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002187 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002188 return;
2189 }
2190 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2191 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002192 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002193
2194 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002195 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002196 if (binding_description.binding < binding_buffers_size) {
2197 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002198 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002199
locke-lunarg1ae57d62020-11-18 10:49:19 -07002200 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002201 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2202 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002203 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2204 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002205 }
2206 }
2207}
2208
2209bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2210 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002211 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002212 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002213 }
locke-lunarg61870c22020-06-09 14:51:50 -06002214
locke-lunarg1ae57d62020-11-18 10:49:19 -07002215 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002216 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002217 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2218 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002219 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002220 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002221 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002222 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
2223 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002224 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002225 }
2226
2227 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2228 // We will detect more accurate range in the future.
2229 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2230 return skip;
2231}
2232
John Zulauf14940722021-04-12 15:19:02 -06002233void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002234 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 -06002235
locke-lunarg1ae57d62020-11-18 10:49:19 -07002236 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002237 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002238 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2239 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002240 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002241
2242 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2243 // We will detect more accurate range in the future.
2244 RecordDrawVertex(UINT32_MAX, 0, tag);
2245}
2246
2247bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002248 bool skip = false;
2249 if (!current_renderpass_context_) return skip;
John Zulauf64ffe552021-02-06 10:25:07 -07002250 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), func_name);
locke-lunarg7077d502020-06-18 21:37:26 -06002251 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002252}
2253
John Zulauf14940722021-04-12 15:19:02 -06002254void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002255 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002256 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002257 }
locke-lunarg61870c22020-06-09 14:51:50 -06002258}
2259
John Zulauf41a9c7c2021-12-07 15:59:53 -07002260ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd, const RENDER_PASS_STATE &rp_state,
2261 const VkRect2D &render_area,
2262 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002263 // Create an access context the current renderpass.
John Zulauf41a9c7c2021-12-07 15:59:53 -07002264 const auto barrier_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2265 const auto load_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002266 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002267 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002268 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002269 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002270 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002271}
2272
John Zulauf41a9c7c2021-12-07 15:59:53 -07002273ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd) {
John Zulauf16adfc92020-04-08 10:28:33 -06002274 assert(current_renderpass_context_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002275 if (!current_renderpass_context_) return NextCommandTag(cmd);
2276
2277 auto store_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kStoreOp);
2278 auto barrier_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2279 auto load_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kLoadOp);
2280
2281 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002282 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002283 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002284}
2285
John Zulauf41a9c7c2021-12-07 15:59:53 -07002286ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd) {
John Zulauf16adfc92020-04-08 10:28:33 -06002287 assert(current_renderpass_context_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002288 if (!current_renderpass_context_) return NextCommandTag(cmd);
John Zulauf16adfc92020-04-08 10:28:33 -06002289
John Zulauf41a9c7c2021-12-07 15:59:53 -07002290 auto store_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kStoreOp);
2291 auto barrier_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2292
2293 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002294 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002295 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002296 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002297}
2298
John Zulauf4a6105a2020-11-17 15:11:05 -07002299void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2300 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002301 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002302 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002303 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002304 }
2305}
2306
John Zulaufae842002021-04-15 18:20:55 -06002307// The is the recorded cb context
John Zulaufbb890452021-12-14 11:30:18 -07002308bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext *proxy_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002309 uint32_t index) const {
2310 assert(proxy_context);
2311 auto *events_context = proxy_context->GetCurrentEventsContext();
2312 auto *access_context = proxy_context->GetCurrentAccessContext();
2313 const ResourceUsageTag base_tag = proxy_context->GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002314 bool skip = false;
2315 ResourceUsageRange tag_range = {0, 0};
2316 const AccessContext *recorded_context = GetCurrentAccessContext();
2317 assert(recorded_context);
2318 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002319 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002320 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002321 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002322 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002323 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002324 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002325 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2326 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002327 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002328 };
John Zulaufbb890452021-12-14 11:30:18 -07002329 const ReplayTrackbackBarriersAction *replay_context = nullptr;
John Zulaufae842002021-04-15 18:20:55 -06002330 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002331 // we update the range to any include layout transition first use writes,
2332 // as they are stored along with the source scope (as effective barrier) when recorded
2333 tag_range.end = sync_op.tag + 1;
John Zulauf610e28c2021-08-03 17:46:23 -06002334 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, proxy_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002335
John Zulaufbb890452021-12-14 11:30:18 -07002336 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002337 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002338 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002339 }
2340 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002341 // Record the barrier into the proxy context.
John Zulaufbb890452021-12-14 11:30:18 -07002342 sync_op.sync_op->ReplayRecord(base_tag + sync_op.tag, access_context, events_context);
2343 replay_context = sync_op.sync_op->GetReplayTrackback();
John Zulauf4fa68462021-04-26 21:04:22 -06002344 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002345 }
2346
John Zulaufbb890452021-12-14 11:30:18 -07002347 // Renderpasses may not cross command buffer boundaries
2348 assert(replay_context == nullptr);
2349
John Zulaufae842002021-04-15 18:20:55 -06002350 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002351 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulaufbb890452021-12-14 11:30:18 -07002352 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002353 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002354 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002355 }
2356
2357 return skip;
2358}
2359
John Zulauf1d5f9c12022-05-13 14:51:08 -06002360void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context, CMD_TYPE cmd) {
John Zulauf4fa68462021-04-26 21:04:22 -06002361 auto *events_context = GetCurrentEventsContext();
2362 auto *access_context = GetCurrentAccessContext();
2363 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2364 assert(recorded_context);
2365
2366 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2367 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002368 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002369 // we update the range to any include layout transition first use writes,
2370 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulaufbb890452021-12-14 11:30:18 -07002371 sync_op.sync_op->ReplayRecord(base_tag + sync_op.tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002372 }
2373
2374 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2375 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002376 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002377}
2378
John Zulauf1d5f9c12022-05-13 14:51:08 -06002379void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002380 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002381 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002382}
2383
John Zulauf3c788ef2022-02-22 12:12:30 -07002384ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002385 // The execution references ensure lifespan for the referenced child CB's...
2386 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002387 InsertRecordedAccessLogEntries(recorded_context);
2388 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002389 return tag_range;
2390}
2391
John Zulauf3c788ef2022-02-22 12:12:30 -07002392void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2393 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2394 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2395}
2396
John Zulauf41a9c7c2021-12-07 15:59:53 -07002397ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2398 ResourceUsageTag next = access_log_.size();
2399 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2400 return next;
2401}
2402
2403ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2404 command_number_++;
2405 subcommand_number_ = 0;
2406 ResourceUsageTag next = access_log_.size();
2407 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2408 return next;
2409}
2410
2411ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2412 if (index == 0) {
2413 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2414 }
2415 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2416}
2417
John Zulaufbb890452021-12-14 11:30:18 -07002418void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2419 auto tag = sync_op->Record(this);
2420 // As renderpass operations can have side effects on the command buffer access context,
2421 // update the sync operation to record these if any.
2422 if (current_renderpass_context_) {
2423 const auto &rpc = *current_renderpass_context_;
2424 sync_op->SetReplayContext(rpc.GetCurrentSubpass(), rpc.GetReplayContext());
2425 }
2426 sync_ops_.emplace_back(tag, std::move(sync_op));
2427}
2428
John Zulaufae842002021-04-15 18:20:55 -06002429class HazardDetectFirstUse {
2430 public:
John Zulaufbb890452021-12-14 11:30:18 -07002431 HazardDetectFirstUse(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
2432 const ReplayTrackbackBarriersAction *replay_barrier)
2433 : recorded_use_(recorded_use), tag_range_(tag_range), replay_barrier_(replay_barrier) {}
John Zulaufae842002021-04-15 18:20:55 -06002434 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufbb890452021-12-14 11:30:18 -07002435 if (replay_barrier_) {
2436 // Intentional copy to apply the replay barrier
2437 auto access = pos->second;
2438 (*replay_barrier_)(&access);
2439 return access.DetectHazard(recorded_use_, tag_range_);
2440 }
John Zulaufae842002021-04-15 18:20:55 -06002441 return pos->second.DetectHazard(recorded_use_, tag_range_);
2442 }
2443 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2444 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2445 }
2446
2447 private:
2448 const ResourceAccessState &recorded_use_;
2449 const ResourceUsageRange &tag_range_;
John Zulaufbb890452021-12-14 11:30:18 -07002450 const ReplayTrackbackBarriersAction *replay_barrier_;
John Zulaufae842002021-04-15 18:20:55 -06002451};
2452
2453// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2454// hazards will be detected
John Zulaufbb890452021-12-14 11:30:18 -07002455HazardResult AccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range, const AccessContext &access_context,
2456 const ReplayTrackbackBarriersAction *replay_barrier) const {
John Zulaufae842002021-04-15 18:20:55 -06002457 HazardResult hazard;
2458 for (const auto address_type : kAddressTypes) {
2459 const auto &recorded_access_map = GetAccessStateMap(address_type);
2460 for (const auto &recorded_access : recorded_access_map) {
2461 // Cull any entries not in the current tag range
2462 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulaufbb890452021-12-14 11:30:18 -07002463 HazardDetectFirstUse detector(recorded_access.second, tag_range, replay_barrier);
John Zulaufae842002021-04-15 18:20:55 -06002464 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2465 if (hazard.hazard) break;
2466 }
2467 }
2468
2469 return hazard;
2470}
2471
John Zulaufbb890452021-12-14 11:30:18 -07002472bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
2473 const CMD_BUFFER_STATE &cmd, const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002474 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002475 const auto &sync_state = exec_context.GetSyncState();
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002476 const auto *pipe = cmd.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002477 if (!pipe) {
2478 return skip;
2479 }
2480
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002481 const auto raster_state = pipe->RasterizationState();
2482 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002483 return skip;
2484 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002485 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002486 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002487
John Zulauf1a224292020-06-30 14:52:13 -06002488 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002489 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002490 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2491 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002492 if (location >= subpass.colorAttachmentCount ||
2493 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002494 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002495 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002496 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2497 if (!view_gen.IsValid()) continue;
2498 HazardResult hazard =
2499 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2500 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002501 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002502 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002503 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002504 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002505 func_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002506 sync_state.report_data->FormatHandle(view_handle).c_str(),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002507 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002508 location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002509 }
2510 }
2511 }
locke-lunarg37047832020-06-12 13:44:45 -06002512
2513 // PHASE1 TODO: Add layout based read/vs. write selection.
2514 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002515 const auto ds_state = pipe->DepthStencilState();
2516 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002517
2518 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2519 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2520 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002521 bool depth_write = false, stencil_write = false;
2522
2523 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002524 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002525 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2526 depth_write = true;
2527 }
2528 // PHASE1 TODO: It needs to check if stencil is writable.
2529 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2530 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2531 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002532 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002533 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2534 stencil_write = true;
2535 }
2536
2537 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2538 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002539 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2540 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2541 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002542 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002543 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002544 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002545 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002546 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002547 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
2548 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002549 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002550 }
2551 }
2552 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002553 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2554 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2555 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002556 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002557 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002558 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002559 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002560 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002561 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
2562 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002563 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002564 }
locke-lunarg61870c22020-06-09 14:51:50 -06002565 }
2566 }
2567 return skip;
2568}
2569
John Zulauf14940722021-04-12 15:19:02 -06002570void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002571 const auto *pipe = cmd.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002572 if (!pipe) {
2573 return;
2574 }
2575
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002576 const auto *raster_state = pipe->RasterizationState();
2577 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002578 return;
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_];
locke-lunarg61870c22020-06-09 14:51:50 -06002582
John Zulauf1a224292020-06-30 14:52:13 -06002583 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002584 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002585 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2586 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002587 if (location >= subpass.colorAttachmentCount ||
2588 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002589 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002590 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002591 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2592 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2593 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2594 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002595 }
2596 }
locke-lunarg37047832020-06-12 13:44:45 -06002597
2598 // PHASE1 TODO: Add layout based read/vs. write selection.
2599 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002600 const auto *ds_state = pipe->DepthStencilState();
2601 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002602 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2603 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2604 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002605 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002606 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2607 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002608
2609 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002610 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2611 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002612 depth_write = true;
2613 }
2614 // PHASE1 TODO: It needs to check if stencil is writable.
2615 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2616 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2617 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002618 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002619 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2620 stencil_write = true;
2621 }
2622
John Zulaufd0ec59f2021-03-13 14:25:08 -07002623 if (depth_write || stencil_write) {
2624 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2625 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2626 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2627 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002628 }
locke-lunarg61870c22020-06-09 14:51:50 -06002629 }
2630}
2631
John Zulaufbb890452021-12-14 11:30:18 -07002632bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002633 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002634 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002635 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002636 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002637 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002638 func_name);
2639
John Zulauf355e49b2020-04-24 15:11:15 -06002640 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002641 if (next_subpass >= subpass_contexts_.size()) {
2642 return skip;
2643 }
John Zulauf1507ee42020-05-18 11:33:09 -06002644 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002645 skip |=
John Zulaufbb890452021-12-14 11:30:18 -07002646 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002647 if (!skip) {
2648 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2649 // on a copy of the (empty) next context.
2650 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2651 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002652 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002653 skip |=
John Zulaufbb890452021-12-14 11:30:18 -07002654 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002655 }
John Zulauf7635de32020-05-29 17:14:15 -06002656 return skip;
2657}
John Zulaufbb890452021-12-14 11:30:18 -07002658bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002659 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002660 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002661 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002662 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002663 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_,
John Zulaufd0ec59f2021-03-13 14:25:08 -07002664
2665 attachment_views_, func_name);
John Zulaufbb890452021-12-14 11:30:18 -07002666 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002667 return skip;
2668}
2669
John Zulauf64ffe552021-02-06 10:25:07 -07002670AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002671 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002672}
2673
John Zulaufbb890452021-12-14 11:30:18 -07002674bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
John Zulauf64ffe552021-02-06 10:25:07 -07002675 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002676 bool skip = false;
2677
John Zulauf7635de32020-05-29 17:14:15 -06002678 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2679 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2680 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2681 // to apply and only copy then, if this proves a hot spot.
2682 std::unique_ptr<AccessContext> proxy_for_current;
2683
John Zulauf355e49b2020-04-24 15:11:15 -06002684 // Validate the "finalLayout" transitions to external
2685 // Get them from where there we're hidding in the extra entry.
2686 const auto &final_transitions = rp_state_->subpass_transitions.back();
2687 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002688 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002689 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002690 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2691 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002692
2693 if (transition.prev_pass == current_subpass_) {
2694 if (!proxy_for_current) {
2695 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
John Zulauf64ffe552021-02-06 10:25:07 -07002696 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002697 }
2698 context = proxy_for_current.get();
2699 }
2700
John Zulaufa0a98292020-09-18 09:30:10 -06002701 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2702 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002703 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002704 if (hazard.hazard) {
John Zulaufee984022022-04-13 16:39:50 -06002705 if (hazard.tag == kInvalidTag) {
2706 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002707 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002708 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2709 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2710 " final image layout transition (old_layout: %s, new_layout: %s).",
2711 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2712 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2713 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002714 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002715 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2716 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2717 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2718 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2719 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002720 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002721 }
John Zulauf355e49b2020-04-24 15:11:15 -06002722 }
2723 }
2724 return skip;
2725}
2726
John Zulauf14940722021-04-12 15:19:02 -06002727void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002728 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002729 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002730}
2731
John Zulauf14940722021-04-12 15:19:02 -06002732void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002733 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2734 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002735
2736 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2737 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002738 const AttachmentViewGen &view_gen = attachment_views_[i];
2739 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002740
2741 const auto &ci = attachment_ci[i];
2742 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002743 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002744 const bool is_color = !(has_depth || has_stencil);
2745
2746 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002747 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2748 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2749 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2750 SyncOrdering::kColorAttachment, tag);
2751 }
John Zulauf1507ee42020-05-18 11:33:09 -06002752 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002753 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002754 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2755 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2756 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2757 SyncOrdering::kDepthStencilAttachment, tag);
2758 }
John Zulauf1507ee42020-05-18 11:33:09 -06002759 }
2760 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002761 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2762 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2763 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2764 SyncOrdering::kDepthStencilAttachment, tag);
2765 }
John Zulauf1507ee42020-05-18 11:33:09 -06002766 }
2767 }
2768 }
2769 }
2770}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002771AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2772 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2773 AttachmentViewGenVector view_gens;
2774 VkExtent3D extent = CastTo3D(render_area.extent);
2775 VkOffset3D offset = CastTo3D(render_area.offset);
2776 view_gens.reserve(attachment_views.size());
2777 for (const auto *view : attachment_views) {
2778 view_gens.emplace_back(view, offset, extent);
2779 }
2780 return view_gens;
2781}
John Zulauf64ffe552021-02-06 10:25:07 -07002782RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2783 VkQueueFlags queue_flags,
2784 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2785 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002786 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002787 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002788 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulaufbb890452021-12-14 11:30:18 -07002789 replay_context_ = std::make_shared<ReplayRenderpassContext>();
2790 auto &replay_subpass_contexts = replay_context_->subpass_contexts;
2791 replay_subpass_contexts.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002792 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002793 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulaufbb890452021-12-14 11:30:18 -07002794 replay_subpass_contexts.emplace_back(queue_flags, rp_state_->subpass_dependencies[pass], replay_subpass_contexts);
John Zulauf355e49b2020-04-24 15:11:15 -06002795 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002796 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002797}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002798void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002799 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002800 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2801 RecordLayoutTransitions(barrier_tag);
2802 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002803}
John Zulauf1507ee42020-05-18 11:33:09 -06002804
John Zulauf41a9c7c2021-12-07 15:59:53 -07002805void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2806 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002807 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002808 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2809 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002810
ziga-lunarg31a3e772022-03-22 11:48:46 +01002811 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2812 return;
2813 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002814 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2815 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002816 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002817 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2818 RecordLayoutTransitions(barrier_tag);
2819 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002820}
2821
John Zulauf41a9c7c2021-12-07 15:59:53 -07002822void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2823 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002824 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002825 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2826 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002827
John Zulauf355e49b2020-04-24 15:11:15 -06002828 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002829 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002830
2831 // Add the "finalLayout" transitions to external
2832 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002833 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2834 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2835 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002836 const auto &final_transitions = rp_state_->subpass_transitions.back();
2837 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002838 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002839 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002840 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002841 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002842 for (const auto &barrier : last_trackback.barriers) {
John Zulaufd5115702021-01-18 12:34:33 -07002843 barrier_action.EmplaceBack(PipelineBarrierOp(barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002844 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002845 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002846 }
2847}
2848
John Zulauf06f6f1e2022-04-19 15:28:11 -06002849SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2850 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002851 SyncExecScope result;
2852 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002853 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002854 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002855 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2856 return result;
2857}
2858
Jeremy Gebben40a22942020-12-22 14:22:06 -07002859SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002860 SyncExecScope result;
2861 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002862 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2863 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002864 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2865 return result;
2866}
2867
2868SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002869 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002870 src_access_scope = 0;
John Zulaufc523bf62021-02-16 08:20:34 -07002871 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002872 dst_access_scope = 0;
2873}
2874
2875template <typename Barrier>
2876SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002877 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002878 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002879 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002880 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2881}
2882
2883SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002884 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2885 if (barrier) {
2886 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002887 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002888 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002889
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002890 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002891 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002892 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2893
2894 } else {
2895 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002896 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002897 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2898
2899 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002900 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002901 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2902 }
2903}
2904
2905template <typename Barrier>
2906SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2907 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2908 src_exec_scope = src.exec_scope;
2909 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2910
2911 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002912 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002913 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002914}
2915
John Zulaufb02c1eb2020-10-06 16:33:36 -06002916// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2917void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
2918 for (const auto &barrier : barriers) {
2919 ApplyBarrier(barrier, layout_transition);
2920 }
2921}
2922
John Zulauf89311b42020-09-29 16:28:47 -06002923// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2924// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2925// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002926void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002927 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002928 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002929 assert(!pending_write_dep_chain);
John Zulaufa0a98292020-09-18 09:30:10 -06002930 for (const auto &barrier : barriers) {
John Zulauf89311b42020-09-29 16:28:47 -06002931 ApplyBarrier(barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002932 }
John Zulaufbb890452021-12-14 11:30:18 -07002933 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002934}
John Zulauf9cb530d2019-09-30 14:14:10 -06002935HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2936 HazardResult hazard;
2937 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002938 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002939 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002940 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002941 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002942 }
2943 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002944 // Write operation:
2945 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2946 // If reads exists -- test only against them because either:
2947 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2948 // * 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
2949 // the current write happens after the reads, so just test the write against the reades
2950 // Otherwise test against last_write
2951 //
2952 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002953 if (last_reads.size()) {
2954 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002955 if (IsReadHazard(usage_stage, read_access)) {
2956 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2957 break;
2958 }
2959 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002960 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002961 // Write-After-Write check -- if we have a previous write to test against
2962 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002963 }
2964 }
2965 return hazard;
2966}
2967
John Zulauf4fa68462021-04-26 21:04:22 -06002968HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002969 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf4fa68462021-04-26 21:04:22 -06002970 return DetectHazard(usage_index, ordering);
2971}
2972
2973HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering) const {
John Zulauf69133422020-05-20 14:55:53 -06002974 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2975 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002976 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002977 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002978 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2979 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002980 if (IsRead(usage_bit)) {
2981 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2982 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2983 if (is_raw_hazard) {
2984 // NOTE: we know last_write is non-zero
2985 // See if the ordering rules save us from the simple RAW check above
2986 // First check to see if the current usage is covered by the ordering rules
2987 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2988 const bool usage_is_ordered =
2989 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2990 if (usage_is_ordered) {
2991 // Now see of the most recent write (or a subsequent read) are ordered
2992 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2993 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002994 }
2995 }
John Zulauf4285ee92020-09-23 10:20:52 -06002996 if (is_raw_hazard) {
2997 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
2998 }
John Zulauf5c628d02021-05-04 15:46:36 -06002999 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3000 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
3001 return DetectBarrierHazard(usage_index, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003002 } else {
3003 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003004 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003005 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003006 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003007 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003008 if (usage_write_is_ordered) {
3009 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
3010 ordered_stages = GetOrderedStages(ordering);
3011 }
3012 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3013 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003014 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003015 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3016 if (IsReadHazard(usage_stage, read_access)) {
3017 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3018 break;
3019 }
John Zulaufd14743a2020-07-03 09:42:39 -06003020 }
3021 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003022 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3023 bool ilt_ilt_hazard = false;
3024 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3025 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3026 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3027 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3028 }
3029 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003030 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003031 }
John Zulauf69133422020-05-20 14:55:53 -06003032 }
3033 }
3034 return hazard;
3035}
3036
John Zulaufae842002021-04-15 18:20:55 -06003037HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range) const {
3038 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003039 using Size = FirstAccesses::size_type;
3040 const auto &recorded_accesses = recorded_use.first_accesses_;
3041 Size count = recorded_accesses.size();
3042 if (count) {
3043 const auto &last_access = recorded_accesses.back();
3044 bool do_write_last = IsWrite(last_access.usage_index);
3045 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003046
John Zulauf4fa68462021-04-26 21:04:22 -06003047 for (Size i = 0; i < count; ++count) {
3048 const auto &first = recorded_accesses[i];
3049 // Skip and quit logic
3050 if (first.tag < tag_range.begin) continue;
3051 if (first.tag >= tag_range.end) {
3052 do_write_last = false; // ignore last since we know it can't be in tag_range
3053 break;
3054 }
3055
3056 hazard = DetectHazard(first.usage_index, first.ordering_rule);
3057 if (hazard.hazard) {
3058 hazard.AddRecordedAccess(first);
3059 break;
3060 }
3061 }
3062
3063 if (do_write_last && tag_range.includes(last_access.tag)) {
3064 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3065 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3066 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3067 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3068 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3069 // the barrier that applies them
3070 barrier |= recorded_use.first_write_layout_ordering_;
3071 }
3072 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3073 // the active context
3074 if (recorded_use.first_read_stages_) {
3075 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3076 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3077 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3078 // active context.
3079 barrier.exec_scope |= recorded_use.first_read_stages_;
3080 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3081 barrier.access_scope |= FlagBit(last_access.usage_index);
3082 }
3083 hazard = DetectHazard(last_access.usage_index, barrier);
3084 if (hazard.hazard) {
3085 hazard.AddRecordedAccess(last_access);
3086 }
3087 }
John Zulaufae842002021-04-15 18:20:55 -06003088 }
3089 return hazard;
3090}
3091
John Zulauf2f952d22020-02-10 11:34:51 -07003092// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003093HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003094 HazardResult hazard;
3095 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003096 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3097 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3098 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003099 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003100 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003101 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003102 }
3103 } else {
John Zulauf14940722021-04-12 15:19:02 -06003104 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003105 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003106 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003107 // Any reads during the other subpass will conflict with this write, so we need to check them all.
John Zulaufab7756b2020-12-29 16:10:16 -07003108 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003109 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003110 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003111 break;
3112 }
3113 }
John Zulauf2f952d22020-02-10 11:34:51 -07003114 }
3115 }
3116 return hazard;
3117}
3118
John Zulaufae842002021-04-15 18:20:55 -06003119HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3120 ResourceUsageTag start_tag) const {
3121 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003122 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003123 // Skip and quit logic
3124 if (first.tag < tag_range.begin) continue;
3125 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003126
3127 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003128 if (hazard.hazard) {
3129 hazard.AddRecordedAccess(first);
3130 break;
3131 }
John Zulaufae842002021-04-15 18:20:55 -06003132 }
3133 return hazard;
3134}
3135
Jeremy Gebben40a22942020-12-22 14:22:06 -07003136HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003137 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003138 // Only supporting image layout transitions for now
3139 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3140 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003141 // only test for WAW if there no intervening read operations.
3142 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003143 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003144 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003145 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003146 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003147 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003148 break;
3149 }
3150 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003151 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3152 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3153 }
3154
3155 return hazard;
3156}
3157
Jeremy Gebben40a22942020-12-22 14:22:06 -07003158HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07003159 const SyncStageAccessFlags &src_access_scope,
John Zulauf14940722021-04-12 15:19:02 -06003160 const ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003161 // Only supporting image layout transitions for now
3162 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3163 HazardResult hazard;
3164 // only test for WAW if there no intervening read operations.
3165 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3166
John Zulaufab7756b2020-12-29 16:10:16 -07003167 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003168 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
3169 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07003170 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003171 if (read_access.tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003172 // The read is in the events first synchronization scope, so we use a barrier hazard check
3173 // If the read stage is not in the src sync scope
3174 // *AND* not execution chained with an existing sync barrier (that's the or)
3175 // then the barrier access is unsafe (R/W after R)
3176 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
3177 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3178 break;
3179 }
3180 } else {
3181 // The read not in the event first sync scope and so is a hazard vs. the layout transition
3182 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3183 }
3184 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003185 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003186 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
John Zulauf14940722021-04-12 15:19:02 -06003187 if (write_tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003188 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3189 // So do a normal barrier hazard check
3190 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3191 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3192 }
3193 } else {
3194 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06003195 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3196 }
John Zulaufd14743a2020-07-03 09:42:39 -06003197 }
John Zulauf361fb532020-07-22 10:45:39 -06003198
John Zulauf0cb5be22020-01-23 12:18:22 -07003199 return hazard;
3200}
3201
John Zulauf5f13a792020-03-10 07:31:21 -06003202// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3203// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3204// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3205void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003206 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003207 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3208 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003209 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003210 } else if (other.write_tag == write_tag) {
3211 // In the *equals* case for write operations, we merged the write barriers and the read state (but without the
John Zulauf5f13a792020-03-10 07:31:21 -06003212 // dependency chaining logic or any stage expansion)
3213 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003214 pending_write_barriers |= other.pending_write_barriers;
3215 pending_layout_transition |= other.pending_layout_transition;
3216 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003217 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003218
John Zulaufd14743a2020-07-03 09:42:39 -06003219 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003220 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003221 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003222 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003223 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003224 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003225 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003226 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3227 // but we should wait on profiling data for that.
3228 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003229 auto &my_read = last_reads[my_read_index];
3230 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003231 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003232 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003233 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003234 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003235 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003236 my_read.pending_dep_chain = other_read.pending_dep_chain;
3237 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3238 // May require tracking more than one access per stage.
3239 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003240 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003241 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003242 // Since I'm overwriting the fragement stage read, also update the input attachment info
3243 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003244 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003245 }
John Zulauf14940722021-04-12 15:19:02 -06003246 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003247 // The read tags match so merge the barriers
3248 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003249 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003250 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003251 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003252
John Zulauf5f13a792020-03-10 07:31:21 -06003253 break;
3254 }
3255 }
3256 } else {
3257 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003258 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003259 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003260 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003261 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003262 }
John Zulauf5f13a792020-03-10 07:31:21 -06003263 }
3264 }
John Zulauf361fb532020-07-22 10:45:39 -06003265 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003266 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3267 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003268
3269 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3270 // of the copy and other into this using the update first logic.
3271 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3272 // of the other first_accesses... )
3273 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3274 FirstAccesses firsts(std::move(first_accesses_));
3275 first_accesses_.clear();
3276 first_read_stages_ = 0U;
3277 auto a = firsts.begin();
3278 auto a_end = firsts.end();
3279 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003280 // TODO: Determine whether some tag offset will be needed for PHASE II
3281 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003282 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3283 ++a;
3284 }
3285 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3286 }
3287 for (; a != a_end; ++a) {
3288 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3289 }
3290 }
John Zulauf5f13a792020-03-10 07:31:21 -06003291}
3292
John Zulauf14940722021-04-12 15:19:02 -06003293void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003294 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3295 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003296 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003297 // Mulitple outstanding reads may be of interest and do dependency chains independently
3298 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3299 const auto usage_stage = PipelineStageBit(usage_index);
3300 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003301 for (auto &read_access : last_reads) {
3302 if (read_access.stage == usage_stage) {
3303 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003304 } else if (read_access.barriers & usage_stage) {
3305 read_access.sync_stages |= usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003306 }
3307 }
3308 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003309 for (auto &read_access : last_reads) {
3310 if (read_access.barriers & usage_stage) {
3311 read_access.sync_stages |= usage_stage;
3312 }
3313 }
John Zulaufab7756b2020-12-29 16:10:16 -07003314 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003315 last_read_stages |= usage_stage;
3316 }
John Zulauf4285ee92020-09-23 10:20:52 -06003317
3318 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
Jeremy Gebben40a22942020-12-22 14:22:06 -07003319 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003320 // TODO Revisit re: multiple reads for a given stage
3321 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003322 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003323 } else {
3324 // Assume write
3325 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003326 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003327 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003328 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003329}
John Zulauf5f13a792020-03-10 07:31:21 -06003330
John Zulauf89311b42020-09-29 16:28:47 -06003331// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3332// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3333// We can overwrite them as *this* write is now after them.
3334//
3335// Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them.
John Zulauf14940722021-04-12 15:19:02 -06003336void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003337 ClearRead();
3338 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003339 write_tag = tag;
3340 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003341}
3342
John Zulauf1d5f9c12022-05-13 14:51:08 -06003343void ResourceAccessState::ClearWrite() {
3344 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3345 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3346 write_barriers.reset();
3347 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3348 last_write.reset();
3349
3350 write_tag = 0;
3351 write_queue = QueueSyncState::kQueueIdInvalid;
3352}
3353
3354void ResourceAccessState::ClearRead() {
3355 last_reads.clear();
3356 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3357}
3358
John Zulauf89311b42020-09-29 16:28:47 -06003359// Apply the memory barrier without updating the existing barriers. The execution barrier
3360// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3361// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3362// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003363template <typename ScopeOps>
3364void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003365 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3366 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003367 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
John Zulaufb7578302022-05-19 13:50:18 -06003368 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003369 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3370 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003371 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003372 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003373 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003374 if (layout_transition) {
3375 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3376 }
John Zulaufa0a98292020-09-18 09:30:10 -06003377 }
John Zulauf89311b42020-09-29 16:28:47 -06003378 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3379 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003380
John Zulauf89311b42020-09-29 16:28:47 -06003381 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003382 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3383 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003384 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3385
John Zulaufab7756b2020-12-29 16:10:16 -07003386 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003387 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
John Zulaufb7578302022-05-19 13:50:18 -06003388 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003389 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3390 stages_in_scope |= read_access.stage;
3391 }
3392 }
3393
3394 for (auto &read_access : last_reads) {
3395 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3396 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3397 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3398 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003399 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003400 }
3401 }
John Zulaufa0a98292020-09-18 09:30:10 -06003402 }
John Zulaufa0a98292020-09-18 09:30:10 -06003403}
3404
John Zulaufb7578302022-05-19 13:50:18 -06003405void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) {
3406 return ApplyBarrier(UntaggedScopeOps(), barrier, layout_transition);
John Zulauf4a6105a2020-11-17 15:11:05 -07003407}
John Zulaufb7578302022-05-19 13:50:18 -06003408
John Zulauf14940722021-04-12 15:19:02 -06003409void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003410 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003411 // SetWrite clobbers the last_reads array, and thus we don't have to clear the read_state out.
John Zulauf89311b42020-09-29 16:28:47 -06003412 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003413 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003414 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3415 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003416 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003417 }
John Zulauf89311b42020-09-29 16:28:47 -06003418
3419 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003420 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003421 for (auto &read_access : last_reads) {
3422 read_access.barriers |= read_access.pending_dep_chain;
3423 read_execution_barriers |= read_access.barriers;
3424 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003425 }
3426
3427 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3428 write_dependency_chain |= pending_write_dep_chain;
3429 write_barriers |= pending_write_barriers;
3430 pending_write_dep_chain = 0;
3431 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003432}
3433
John Zulauf1d5f9c12022-05-13 14:51:08 -06003434bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3435 return (queue == usage_queue) && (tag <= usage_tag);
3436}
3437
3438bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3439
3440bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3441
3442// Return if the resulting state is "empty"
3443template <typename Pred>
3444bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3445 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3446
3447 // Use the predicate to build a mask of the read stages we are synchronizing
3448 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003449 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003450 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003451 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3452 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003453 }
3454 }
3455
John Zulauf434c4e62022-05-19 16:03:56 -06003456 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3457 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3458 uint32_t unsync_count = 0;
3459 for (auto &read_access : last_reads) {
3460 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3461 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3462 sync_reads |= read_access.stage;
3463 } else {
3464 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003465 }
3466 }
3467
3468 if (unsync_count) {
3469 if (sync_reads) {
3470 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3471 ReadStates unsync_reads;
3472 unsync_reads.reserve(unsync_count);
3473 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3474 for (auto &read_access : last_reads) {
3475 if (0 == (read_access.stage & sync_reads)) {
3476 unsync_reads.emplace_back(read_access);
3477 unsync_read_stages |= read_access.stage;
3478 }
3479 }
3480 last_read_stages = unsync_read_stages;
3481 last_reads = std::move(unsync_reads);
3482 }
3483 } else {
3484 // Nothing remains (or it was empty to begin with)
3485 ClearRead();
3486 }
3487
3488 bool all_clear = last_reads.size() == 0;
3489 if (last_write.any()) {
3490 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3491 // Clear any predicated write, or any the write from any any access with synchronized reads.
3492 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3493 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3494 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3495 ClearWrite();
3496 } else {
3497 all_clear = false;
3498 }
3499 }
3500 return all_clear;
3501}
3502
John Zulaufae842002021-04-15 18:20:55 -06003503bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3504 if (!first_accesses_.size()) return false;
3505 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3506 return tag_range.intersects(first_access_range);
3507}
3508
John Zulauf1d5f9c12022-05-13 14:51:08 -06003509void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3510 if (last_write.any()) write_tag += offset;
3511 for (auto &read_access : last_reads) {
3512 read_access.tag += offset;
3513 }
3514 for (auto &first : first_accesses_) {
3515 first.tag += offset;
3516 }
3517}
3518
3519ResourceAccessState::ResourceAccessState()
3520 : write_barriers(~SyncStageAccessFlags(0)),
3521 write_dependency_chain(0),
3522 write_tag(),
3523 write_queue(QueueSyncState::kQueueIdInvalid),
3524 last_write(0),
3525 input_attachment_read(false),
3526 last_read_stages(0),
3527 read_execution_barriers(0),
3528 pending_write_dep_chain(0),
3529 pending_layout_transition(false),
3530 pending_write_barriers(0),
3531 pending_layout_ordering_(),
3532 first_accesses_(),
3533 first_read_stages_(0U),
3534 first_write_layout_ordering_() {}
3535
John Zulauf59e25072020-07-17 10:55:21 -06003536// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003537VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3538 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003539
John Zulaufab7756b2020-12-29 16:10:16 -07003540 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003541 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003542 barriers = read_access.barriers;
3543 break;
John Zulauf59e25072020-07-17 10:55:21 -06003544 }
3545 }
John Zulauf4285ee92020-09-23 10:20:52 -06003546
John Zulauf59e25072020-07-17 10:55:21 -06003547 return barriers;
3548}
3549
John Zulauf1d5f9c12022-05-13 14:51:08 -06003550void ResourceAccessState::SetQueueId(QueueId id) {
3551 for (auto &read_access : last_reads) {
3552 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3553 read_access.queue = id;
3554 }
3555 }
3556 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3557 write_queue = id;
3558 }
3559}
3560
John Zulaufb7578302022-05-19 13:50:18 -06003561bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3562 SyncStageAccessFlags src_access_scope) const {
3563 return (src_access_scope & last_write).any() || (write_dependency_chain & src_exec_scope);
3564}
3565
3566bool ResourceAccessState::WriteInEventScope(const SyncStageAccessFlags &src_access_scope, ResourceUsageTag scope_tag) const {
3567 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3568 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3569 // in order to know if it's in the excecution scope
3570 return (write_tag < scope_tag) && (src_access_scope & last_write).any();
3571}
3572
John Zulaufcb7e1672022-05-04 13:46:08 -06003573bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003574 assert(IsRead(usage));
3575 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3576 // * the previous reads are not hazards, and thus last_write must be visible and available to
3577 // any reads that happen after.
3578 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3579 // 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 -07003580 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003581}
3582
Jeremy Gebben40a22942020-12-22 14:22:06 -07003583VkPipelineStageFlags2KHR ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003584 // Whether the stage are in the ordering scope only matters if the current write is ordered
Jeremy Gebben40a22942020-12-22 14:22:06 -07003585 VkPipelineStageFlags2KHR ordered_stages = last_read_stages & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003586 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003587 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003588 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003589 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
Jeremy Gebben40a22942020-12-22 14:22:06 -07003590 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003591 }
3592
3593 return ordered_stages;
3594}
3595
John Zulauf14940722021-04-12 15:19:02 -06003596void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003597 // Only record until we record a write.
3598 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003599 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003600 if (0 == (usage_stage & first_read_stages_)) {
3601 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003602 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003603 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003604 if (0 == (read_execution_barriers & usage_stage)) {
3605 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3606 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3607 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003608 }
3609 }
3610}
3611
John Zulauf4fa68462021-04-26 21:04:22 -06003612void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3613 // Only call this after recording an image layout transition
3614 assert(first_accesses_.size());
3615 if (first_accesses_.back().tag == tag) {
3616 // If this layout transition is the the first write, add the additional ordering rules that guard the ILT
Samuel Iglesias Gonsálvez9b4660b2021-10-21 08:50:39 +02003617 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003618 first_write_layout_ordering_ = layout_ordering;
3619 }
3620}
3621
John Zulauf1d5f9c12022-05-13 14:51:08 -06003622ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3623 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3624 : stage(stage_),
3625 access(access_),
3626 barriers(barriers_),
3627 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3628 tag(tag_),
3629 queue(QueueSyncState::kQueueIdInvalid),
3630 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3631
John Zulaufee984022022-04-13 16:39:50 -06003632void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3633 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3634 stage = stage_;
3635 access = access_;
3636 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003637 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003638 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003639 pending_dep_chain = VK_PIPELINE_STAGE_2_NONE; // If this is a new read, we aren't applying a barrier set.
John Zulaufee984022022-04-13 16:39:50 -06003640}
3641
John Zulauf697c0e12022-04-19 16:31:12 -06003642ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3643 ResourceUsageRange reserve;
3644 reserve.begin = tag_limit_.fetch_add(tag_count);
3645 reserve.end = reserve.begin + tag_count;
3646 return reserve;
3647}
3648
John Zulaufbbda4572022-04-19 16:20:45 -06003649const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3650 return GetMappedPlainFromShared(queue_sync_states_, queue);
3651}
3652
3653QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3654
3655std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3656 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3657}
3658
3659std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3660 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3661}
3662
John Zulauf1d5f9c12022-05-13 14:51:08 -06003663template <typename BatchSet, typename Predicate>
3664static BatchSet GetQueueLastBatchSnapshotImpl(const SyncValidator::QueueSyncStatesMap &queues, Predicate &&pred) {
3665 BatchSet snapshot;
3666 for (auto &queue : queues) {
John Zulauf697c0e12022-04-19 16:31:12 -06003667 auto batch = queue.second->LastBatch();
John Zulauf1d5f9c12022-05-13 14:51:08 -06003668 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003669 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003670 return snapshot;
3671}
3672
3673template <typename Predicate>
3674QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
3675 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::ConstBatchSet, Predicate>(queue_sync_states_,
3676 std::forward<Predicate>(pred));
3677}
3678
3679template <typename Predicate>
3680QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
3681 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::BatchSet, Predicate>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf697c0e12022-04-19 16:31:12 -06003682}
3683
John Zulaufcb7e1672022-05-04 13:46:08 -06003684bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3685 const std::shared_ptr<QueueBatchContext> &batch,
3686 const VkSemaphoreSubmitInfo &signal_info) {
3687 const SyncExecScope exec_scope =
3688 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3689 const VkSemaphore sem = sem_state->semaphore();
3690 auto signal_it = signaled_.find(sem);
3691 std::shared_ptr<Signal> insert_signal;
3692 if (signal_it == signaled_.end()) {
3693 if (prev_) {
3694 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3695 if (prev_sig) {
3696 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3697 insert_signal = std::make_shared<Signal>(*prev_sig);
3698 }
3699 }
3700 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3701 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003702 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003703
3704 bool success = false;
3705 if (!signal_it->second) {
3706 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3707 success = true;
3708 }
3709
3710 return success;
3711}
3712
3713std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3714 std::shared_ptr<Signal> unsignaled;
3715 const auto found_it = signaled_.find(sem);
3716 if (found_it != signaled_.end()) {
3717 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3718 // a bit.
3719 unsignaled = std::move(found_it->second);
3720 if (!prev_) {
3721 // No parent, not need to keep the entry
3722 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3723 signaled_.erase(found_it);
3724 }
3725 } else if (prev_) {
3726 // We can't unsignal prev_ because it's const * by design.
3727 // We put in an empty placeholder
3728 signaled_.emplace(sem, std::shared_ptr<Signal>());
3729 unsignaled = GetPrev(sem);
3730 }
3731 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3732 // but CoreChecks should have reported it
3733
3734 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003735 return unsignaled;
3736}
3737
John Zulaufcb7e1672022-05-04 13:46:08 -06003738void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3739 // Overwrite the s tate with the last state from this
3740 if (from) {
3741 assert(sem == from->sem_state->semaphore());
3742 signaled_[sem] = std::move(from);
3743 } else {
3744 signaled_.erase(sem);
3745 }
3746}
3747
3748void SignaledSemaphores::Reset() {
3749 signaled_.clear();
3750 prev_ = nullptr;
3751}
3752
John Zulaufea943c52022-02-22 11:05:17 -07003753std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3754 // If we don't have one, make it.
3755 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3756 assert(cb_state.get());
3757 auto queue_flags = cb_state->GetQueueFlags();
3758 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3759}
3760
John Zulaufcb7e1672022-05-04 13:46:08 -06003761std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003762 return GetMappedInsert(cb_access_state, command_buffer,
3763 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3764}
3765
3766std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3767 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3768}
3769
3770const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3771 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3772}
3773
3774CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3775 return GetAccessContextShared(command_buffer).get();
3776}
3777
3778CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3779 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3780}
3781
John Zulaufd1f85d42020-04-15 12:23:15 -06003782void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003783 auto *access_context = GetAccessContextNoInsert(command_buffer);
3784 if (access_context) {
3785 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003786 }
3787}
3788
John Zulaufd1f85d42020-04-15 12:23:15 -06003789void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3790 auto access_found = cb_access_state.find(command_buffer);
3791 if (access_found != cb_access_state.end()) {
3792 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003793 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003794 cb_access_state.erase(access_found);
3795 }
3796}
3797
John Zulauf9cb530d2019-09-30 14:14:10 -06003798bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3799 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3800 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003801 const auto *cb_context = GetAccessContext(commandBuffer);
3802 assert(cb_context);
3803 if (!cb_context) return skip;
3804 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003805
John Zulauf3d84f1b2020-03-09 13:33:25 -06003806 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003807 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3808 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003809
3810 for (uint32_t region = 0; region < regionCount; region++) {
3811 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003812 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003813 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003814 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003815 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003816 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003817 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003818 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003819 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003820 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003821 }
John Zulauf16adfc92020-04-08 10:28:33 -06003822 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003823 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003824 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003825 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003826 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003827 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003828 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003829 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003830 }
3831 }
3832 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003833 }
3834 return skip;
3835}
3836
3837void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3838 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003839 auto *cb_context = GetAccessContext(commandBuffer);
3840 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003841 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003842 auto *context = cb_context->GetCurrentAccessContext();
3843
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003844 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3845 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003846
3847 for (uint32_t region = 0; region < regionCount; region++) {
3848 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003849 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003850 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003851 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003852 }
John Zulauf16adfc92020-04-08 10:28:33 -06003853 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003854 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003855 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003856 }
3857 }
3858}
3859
John Zulauf4a6105a2020-11-17 15:11:05 -07003860void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3861 // Clear out events from the command buffer contexts
3862 for (auto &cb_context : cb_access_state) {
3863 cb_context.second->RecordDestroyEvent(event);
3864 }
3865}
3866
Tony-LunarGef035472021-11-02 10:23:33 -06003867bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
3868 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04003869 bool skip = false;
3870 const auto *cb_context = GetAccessContext(commandBuffer);
3871 assert(cb_context);
3872 if (!cb_context) return skip;
3873 const auto *context = cb_context->GetCurrentAccessContext();
Tony-LunarGef035472021-11-02 10:23:33 -06003874 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003875
3876 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003877 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3878 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003879
3880 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3881 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3882 if (src_buffer) {
3883 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003884 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003885 if (hazard.hazard) {
3886 // TODO -- add tag information to log msg when useful.
3887 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
Tony-LunarGef035472021-11-02 10:23:33 -06003888 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04003889 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06003890 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003891 }
3892 }
3893 if (dst_buffer && !skip) {
3894 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003895 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003896 if (hazard.hazard) {
3897 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
Tony-LunarGef035472021-11-02 10:23:33 -06003898 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04003899 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06003900 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003901 }
3902 }
3903 if (skip) break;
3904 }
3905 return skip;
3906}
3907
Tony-LunarGef035472021-11-02 10:23:33 -06003908bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3909 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3910 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3911}
3912
3913bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
3914 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3915}
3916
3917void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04003918 auto *cb_context = GetAccessContext(commandBuffer);
3919 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06003920 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003921 auto *context = cb_context->GetCurrentAccessContext();
3922
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003923 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3924 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003925
3926 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3927 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3928 if (src_buffer) {
3929 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003930 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003931 }
3932 if (dst_buffer) {
3933 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003934 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003935 }
3936 }
3937}
3938
Tony-LunarGef035472021-11-02 10:23:33 -06003939void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3940 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3941}
3942
3943void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
3944 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3945}
3946
John Zulauf5c5e88d2019-12-26 11:22:02 -07003947bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3948 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3949 const VkImageCopy *pRegions) const {
3950 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003951 const auto *cb_access_context = GetAccessContext(commandBuffer);
3952 assert(cb_access_context);
3953 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003954
John Zulauf3d84f1b2020-03-09 13:33:25 -06003955 const auto *context = cb_access_context->GetCurrentAccessContext();
3956 assert(context);
3957 if (!context) return skip;
3958
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003959 auto src_image = Get<IMAGE_STATE>(srcImage);
3960 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003961 for (uint32_t region = 0; region < regionCount; region++) {
3962 const auto &copy_region = pRegions[region];
3963 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003964 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003965 copy_region.srcOffset, copy_region.extent);
3966 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003967 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003968 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003969 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003970 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003971 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003972 }
3973
3974 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003975 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
ziga-lunarg73746512022-03-23 23:08:17 +01003976 copy_region.dstOffset, copy_region.extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003977 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003978 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003979 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003980 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003981 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003982 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07003983 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003984 }
3985 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003986
John Zulauf5c5e88d2019-12-26 11:22:02 -07003987 return skip;
3988}
3989
3990void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3991 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3992 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003993 auto *cb_access_context = GetAccessContext(commandBuffer);
3994 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003995 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003996 auto *context = cb_access_context->GetCurrentAccessContext();
3997 assert(context);
3998
Jeremy Gebben9f537102021-10-05 16:37:12 -06003999 auto src_image = Get<IMAGE_STATE>(srcImage);
4000 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004001
4002 for (uint32_t region = 0; region < regionCount; region++) {
4003 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004004 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004005 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004006 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004007 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004008 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004009 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004010 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004011 }
4012 }
4013}
4014
Tony-LunarGb61514a2021-11-02 12:36:51 -06004015bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4016 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004017 bool skip = false;
4018 const auto *cb_access_context = GetAccessContext(commandBuffer);
4019 assert(cb_access_context);
4020 if (!cb_access_context) return skip;
4021
4022 const auto *context = cb_access_context->GetCurrentAccessContext();
4023 assert(context);
4024 if (!context) return skip;
4025
Tony-LunarGb61514a2021-11-02 12:36:51 -06004026 const char *func_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004027 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4028 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004029
Jeff Leger178b1e52020-10-05 12:22:23 -04004030 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4031 const auto &copy_region = pCopyImageInfo->pRegions[region];
4032 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004033 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Jeff Leger178b1e52020-10-05 12:22:23 -04004034 copy_region.srcOffset, copy_region.extent);
4035 if (hazard.hazard) {
4036 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sfricke-samsung71f04e32022-03-16 01:21:21 -05004037 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04004038 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004039 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004040 }
4041 }
4042
4043 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004044 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
ziga-lunarg73746512022-03-23 23:08:17 +01004045 copy_region.dstOffset, copy_region.extent);
Jeff Leger178b1e52020-10-05 12:22:23 -04004046 if (hazard.hazard) {
4047 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sfricke-samsung71f04e32022-03-16 01:21:21 -05004048 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04004049 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004050 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004051 }
4052 if (skip) break;
4053 }
4054 }
4055
4056 return skip;
4057}
4058
Tony-LunarGb61514a2021-11-02 12:36:51 -06004059bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4060 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4061 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4062}
4063
4064bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4065 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4066}
4067
4068void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004069 auto *cb_access_context = GetAccessContext(commandBuffer);
4070 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004071 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004072 auto *context = cb_access_context->GetCurrentAccessContext();
4073 assert(context);
4074
Jeremy Gebben9f537102021-10-05 16:37:12 -06004075 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4076 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004077
4078 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4079 const auto &copy_region = pCopyImageInfo->pRegions[region];
4080 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004081 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004082 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004083 }
4084 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004085 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004086 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004087 }
4088 }
4089}
4090
Tony-LunarGb61514a2021-11-02 12:36:51 -06004091void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4092 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4093}
4094
4095void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4096 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4097}
4098
John Zulauf9cb530d2019-09-30 14:14:10 -06004099bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4100 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4101 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4102 uint32_t bufferMemoryBarrierCount,
4103 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4104 uint32_t imageMemoryBarrierCount,
4105 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4106 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004107 const auto *cb_access_context = GetAccessContext(commandBuffer);
4108 assert(cb_access_context);
4109 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004110
John Zulauf36ef9282021-02-02 11:47:24 -07004111 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4112 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4113 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4114 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004115 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004116 return skip;
4117}
4118
4119void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4120 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4121 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4122 uint32_t bufferMemoryBarrierCount,
4123 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4124 uint32_t imageMemoryBarrierCount,
4125 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004126 auto *cb_access_context = GetAccessContext(commandBuffer);
4127 assert(cb_access_context);
4128 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004129
John Zulauf1bf30522021-09-03 15:39:06 -06004130 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4131 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4132 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4133 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004134}
4135
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004136bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4137 const VkDependencyInfoKHR *pDependencyInfo) const {
4138 bool skip = false;
4139 const auto *cb_access_context = GetAccessContext(commandBuffer);
4140 assert(cb_access_context);
4141 if (!cb_access_context) return skip;
4142
4143 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4144 skip = pipeline_barrier.Validate(*cb_access_context);
4145 return skip;
4146}
4147
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004148bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4149 const VkDependencyInfo *pDependencyInfo) const {
4150 bool skip = false;
4151 const auto *cb_access_context = GetAccessContext(commandBuffer);
4152 assert(cb_access_context);
4153 if (!cb_access_context) return skip;
4154
4155 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4156 skip = pipeline_barrier.Validate(*cb_access_context);
4157 return skip;
4158}
4159
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004160void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4161 auto *cb_access_context = GetAccessContext(commandBuffer);
4162 assert(cb_access_context);
4163 if (!cb_access_context) return;
4164
John Zulauf1bf30522021-09-03 15:39:06 -06004165 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4166 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004167}
4168
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004169void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4170 auto *cb_access_context = GetAccessContext(commandBuffer);
4171 assert(cb_access_context);
4172 if (!cb_access_context) return;
4173
4174 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4175 *pDependencyInfo);
4176}
4177
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004178void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004179 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004180 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004181
John Zulauf5f13a792020-03-10 07:31:21 -06004182 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4183 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004184 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004185 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4186 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004187
John Zulauf1d5f9c12022-05-13 14:51:08 -06004188 QueueId queue_id = QueueSyncState::kQueueIdBase;
4189 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004190 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004191 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004192 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4193 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004194}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004195
John Zulauf355e49b2020-04-24 15:11:15 -06004196bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07004197 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004198 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004199 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004200 if (cb_context) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004201 SyncOpBeginRenderPass sync_op(cmd, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004202 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004203 }
John Zulauf355e49b2020-04-24 15:11:15 -06004204 return skip;
4205}
4206
4207bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4208 VkSubpassContents contents) const {
4209 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004210 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004211 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004212 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004213 return skip;
4214}
4215
4216bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004217 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004218 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004219 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004220 return skip;
4221}
4222
4223bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4224 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004225 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004226 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004227 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004228 return skip;
4229}
4230
John Zulauf3d84f1b2020-03-09 13:33:25 -06004231void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4232 VkResult result) {
4233 // The state tracker sets up the command buffer state
4234 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4235
4236 // Create/initialize the structure that trackers accesses at the command buffer scope.
4237 auto cb_access_context = GetAccessContext(commandBuffer);
4238 assert(cb_access_context);
4239 cb_access_context->Reset();
4240}
4241
4242void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07004243 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004244 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004245 if (cb_context) {
John Zulaufbb890452021-12-14 11:30:18 -07004246 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004247 }
4248}
4249
4250void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4251 VkSubpassContents contents) {
4252 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004253 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004254 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004255 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004256}
4257
4258void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4259 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4260 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004261 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004262}
4263
4264void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4265 const VkRenderPassBeginInfo *pRenderPassBegin,
4266 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4267 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004268 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004269}
4270
Mike Schuchardt2df08912020-12-15 16:28:09 -08004271bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07004272 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004273 bool skip = false;
4274
4275 auto cb_context = GetAccessContext(commandBuffer);
4276 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004277 if (!cb_context) return skip;
sfricke-samsung85584a72021-09-30 21:43:38 -07004278 SyncOpNextSubpass sync_op(cmd, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004279 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004280}
4281
4282bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4283 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004284 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004285 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004286 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004287 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4288 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004289 return skip;
4290}
4291
Mike Schuchardt2df08912020-12-15 16:28:09 -08004292bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4293 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004294 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004295 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004296 return skip;
4297}
4298
4299bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4300 const VkSubpassEndInfo *pSubpassEndInfo) const {
4301 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004302 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004303 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004304}
4305
4306void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07004307 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004308 auto cb_context = GetAccessContext(commandBuffer);
4309 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004310 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004311
John Zulaufbb890452021-12-14 11:30:18 -07004312 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004313}
4314
4315void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4316 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004317 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004318 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004319 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004320}
4321
4322void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4323 const VkSubpassEndInfo *pSubpassEndInfo) {
4324 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004325 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004326}
4327
4328void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4329 const VkSubpassEndInfo *pSubpassEndInfo) {
4330 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004331 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004332}
4333
sfricke-samsung85584a72021-09-30 21:43:38 -07004334bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4335 CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004336 bool skip = false;
4337
4338 auto cb_context = GetAccessContext(commandBuffer);
4339 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004340 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004341
sfricke-samsung85584a72021-09-30 21:43:38 -07004342 SyncOpEndRenderPass sync_op(cmd, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004343 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004344 return skip;
4345}
4346
4347bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4348 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004349 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004350 return skip;
4351}
4352
Mike Schuchardt2df08912020-12-15 16:28:09 -08004353bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004354 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004355 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004356 return skip;
4357}
4358
4359bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004360 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004361 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004362 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004363 return skip;
4364}
4365
sfricke-samsung85584a72021-09-30 21:43:38 -07004366void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004367 // Resolve the all subpass contexts to the command buffer contexts
4368 auto cb_context = GetAccessContext(commandBuffer);
4369 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004370 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004371
John Zulaufbb890452021-12-14 11:30:18 -07004372 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004373}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004374
John Zulauf33fc1d52020-07-17 11:01:10 -06004375// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4376// updates to a resource which do not conflict at the byte level.
4377// TODO: Revisit this rule to see if it needs to be tighter or looser
4378// TODO: Add programatic control over suppression heuristics
4379bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4380 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4381}
4382
John Zulauf3d84f1b2020-03-09 13:33:25 -06004383void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004384 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004385 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004386}
4387
4388void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004389 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004390 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004391}
4392
4393void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004394 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004395 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004396}
locke-lunarga19c71d2020-03-02 18:17:04 -07004397
sfricke-samsung71f04e32022-03-16 01:21:21 -05004398template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004399bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004400 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4401 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004402 bool skip = false;
4403 const auto *cb_access_context = GetAccessContext(commandBuffer);
4404 assert(cb_access_context);
4405 if (!cb_access_context) return skip;
4406
Tony Barbour845d29b2021-11-09 11:43:14 -07004407 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004408
locke-lunarga19c71d2020-03-02 18:17:04 -07004409 const auto *context = cb_access_context->GetCurrentAccessContext();
4410 assert(context);
4411 if (!context) return skip;
4412
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004413 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4414 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004415
4416 for (uint32_t region = 0; region < regionCount; region++) {
4417 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004418 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004419 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004420 if (src_buffer) {
4421 ResourceAccessRange src_range =
4422 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004423 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004424 if (hazard.hazard) {
4425 // PHASE1 TODO -- add tag information to log msg when useful.
4426 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4427 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
4428 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004429 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004430 }
4431 }
4432
Jeremy Gebben40a22942020-12-22 14:22:06 -07004433 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
John Zulauf477700e2021-01-06 11:41:49 -07004434 copy_region.imageOffset, copy_region.imageExtent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004435 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004436 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004437 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004438 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004439 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004440 }
4441 if (skip) break;
4442 }
4443 if (skip) break;
4444 }
4445 return skip;
4446}
4447
Jeff Leger178b1e52020-10-05 12:22:23 -04004448bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4449 VkImageLayout dstImageLayout, uint32_t regionCount,
4450 const VkBufferImageCopy *pRegions) const {
4451 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004452 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004453}
4454
4455bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4456 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4457 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4458 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004459 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4460}
4461
4462bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4463 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4464 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4465 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4466 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004467}
4468
sfricke-samsung71f04e32022-03-16 01:21:21 -05004469template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004470void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004471 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4472 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004473 auto *cb_access_context = GetAccessContext(commandBuffer);
4474 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004475
Jeff Leger178b1e52020-10-05 12:22:23 -04004476 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004477 auto *context = cb_access_context->GetCurrentAccessContext();
4478 assert(context);
4479
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004480 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4481 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004482
4483 for (uint32_t region = 0; region < regionCount; region++) {
4484 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004485 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004486 if (src_buffer) {
4487 ResourceAccessRange src_range =
4488 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004489 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004490 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004491 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004492 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004493 }
4494 }
4495}
4496
Jeff Leger178b1e52020-10-05 12:22:23 -04004497void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4498 VkImageLayout dstImageLayout, uint32_t regionCount,
4499 const VkBufferImageCopy *pRegions) {
4500 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004501 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004502}
4503
4504void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4505 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4506 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4507 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4508 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004509 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4510}
4511
4512void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4513 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4514 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4515 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4516 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4517 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004518}
4519
sfricke-samsung71f04e32022-03-16 01:21:21 -05004520template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004521bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004522 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4523 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004524 bool skip = false;
4525 const auto *cb_access_context = GetAccessContext(commandBuffer);
4526 assert(cb_access_context);
4527 if (!cb_access_context) return skip;
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004528 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004529
locke-lunarga19c71d2020-03-02 18:17:04 -07004530 const auto *context = cb_access_context->GetCurrentAccessContext();
4531 assert(context);
4532 if (!context) return skip;
4533
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004534 auto src_image = Get<IMAGE_STATE>(srcImage);
4535 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004536 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004537 for (uint32_t region = 0; region < regionCount; region++) {
4538 const auto &copy_region = pRegions[region];
4539 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004540 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07004541 copy_region.imageOffset, copy_region.imageExtent);
4542 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004543 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004544 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004545 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004546 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004547 }
John Zulauf477700e2021-01-06 11:41:49 -07004548 if (dst_mem) {
4549 ResourceAccessRange dst_range =
4550 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004551 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004552 if (hazard.hazard) {
4553 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4554 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
4555 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004556 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004557 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004558 }
4559 }
4560 if (skip) break;
4561 }
4562 return skip;
4563}
4564
Jeff Leger178b1e52020-10-05 12:22:23 -04004565bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4566 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4567 const VkBufferImageCopy *pRegions) const {
4568 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004569 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004570}
4571
4572bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4573 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4574 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4575 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004576 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4577}
4578
4579bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4580 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4581 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4582 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4583 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004584}
4585
sfricke-samsung71f04e32022-03-16 01:21:21 -05004586template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004587void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004588 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004589 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004590 auto *cb_access_context = GetAccessContext(commandBuffer);
4591 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004592
Jeff Leger178b1e52020-10-05 12:22:23 -04004593 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004594 auto *context = cb_access_context->GetCurrentAccessContext();
4595 assert(context);
4596
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004597 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004598 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004599 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004600 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004601
4602 for (uint32_t region = 0; region < regionCount; region++) {
4603 const auto &copy_region = pRegions[region];
4604 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004605 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004606 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004607 if (dst_buffer) {
4608 ResourceAccessRange dst_range =
4609 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004610 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004611 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004612 }
4613 }
4614}
4615
Jeff Leger178b1e52020-10-05 12:22:23 -04004616void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4617 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4618 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004619 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004620}
4621
4622void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4623 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4624 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4625 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4626 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004627 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4628}
4629
4630void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4631 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4632 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4633 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4634 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4635 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004636}
4637
4638template <typename RegionType>
4639bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4640 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4641 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004642 bool skip = false;
4643 const auto *cb_access_context = GetAccessContext(commandBuffer);
4644 assert(cb_access_context);
4645 if (!cb_access_context) return skip;
4646
4647 const auto *context = cb_access_context->GetCurrentAccessContext();
4648 assert(context);
4649 if (!context) return skip;
4650
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004651 auto src_image = Get<IMAGE_STATE>(srcImage);
4652 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004653
4654 for (uint32_t region = 0; region < regionCount; region++) {
4655 const auto &blit_region = pRegions[region];
4656 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004657 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4658 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4659 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4660 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4661 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4662 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004663 auto hazard = context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004664 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004665 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004666 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004667 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004668 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004669 }
4670 }
4671
4672 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004673 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4674 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4675 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4676 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4677 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4678 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004679 auto hazard = context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004680 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004681 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004682 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004683 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004684 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004685 }
4686 if (skip) break;
4687 }
4688 }
4689
4690 return skip;
4691}
4692
Jeff Leger178b1e52020-10-05 12:22:23 -04004693bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4694 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4695 const VkImageBlit *pRegions, VkFilter filter) const {
4696 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4697 "vkCmdBlitImage");
4698}
4699
4700bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4701 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4702 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4703 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4704 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4705}
4706
Tony-LunarG542ae912021-11-04 16:06:44 -06004707bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4708 const VkBlitImageInfo2 *pBlitImageInfo) const {
4709 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4710 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4711 pBlitImageInfo->filter, "vkCmdBlitImage2");
4712}
4713
Jeff Leger178b1e52020-10-05 12:22:23 -04004714template <typename RegionType>
4715void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4716 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4717 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004718 auto *cb_access_context = GetAccessContext(commandBuffer);
4719 assert(cb_access_context);
4720 auto *context = cb_access_context->GetCurrentAccessContext();
4721 assert(context);
4722
Jeremy Gebben9f537102021-10-05 16:37:12 -06004723 auto src_image = Get<IMAGE_STATE>(srcImage);
4724 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004725
4726 for (uint32_t region = 0; region < regionCount; region++) {
4727 const auto &blit_region = pRegions[region];
4728 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004729 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4730 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4731 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4732 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4733 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4734 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004735 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004736 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004737 }
4738 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004739 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4740 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4741 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4742 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4743 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4744 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004745 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004746 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004747 }
4748 }
4749}
locke-lunarg36ba2592020-04-03 09:42:04 -06004750
Jeff Leger178b1e52020-10-05 12:22:23 -04004751void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4752 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4753 const VkImageBlit *pRegions, VkFilter filter) {
4754 auto *cb_access_context = GetAccessContext(commandBuffer);
4755 assert(cb_access_context);
4756 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4757 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4758 pRegions, filter);
4759 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4760}
4761
4762void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4763 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4764 auto *cb_access_context = GetAccessContext(commandBuffer);
4765 assert(cb_access_context);
4766 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4767 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4768 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4769 pBlitImageInfo->filter, tag);
4770}
4771
Tony-LunarG542ae912021-11-04 16:06:44 -06004772void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4773 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4774 auto *cb_access_context = GetAccessContext(commandBuffer);
4775 assert(cb_access_context);
4776 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4777 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4778 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4779 pBlitImageInfo->filter, tag);
4780}
4781
John Zulauffaea0ee2021-01-14 14:01:32 -07004782bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4783 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4784 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4785 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004786 bool skip = false;
4787 if (drawCount == 0) return skip;
4788
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004789 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004790 VkDeviceSize size = struct_size;
4791 if (drawCount == 1 || stride == size) {
4792 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004793 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004794 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4795 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004796 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004797 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004798 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004799 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004800 }
4801 } else {
4802 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004803 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004804 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4805 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004806 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004807 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4808 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004809 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004810 break;
4811 }
4812 }
4813 }
4814 return skip;
4815}
4816
John Zulauf14940722021-04-12 15:19:02 -06004817void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004818 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4819 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004820 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004821 VkDeviceSize size = struct_size;
4822 if (drawCount == 1 || stride == size) {
4823 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004824 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004825 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004826 } else {
4827 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004828 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004829 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4830 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004831 }
4832 }
4833}
4834
John Zulauffaea0ee2021-01-14 14:01:32 -07004835bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4836 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4837 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004838 bool skip = false;
4839
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004840 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004841 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004842 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4843 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004844 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004845 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004846 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004847 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004848 }
4849 return skip;
4850}
4851
John Zulauf14940722021-04-12 15:19:02 -06004852void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004853 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004854 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004855 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004856}
4857
locke-lunarg36ba2592020-04-03 09:42:04 -06004858bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004859 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004860 const auto *cb_access_context = GetAccessContext(commandBuffer);
4861 assert(cb_access_context);
4862 if (!cb_access_context) return skip;
4863
locke-lunarg61870c22020-06-09 14:51:50 -06004864 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004865 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004866}
4867
4868void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004869 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004870 auto *cb_access_context = GetAccessContext(commandBuffer);
4871 assert(cb_access_context);
4872 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004873
locke-lunarg61870c22020-06-09 14:51:50 -06004874 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004875}
locke-lunarge1a67022020-04-29 00:15:36 -06004876
4877bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004878 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004879 const auto *cb_access_context = GetAccessContext(commandBuffer);
4880 assert(cb_access_context);
4881 if (!cb_access_context) return skip;
4882
4883 const auto *context = cb_access_context->GetCurrentAccessContext();
4884 assert(context);
4885 if (!context) return skip;
4886
locke-lunarg61870c22020-06-09 14:51:50 -06004887 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004888 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4889 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004890 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004891}
4892
4893void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004894 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004895 auto *cb_access_context = GetAccessContext(commandBuffer);
4896 assert(cb_access_context);
4897 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4898 auto *context = cb_access_context->GetCurrentAccessContext();
4899 assert(context);
4900
locke-lunarg61870c22020-06-09 14:51:50 -06004901 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4902 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004903}
4904
4905bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4906 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004907 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004908 const auto *cb_access_context = GetAccessContext(commandBuffer);
4909 assert(cb_access_context);
4910 if (!cb_access_context) return skip;
4911
locke-lunarg61870c22020-06-09 14:51:50 -06004912 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4913 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4914 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004915 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004916}
4917
4918void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4919 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004920 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004921 auto *cb_access_context = GetAccessContext(commandBuffer);
4922 assert(cb_access_context);
4923 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004924
locke-lunarg61870c22020-06-09 14:51:50 -06004925 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4926 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4927 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004928}
4929
4930bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4931 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004932 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004933 const auto *cb_access_context = GetAccessContext(commandBuffer);
4934 assert(cb_access_context);
4935 if (!cb_access_context) return skip;
4936
locke-lunarg61870c22020-06-09 14:51:50 -06004937 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4938 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4939 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004940 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004941}
4942
4943void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4944 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004945 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004946 auto *cb_access_context = GetAccessContext(commandBuffer);
4947 assert(cb_access_context);
4948 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004949
locke-lunarg61870c22020-06-09 14:51:50 -06004950 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4951 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4952 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004953}
4954
4955bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4956 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004957 bool skip = false;
4958 if (drawCount == 0) return skip;
4959
locke-lunargff255f92020-05-13 18:53:52 -06004960 const auto *cb_access_context = GetAccessContext(commandBuffer);
4961 assert(cb_access_context);
4962 if (!cb_access_context) return skip;
4963
4964 const auto *context = cb_access_context->GetCurrentAccessContext();
4965 assert(context);
4966 if (!context) return skip;
4967
locke-lunarg61870c22020-06-09 14:51:50 -06004968 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4969 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004970 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4971 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004972
4973 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4974 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4975 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004976 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004977 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004978}
4979
4980void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4981 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004982 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004983 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06004984 auto *cb_access_context = GetAccessContext(commandBuffer);
4985 assert(cb_access_context);
4986 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
4987 auto *context = cb_access_context->GetCurrentAccessContext();
4988 assert(context);
4989
locke-lunarg61870c22020-06-09 14:51:50 -06004990 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4991 cb_access_context->RecordDrawSubpassAttachment(tag);
4992 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06004993
4994 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
4995 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4996 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004997 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004998}
4999
5000bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5001 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005002 bool skip = false;
5003 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005004 const auto *cb_access_context = GetAccessContext(commandBuffer);
5005 assert(cb_access_context);
5006 if (!cb_access_context) return skip;
5007
5008 const auto *context = cb_access_context->GetCurrentAccessContext();
5009 assert(context);
5010 if (!context) return skip;
5011
locke-lunarg61870c22020-06-09 14:51:50 -06005012 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
5013 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07005014 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
5015 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005016
5017 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5018 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5019 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005020 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005021 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005022}
5023
5024void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5025 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005026 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005027 auto *cb_access_context = GetAccessContext(commandBuffer);
5028 assert(cb_access_context);
5029 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5030 auto *context = cb_access_context->GetCurrentAccessContext();
5031 assert(context);
5032
locke-lunarg61870c22020-06-09 14:51:50 -06005033 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5034 cb_access_context->RecordDrawSubpassAttachment(tag);
5035 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005036
5037 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5038 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5039 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005040 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005041}
5042
5043bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5044 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5045 uint32_t stride, const char *function) const {
5046 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005047 const auto *cb_access_context = GetAccessContext(commandBuffer);
5048 assert(cb_access_context);
5049 if (!cb_access_context) return skip;
5050
5051 const auto *context = cb_access_context->GetCurrentAccessContext();
5052 assert(context);
5053 if (!context) return skip;
5054
locke-lunarg61870c22020-06-09 14:51:50 -06005055 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
5056 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07005057 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
5058 maxDrawCount, stride, function);
5059 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06005060
5061 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5062 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5063 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005064 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06005065 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005066}
5067
5068bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5069 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5070 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005071 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5072 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06005073}
5074
sfricke-samsung85584a72021-09-30 21:43:38 -07005075void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5076 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5077 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005078 auto *cb_access_context = GetAccessContext(commandBuffer);
5079 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005080 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005081 auto *context = cb_access_context->GetCurrentAccessContext();
5082 assert(context);
5083
locke-lunarg61870c22020-06-09 14:51:50 -06005084 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5085 cb_access_context->RecordDrawSubpassAttachment(tag);
5086 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5087 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005088
5089 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5090 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5091 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005092 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005093}
5094
sfricke-samsung85584a72021-09-30 21:43:38 -07005095void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5096 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5097 uint32_t stride) {
5098 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5099 stride);
5100 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5101 CMD_DRAWINDIRECTCOUNT);
5102}
locke-lunarge1a67022020-04-29 00:15:36 -06005103bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5104 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5105 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005106 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5107 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06005108}
5109
5110void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5111 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5112 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005113 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5114 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005115 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5116 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005117}
5118
5119bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5120 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5121 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005122 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5123 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06005124}
5125
5126void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5127 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5128 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005129 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5130 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005131 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5132 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005133}
5134
5135bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5136 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5137 uint32_t stride, const char *function) const {
5138 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005139 const auto *cb_access_context = GetAccessContext(commandBuffer);
5140 assert(cb_access_context);
5141 if (!cb_access_context) return skip;
5142
5143 const auto *context = cb_access_context->GetCurrentAccessContext();
5144 assert(context);
5145 if (!context) return skip;
5146
locke-lunarg61870c22020-06-09 14:51:50 -06005147 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
5148 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07005149 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
5150 offset, maxDrawCount, stride, function);
5151 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06005152
5153 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5154 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5155 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005156 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06005157 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005158}
5159
5160bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5161 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5162 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005163 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5164 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06005165}
5166
sfricke-samsung85584a72021-09-30 21:43:38 -07005167void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5168 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5169 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005170 auto *cb_access_context = GetAccessContext(commandBuffer);
5171 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005172 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005173 auto *context = cb_access_context->GetCurrentAccessContext();
5174 assert(context);
5175
locke-lunarg61870c22020-06-09 14:51:50 -06005176 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5177 cb_access_context->RecordDrawSubpassAttachment(tag);
5178 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5179 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005180
5181 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5182 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005183 // We will update the index and vertex buffer in SubmitQueue in the future.
5184 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005185}
5186
sfricke-samsung85584a72021-09-30 21:43:38 -07005187void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5188 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5189 uint32_t maxDrawCount, uint32_t stride) {
5190 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5191 maxDrawCount, stride);
5192 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5193 CMD_DRAWINDEXEDINDIRECTCOUNT);
5194}
5195
locke-lunarge1a67022020-04-29 00:15:36 -06005196bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5197 VkDeviceSize offset, VkBuffer countBuffer,
5198 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5199 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005200 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5201 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06005202}
5203
5204void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5205 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5206 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005207 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5208 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005209 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5210 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005211}
5212
5213bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5214 VkDeviceSize offset, VkBuffer countBuffer,
5215 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5216 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005217 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5218 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06005219}
5220
5221void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5222 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5223 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005224 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5225 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005226 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5227 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005228}
5229
5230bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5231 const VkClearColorValue *pColor, uint32_t rangeCount,
5232 const VkImageSubresourceRange *pRanges) const {
5233 bool skip = false;
5234 const auto *cb_access_context = GetAccessContext(commandBuffer);
5235 assert(cb_access_context);
5236 if (!cb_access_context) return skip;
5237
5238 const auto *context = cb_access_context->GetCurrentAccessContext();
5239 assert(context);
5240 if (!context) return skip;
5241
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005242 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005243
5244 for (uint32_t index = 0; index < rangeCount; index++) {
5245 const auto &range = pRanges[index];
5246 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005247 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005248 if (hazard.hazard) {
5249 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005250 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005251 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005252 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005253 }
5254 }
5255 }
5256 return skip;
5257}
5258
5259void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5260 const VkClearColorValue *pColor, uint32_t rangeCount,
5261 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005262 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005263 auto *cb_access_context = GetAccessContext(commandBuffer);
5264 assert(cb_access_context);
5265 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5266 auto *context = cb_access_context->GetCurrentAccessContext();
5267 assert(context);
5268
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005269 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005270
5271 for (uint32_t index = 0; index < rangeCount; index++) {
5272 const auto &range = pRanges[index];
5273 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005274 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005275 }
5276 }
5277}
5278
5279bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5280 VkImageLayout imageLayout,
5281 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5282 const VkImageSubresourceRange *pRanges) const {
5283 bool skip = false;
5284 const auto *cb_access_context = GetAccessContext(commandBuffer);
5285 assert(cb_access_context);
5286 if (!cb_access_context) return skip;
5287
5288 const auto *context = cb_access_context->GetCurrentAccessContext();
5289 assert(context);
5290 if (!context) return skip;
5291
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005292 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005293
5294 for (uint32_t index = 0; index < rangeCount; index++) {
5295 const auto &range = pRanges[index];
5296 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005297 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005298 if (hazard.hazard) {
5299 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005300 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005301 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005302 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005303 }
5304 }
5305 }
5306 return skip;
5307}
5308
5309void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5310 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5311 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005312 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005313 auto *cb_access_context = GetAccessContext(commandBuffer);
5314 assert(cb_access_context);
5315 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5316 auto *context = cb_access_context->GetCurrentAccessContext();
5317 assert(context);
5318
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005319 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005320
5321 for (uint32_t index = 0; index < rangeCount; index++) {
5322 const auto &range = pRanges[index];
5323 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005324 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005325 }
5326 }
5327}
5328
5329bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5330 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5331 VkDeviceSize dstOffset, VkDeviceSize stride,
5332 VkQueryResultFlags flags) const {
5333 bool skip = false;
5334 const auto *cb_access_context = GetAccessContext(commandBuffer);
5335 assert(cb_access_context);
5336 if (!cb_access_context) return skip;
5337
5338 const auto *context = cb_access_context->GetCurrentAccessContext();
5339 assert(context);
5340 if (!context) return skip;
5341
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005342 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005343
5344 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005345 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005346 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005347 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005348 skip |=
5349 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5350 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005351 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005352 }
5353 }
locke-lunargff255f92020-05-13 18:53:52 -06005354
5355 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005356 return skip;
5357}
5358
5359void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5360 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5361 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005362 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5363 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005364 auto *cb_access_context = GetAccessContext(commandBuffer);
5365 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005366 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005367 auto *context = cb_access_context->GetCurrentAccessContext();
5368 assert(context);
5369
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005370 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005371
5372 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005373 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005374 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005375 }
locke-lunargff255f92020-05-13 18:53:52 -06005376
5377 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005378}
5379
5380bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5381 VkDeviceSize size, uint32_t data) const {
5382 bool skip = false;
5383 const auto *cb_access_context = GetAccessContext(commandBuffer);
5384 assert(cb_access_context);
5385 if (!cb_access_context) return skip;
5386
5387 const auto *context = cb_access_context->GetCurrentAccessContext();
5388 assert(context);
5389 if (!context) return skip;
5390
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005391 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005392
5393 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005394 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005395 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005396 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005397 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005398 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005399 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005400 }
5401 }
5402 return skip;
5403}
5404
5405void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5406 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005407 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005408 auto *cb_access_context = GetAccessContext(commandBuffer);
5409 assert(cb_access_context);
5410 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5411 auto *context = cb_access_context->GetCurrentAccessContext();
5412 assert(context);
5413
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005414 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005415
5416 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005417 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005418 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005419 }
5420}
5421
5422bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5423 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5424 const VkImageResolve *pRegions) const {
5425 bool skip = false;
5426 const auto *cb_access_context = GetAccessContext(commandBuffer);
5427 assert(cb_access_context);
5428 if (!cb_access_context) return skip;
5429
5430 const auto *context = cb_access_context->GetCurrentAccessContext();
5431 assert(context);
5432 if (!context) return skip;
5433
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005434 auto src_image = Get<IMAGE_STATE>(srcImage);
5435 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005436
5437 for (uint32_t region = 0; region < regionCount; region++) {
5438 const auto &resolve_region = pRegions[region];
5439 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005440 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
locke-lunarge1a67022020-04-29 00:15:36 -06005441 resolve_region.srcOffset, resolve_region.extent);
5442 if (hazard.hazard) {
5443 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005444 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005445 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005446 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005447 }
5448 }
5449
5450 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005451 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
locke-lunarge1a67022020-04-29 00:15:36 -06005452 resolve_region.dstOffset, resolve_region.extent);
5453 if (hazard.hazard) {
5454 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005455 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005456 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005457 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005458 }
5459 if (skip) break;
5460 }
5461 }
5462
5463 return skip;
5464}
5465
5466void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5467 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5468 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005469 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5470 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005471 auto *cb_access_context = GetAccessContext(commandBuffer);
5472 assert(cb_access_context);
5473 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5474 auto *context = cb_access_context->GetCurrentAccessContext();
5475 assert(context);
5476
Jeremy Gebben9f537102021-10-05 16:37:12 -06005477 auto src_image = Get<IMAGE_STATE>(srcImage);
5478 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005479
5480 for (uint32_t region = 0; region < regionCount; region++) {
5481 const auto &resolve_region = pRegions[region];
5482 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005483 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005484 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005485 }
5486 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005487 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005488 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005489 }
5490 }
5491}
5492
Tony-LunarG562fc102021-11-12 13:58:35 -07005493bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5494 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005495 bool skip = false;
5496 const auto *cb_access_context = GetAccessContext(commandBuffer);
5497 assert(cb_access_context);
5498 if (!cb_access_context) return skip;
5499
5500 const auto *context = cb_access_context->GetCurrentAccessContext();
5501 assert(context);
5502 if (!context) return skip;
5503
Tony-LunarG562fc102021-11-12 13:58:35 -07005504 const char *func_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005505 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5506 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005507
5508 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5509 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5510 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005511 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Jeff Leger178b1e52020-10-05 12:22:23 -04005512 resolve_region.srcOffset, resolve_region.extent);
5513 if (hazard.hazard) {
5514 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
Tony-LunarG562fc102021-11-12 13:58:35 -07005515 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04005516 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005517 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005518 }
5519 }
5520
5521 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005522 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Jeff Leger178b1e52020-10-05 12:22:23 -04005523 resolve_region.dstOffset, resolve_region.extent);
5524 if (hazard.hazard) {
5525 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
Tony-LunarG562fc102021-11-12 13:58:35 -07005526 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04005527 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005528 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005529 }
5530 if (skip) break;
5531 }
5532 }
5533
5534 return skip;
5535}
5536
Tony-LunarG562fc102021-11-12 13:58:35 -07005537bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5538 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5539 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5540}
5541
5542bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5543 const VkResolveImageInfo2 *pResolveImageInfo) const {
5544 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5545}
5546
5547void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5548 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005549 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5550 auto *cb_access_context = GetAccessContext(commandBuffer);
5551 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005552 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005553 auto *context = cb_access_context->GetCurrentAccessContext();
5554 assert(context);
5555
Jeremy Gebben9f537102021-10-05 16:37:12 -06005556 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5557 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005558
5559 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5560 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5561 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005562 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005563 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005564 }
5565 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005566 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005567 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005568 }
5569 }
5570}
5571
Tony-LunarG562fc102021-11-12 13:58:35 -07005572void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5573 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5574 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5575}
5576
5577void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5578 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5579}
5580
locke-lunarge1a67022020-04-29 00:15:36 -06005581bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5582 VkDeviceSize dataSize, const void *pData) const {
5583 bool skip = false;
5584 const auto *cb_access_context = GetAccessContext(commandBuffer);
5585 assert(cb_access_context);
5586 if (!cb_access_context) return skip;
5587
5588 const auto *context = cb_access_context->GetCurrentAccessContext();
5589 assert(context);
5590 if (!context) return skip;
5591
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005592 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005593
5594 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005595 // VK_WHOLE_SIZE not allowed
5596 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005597 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005598 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005599 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005600 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005601 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005602 }
5603 }
5604 return skip;
5605}
5606
5607void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5608 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005609 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005610 auto *cb_access_context = GetAccessContext(commandBuffer);
5611 assert(cb_access_context);
5612 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5613 auto *context = cb_access_context->GetCurrentAccessContext();
5614 assert(context);
5615
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005616 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005617
5618 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005619 // VK_WHOLE_SIZE not allowed
5620 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005621 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005622 }
5623}
locke-lunargff255f92020-05-13 18:53:52 -06005624
5625bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5626 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5627 bool skip = false;
5628 const auto *cb_access_context = GetAccessContext(commandBuffer);
5629 assert(cb_access_context);
5630 if (!cb_access_context) return skip;
5631
5632 const auto *context = cb_access_context->GetCurrentAccessContext();
5633 assert(context);
5634 if (!context) return skip;
5635
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005636 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005637
5638 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005639 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005640 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005641 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005642 skip |=
5643 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5644 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005645 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005646 }
5647 }
5648 return skip;
5649}
5650
5651void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5652 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005653 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005654 auto *cb_access_context = GetAccessContext(commandBuffer);
5655 assert(cb_access_context);
5656 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5657 auto *context = cb_access_context->GetCurrentAccessContext();
5658 assert(context);
5659
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005660 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005661
5662 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005663 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005664 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005665 }
5666}
John Zulauf49beb112020-11-04 16:06:31 -07005667
5668bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5669 bool skip = false;
5670 const auto *cb_context = GetAccessContext(commandBuffer);
5671 assert(cb_context);
5672 if (!cb_context) return skip;
5673
John Zulauf36ef9282021-02-02 11:47:24 -07005674 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005675 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005676}
5677
5678void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5679 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5680 auto *cb_context = GetAccessContext(commandBuffer);
5681 assert(cb_context);
5682 if (!cb_context) return;
John Zulauf1bf30522021-09-03 15:39:06 -06005683 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005684}
5685
John Zulauf4edde622021-02-15 08:54:50 -07005686bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5687 const VkDependencyInfoKHR *pDependencyInfo) const {
5688 bool skip = false;
5689 const auto *cb_context = GetAccessContext(commandBuffer);
5690 assert(cb_context);
5691 if (!cb_context || !pDependencyInfo) return skip;
5692
5693 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5694 return set_event_op.Validate(*cb_context);
5695}
5696
Tony-LunarGc43525f2021-11-15 16:12:38 -07005697bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5698 const VkDependencyInfo *pDependencyInfo) const {
5699 bool skip = false;
5700 const auto *cb_context = GetAccessContext(commandBuffer);
5701 assert(cb_context);
5702 if (!cb_context || !pDependencyInfo) return skip;
5703
5704 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5705 return set_event_op.Validate(*cb_context);
5706}
5707
John Zulauf4edde622021-02-15 08:54:50 -07005708void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5709 const VkDependencyInfoKHR *pDependencyInfo) {
5710 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5711 auto *cb_context = GetAccessContext(commandBuffer);
5712 assert(cb_context);
5713 if (!cb_context || !pDependencyInfo) return;
5714
John Zulauf1bf30522021-09-03 15:39:06 -06005715 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
John Zulauf4edde622021-02-15 08:54:50 -07005716}
5717
Tony-LunarGc43525f2021-11-15 16:12:38 -07005718void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5719 const VkDependencyInfo *pDependencyInfo) {
5720 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5721 auto *cb_context = GetAccessContext(commandBuffer);
5722 assert(cb_context);
5723 if (!cb_context || !pDependencyInfo) return;
5724
5725 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5726}
5727
John Zulauf49beb112020-11-04 16:06:31 -07005728bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5729 VkPipelineStageFlags stageMask) const {
5730 bool skip = false;
5731 const auto *cb_context = GetAccessContext(commandBuffer);
5732 assert(cb_context);
5733 if (!cb_context) return skip;
5734
John Zulauf36ef9282021-02-02 11:47:24 -07005735 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005736 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005737}
5738
5739void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5740 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5741 auto *cb_context = GetAccessContext(commandBuffer);
5742 assert(cb_context);
5743 if (!cb_context) return;
5744
John Zulauf1bf30522021-09-03 15:39:06 -06005745 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005746}
5747
John Zulauf4edde622021-02-15 08:54:50 -07005748bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5749 VkPipelineStageFlags2KHR stageMask) const {
5750 bool skip = false;
5751 const auto *cb_context = GetAccessContext(commandBuffer);
5752 assert(cb_context);
5753 if (!cb_context) return skip;
5754
5755 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5756 return reset_event_op.Validate(*cb_context);
5757}
5758
Tony-LunarGa2662db2021-11-16 07:26:24 -07005759bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5760 VkPipelineStageFlags2 stageMask) const {
5761 bool skip = false;
5762 const auto *cb_context = GetAccessContext(commandBuffer);
5763 assert(cb_context);
5764 if (!cb_context) return skip;
5765
5766 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5767 return reset_event_op.Validate(*cb_context);
5768}
5769
John Zulauf4edde622021-02-15 08:54:50 -07005770void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5771 VkPipelineStageFlags2KHR stageMask) {
5772 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5773 auto *cb_context = GetAccessContext(commandBuffer);
5774 assert(cb_context);
5775 if (!cb_context) return;
5776
John Zulauf1bf30522021-09-03 15:39:06 -06005777 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005778}
5779
Tony-LunarGa2662db2021-11-16 07:26:24 -07005780void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5781 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5782 auto *cb_context = GetAccessContext(commandBuffer);
5783 assert(cb_context);
5784 if (!cb_context) return;
5785
5786 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5787}
5788
John Zulauf49beb112020-11-04 16:06:31 -07005789bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5790 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5791 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5792 uint32_t bufferMemoryBarrierCount,
5793 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5794 uint32_t imageMemoryBarrierCount,
5795 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5796 bool skip = false;
5797 const auto *cb_context = GetAccessContext(commandBuffer);
5798 assert(cb_context);
5799 if (!cb_context) return skip;
5800
John Zulauf36ef9282021-02-02 11:47:24 -07005801 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5802 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5803 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005804 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005805}
5806
5807void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5808 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5809 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5810 uint32_t bufferMemoryBarrierCount,
5811 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5812 uint32_t imageMemoryBarrierCount,
5813 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5814 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5815 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5816 imageMemoryBarrierCount, pImageMemoryBarriers);
5817
5818 auto *cb_context = GetAccessContext(commandBuffer);
5819 assert(cb_context);
5820 if (!cb_context) return;
5821
John Zulauf1bf30522021-09-03 15:39:06 -06005822 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005823 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005824 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005825}
5826
John Zulauf4edde622021-02-15 08:54:50 -07005827bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5828 const VkDependencyInfoKHR *pDependencyInfos) const {
5829 bool skip = false;
5830 const auto *cb_context = GetAccessContext(commandBuffer);
5831 assert(cb_context);
5832 if (!cb_context) return skip;
5833
5834 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5835 skip |= wait_events_op.Validate(*cb_context);
5836 return skip;
5837}
5838
5839void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5840 const VkDependencyInfoKHR *pDependencyInfos) {
5841 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5842
5843 auto *cb_context = GetAccessContext(commandBuffer);
5844 assert(cb_context);
5845 if (!cb_context) return;
5846
John Zulauf1bf30522021-09-03 15:39:06 -06005847 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5848 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07005849}
5850
Tony-LunarG1364cf52021-11-17 16:10:11 -07005851bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5852 const VkDependencyInfo *pDependencyInfos) const {
5853 bool skip = false;
5854 const auto *cb_context = GetAccessContext(commandBuffer);
5855 assert(cb_context);
5856 if (!cb_context) return skip;
5857
5858 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5859 skip |= wait_events_op.Validate(*cb_context);
5860 return skip;
5861}
5862
5863void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5864 const VkDependencyInfo *pDependencyInfos) {
5865 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5866
5867 auto *cb_context = GetAccessContext(commandBuffer);
5868 assert(cb_context);
5869 if (!cb_context) return;
5870
5871 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5872 pDependencyInfos);
5873}
5874
John Zulauf4a6105a2020-11-17 15:11:05 -07005875void SyncEventState::ResetFirstScope() {
5876 for (const auto address_type : kAddressTypes) {
5877 first_scope[static_cast<size_t>(address_type)].clear();
5878 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005879 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06005880 first_scope_set = false;
5881 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07005882}
5883
5884// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
John Zulauf4edde622021-02-15 08:54:50 -07005885SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005886 IgnoreReason reason = NotIgnored;
5887
Tony-LunarG1364cf52021-11-17 16:10:11 -07005888 if ((CMD_WAITEVENTS2KHR == cmd || CMD_WAITEVENTS2 == cmd) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07005889 reason = SetVsWait2;
5890 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
5891 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07005892 } else if (unsynchronized_set) {
5893 reason = SetRace;
John Zulauf78b1f892021-09-20 15:02:09 -06005894 } else if (first_scope_set) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005895 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005896 if (missing_bits) reason = MissingStageBits;
5897 }
5898
5899 return reason;
5900}
5901
Jeremy Gebben40a22942020-12-22 14:22:06 -07005902bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005903 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5904 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5905 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005906}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005907
John Zulaufbb890452021-12-14 11:30:18 -07005908void SyncOpBase::SetReplayContext(uint32_t subpass, ReplayContextPtr &&replay) {
5909 subpass_ = subpass;
5910 replay_context_ = std::move(replay);
5911}
5912
5913const ReplayTrackbackBarriersAction *SyncOpBase::GetReplayTrackback() const {
5914 if (replay_context_) {
5915 assert(subpass_ < replay_context_->subpass_contexts.size());
5916 return &replay_context_->subpass_contexts[subpass_];
5917 }
5918 return nullptr;
5919}
5920
John Zulauf36ef9282021-02-02 11:47:24 -07005921SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
5922 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5923 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005924 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5925 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5926 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf4edde622021-02-15 08:54:50 -07005927 : SyncOpBase(cmd), barriers_(1) {
5928 auto &barrier_set = barriers_[0];
5929 barrier_set.dependency_flags = dependencyFlags;
5930 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
5931 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005932 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07005933 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
5934 pMemoryBarriers);
5935 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5936 bufferMemoryBarrierCount, pBufferMemoryBarriers);
5937 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5938 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005939}
5940
John Zulauf4edde622021-02-15 08:54:50 -07005941SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
5942 const VkDependencyInfoKHR *dep_infos)
5943 : SyncOpBase(cmd), barriers_(event_count) {
5944 for (uint32_t i = 0; i < event_count; i++) {
5945 const auto &dep_info = dep_infos[i];
5946 auto &barrier_set = barriers_[i];
5947 barrier_set.dependency_flags = dep_info.dependencyFlags;
5948 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
5949 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
5950 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
5951 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5952 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
5953 dep_info.pMemoryBarriers);
5954 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
5955 dep_info.pBufferMemoryBarriers);
5956 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
5957 dep_info.pImageMemoryBarriers);
5958 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005959}
5960
John Zulauf36ef9282021-02-02 11:47:24 -07005961SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07005962 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5963 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5964 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5965 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5966 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf36ef9282021-02-02 11:47:24 -07005967 : SyncOpBarriers(cmd, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
John Zulaufd5115702021-01-18 12:34:33 -07005968 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5969
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005970SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
5971 const VkDependencyInfoKHR &dep_info)
John Zulauf4edde622021-02-15 08:54:50 -07005972 : SyncOpBarriers(cmd, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005973
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005974bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
5975 bool skip = false;
5976 const auto *context = cb_context.GetCurrentAccessContext();
5977 assert(context);
5978 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07005979 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
5980
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005981 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07005982 const auto &barrier_set = barriers_[0];
5983 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
5984 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
5985 const auto *image_state = image_barrier.image.get();
5986 if (!image_state) continue;
5987 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
5988 if (hazard.hazard) {
5989 // PHASE1 TODO -- add tag information to log msg when useful.
5990 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005991 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07005992 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
5993 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
5994 string_SyncHazard(hazard.hazard), image_barrier.index,
5995 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005996 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005997 }
5998 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005999 return skip;
6000}
6001
John Zulaufd5115702021-01-18 12:34:33 -07006002struct SyncOpPipelineBarrierFunctorFactory {
6003 using BarrierOpFunctor = PipelineBarrierOp;
6004 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6005 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6006 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6007 using BufferRange = ResourceAccessRange;
6008 using ImageRange = subresource_adapter::ImageRangeGenerator;
6009 using GlobalRange = ResourceAccessRange;
6010
6011 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier, bool layout_transition) const {
6012 return ApplyFunctor(BarrierOpFunctor(barrier, layout_transition));
6013 }
John Zulauf14940722021-04-12 15:19:02 -06006014 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006015 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6016 }
6017 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier) const {
6018 return GlobalBarrierOpFunctor(barrier, false);
6019 }
6020
6021 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6022 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6023 const auto base_address = ResourceBaseAddress(buffer);
6024 return (range + base_address);
6025 }
John Zulauf110413c2021-03-20 05:38:38 -06006026 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006027 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006028
6029 const auto base_address = ResourceBaseAddress(image);
John Zulauf110413c2021-03-20 05:38:38 -06006030 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
John Zulaufd5115702021-01-18 12:34:33 -07006031 return range_gen;
6032 }
6033 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6034};
6035
6036template <typename Barriers, typename FunctorFactory>
John Zulauf14940722021-04-12 15:19:02 -06006037void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag tag,
John Zulaufd5115702021-01-18 12:34:33 -07006038 AccessContext *context) {
6039 for (const auto &barrier : barriers) {
6040 const auto *state = barrier.GetState();
6041 if (state) {
6042 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
6043 auto update_action = factory.MakeApplyFunctor(barrier.barrier, barrier.IsLayoutTransition());
6044 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6045 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6046 }
6047 }
6048}
6049
6050template <typename Barriers, typename FunctorFactory>
John Zulauf14940722021-04-12 15:19:02 -06006051void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const ResourceUsageTag tag,
John Zulaufd5115702021-01-18 12:34:33 -07006052 AccessContext *access_context) {
6053 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6054 for (const auto &barrier : barriers) {
6055 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(barrier));
6056 }
6057 for (const auto address_type : kAddressTypes) {
6058 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6059 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6060 }
6061}
6062
John Zulauf8eda1562021-04-13 17:06:41 -06006063ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006064 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf8eda1562021-04-13 17:06:41 -06006065 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf36ef9282021-02-02 11:47:24 -07006066 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulaufbb890452021-12-14 11:30:18 -07006067 ReplayRecord(tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006068 return tag;
6069}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006070
John Zulaufbb890452021-12-14 11:30:18 -07006071void SyncOpPipelineBarrier::ReplayRecord(const ResourceUsageTag tag, AccessContext *access_context,
6072 SyncEventsContext *events_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006073 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006074 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6075 assert(barriers_.size() == 1);
6076 const auto &barrier_set = barriers_[0];
6077 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, tag, access_context);
6078 ApplyBarriers(barrier_set.image_memory_barriers, factory, tag, access_context);
6079 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006080 if (barrier_set.single_exec_scope) {
John Zulauf8eda1562021-04-13 17:06:41 -06006081 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006082 } else {
6083 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulauf8eda1562021-04-13 17:06:41 -06006084 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006085 }
6086 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006087}
6088
John Zulauf8eda1562021-04-13 17:06:41 -06006089bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006090 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006091 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6092 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006093 return false;
6094}
6095
John Zulauf4edde622021-02-15 08:54:50 -07006096void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6097 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6098 const VkMemoryBarrier *barriers) {
6099 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006100 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006101 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006102 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006103 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006104 }
6105 if (0 == memory_barrier_count) {
6106 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006107 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006108 }
John Zulauf4edde622021-02-15 08:54:50 -07006109 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006110}
6111
John Zulauf4edde622021-02-15 08:54:50 -07006112void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6113 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6114 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6115 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006116 for (uint32_t index = 0; index < barrier_count; index++) {
6117 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006118 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006119 if (buffer) {
6120 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6121 const auto range = MakeRange(barrier.offset, barrier_size);
6122 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006123 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006124 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006125 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006126 }
6127 }
6128}
6129
John Zulauf4edde622021-02-15 08:54:50 -07006130void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006131 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006132 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006133 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006134 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006135 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6136 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6137 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006138 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006139 }
John Zulauf4edde622021-02-15 08:54:50 -07006140 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006141}
6142
John Zulauf4edde622021-02-15 08:54:50 -07006143void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6144 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006145 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006146 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006147 for (uint32_t index = 0; index < barrier_count; index++) {
6148 const auto &barrier = barriers[index];
6149 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6150 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006151 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006152 if (buffer) {
6153 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6154 const auto range = MakeRange(barrier.offset, barrier_size);
6155 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006156 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006157 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006158 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006159 }
6160 }
6161}
6162
John Zulauf4edde622021-02-15 08:54:50 -07006163void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6164 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6165 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6166 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006167 for (uint32_t index = 0; index < barrier_count; index++) {
6168 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006169 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006170 if (image) {
6171 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6172 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006173 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006174 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006175 image_memory_barriers.emplace_back();
6176 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006177 }
6178 }
6179}
John Zulaufd5115702021-01-18 12:34:33 -07006180
John Zulauf4edde622021-02-15 08:54:50 -07006181void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6182 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006183 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006184 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006185 for (uint32_t index = 0; index < barrier_count; index++) {
6186 const auto &barrier = barriers[index];
6187 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6188 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006189 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006190 if (image) {
6191 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6192 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006193 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006194 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006195 image_memory_barriers.emplace_back();
6196 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006197 }
6198 }
6199}
6200
John Zulauf36ef9282021-02-02 11:47:24 -07006201SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
John Zulaufd5115702021-01-18 12:34:33 -07006202 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6203 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6204 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6205 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf36ef9282021-02-02 11:47:24 -07006206 : SyncOpBarriers(cmd, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006207 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6208 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006209 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006210}
6211
John Zulauf4edde622021-02-15 08:54:50 -07006212SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
6213 const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6214 : SyncOpBarriers(cmd, sync_state, queue_flags, eventCount, pDependencyInfo) {
6215 MakeEventsList(sync_state, eventCount, pEvents);
6216 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6217}
6218
John Zulauf610e28c2021-08-03 17:46:23 -06006219const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6220
John Zulaufd5115702021-01-18 12:34:33 -07006221bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006222 bool skip = false;
6223 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006224 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006225
John Zulauf610e28c2021-08-03 17:46:23 -06006226 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006227 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6228 const auto &barrier_set = barriers_[barrier_set_index];
6229 if (barrier_set.single_exec_scope) {
6230 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6231 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6232 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6233 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6234 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6235 } else {
6236 const auto &barriers = barrier_set.memory_barriers;
6237 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6238 const auto &barrier = barriers[barrier_index];
6239 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6240 const std::string vuid =
6241 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6242 skip =
6243 sync_state.LogInfo(command_buffer_handle, vuid,
6244 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6245 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6246 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6247 }
6248 }
6249 }
6250 }
John Zulaufd5115702021-01-18 12:34:33 -07006251 }
6252
John Zulauf610e28c2021-08-03 17:46:23 -06006253 // The rest is common to record time and replay time.
6254 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6255 return skip;
6256}
6257
John Zulaufbb890452021-12-14 11:30:18 -07006258bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006259 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006260 const auto &sync_state = exec_context.GetSyncState();
John Zulauf610e28c2021-08-03 17:46:23 -06006261
Jeremy Gebben40a22942020-12-22 14:22:06 -07006262 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006263 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006264 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006265 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006266 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006267 size_t barrier_set_index = 0;
6268 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006269 for (const auto &event : events_) {
6270 const auto *sync_event = events_context->Get(event.get());
6271 const auto &barrier_set = barriers_[barrier_set_index];
6272 if (!sync_event) {
6273 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6274 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6275 // new validation error... wait without previously submitted set event...
6276 events_not_found = true; // Demote "extra_stage_bits" error to warning, to avoid false positives at *record time*
John Zulauf4edde622021-02-15 08:54:50 -07006277 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006278 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006279 }
John Zulauf610e28c2021-08-03 17:46:23 -06006280
6281 // For replay calls, don't revalidate "same command buffer" events
6282 if (sync_event->last_command_tag > base_tag) continue;
6283
John Zulauf78394fc2021-07-12 15:41:40 -06006284 const auto event_handle = sync_event->event->event();
6285 // TODO add "destroyed" checks
6286
John Zulauf78b1f892021-09-20 15:02:09 -06006287 if (sync_event->first_scope_set) {
6288 // Only accumulate barrier and event stages if there is a pending set in the current context
6289 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6290 event_stage_masks |= sync_event->scope.mask_param;
6291 }
6292
John Zulauf78394fc2021-07-12 15:41:40 -06006293 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006294
John Zulauf78394fc2021-07-12 15:41:40 -06006295 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_, src_exec_scope.mask_param);
6296 if (ignore_reason) {
6297 switch (ignore_reason) {
6298 case SyncEventState::ResetWaitRace:
6299 case SyncEventState::Reset2WaitRace: {
6300 // Four permuations of Reset and Wait calls...
6301 const char *vuid =
6302 (cmd_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
6303 if (ignore_reason == SyncEventState::Reset2WaitRace) {
Tony-LunarG279601c2021-11-16 10:50:51 -07006304 vuid = (cmd_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6305 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006306 }
6307 const char *const message =
6308 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6309 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6310 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006311 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006312 break;
6313 }
6314 case SyncEventState::SetRace: {
6315 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6316 // this event
6317 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6318 const char *const message =
6319 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6320 const char *const reason = "First synchronization scope is undefined.";
6321 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6322 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006323 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006324 break;
6325 }
6326 case SyncEventState::MissingStageBits: {
6327 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6328 // Issue error message that event waited for is not in wait events scope
6329 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6330 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6331 ". Bits missing from srcStageMask %s. %s";
6332 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6333 sync_state.report_data->FormatHandle(event_handle).c_str(),
6334 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006335 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006336 break;
6337 }
6338 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006339 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006340 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6341 sync_state.report_data->FormatHandle(event_handle).c_str(),
6342 CommandTypeString(sync_event->last_command));
6343 break;
6344 }
6345 default:
6346 assert(ignore_reason == SyncEventState::NotIgnored);
6347 }
6348 } else if (barrier_set.image_memory_barriers.size()) {
6349 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006350 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006351 assert(context);
6352 for (const auto &image_memory_barrier : image_memory_barriers) {
6353 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6354 const auto *image_state = image_memory_barrier.image.get();
6355 if (!image_state) continue;
6356 const auto &subresource_range = image_memory_barrier.range;
6357 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
6358 const auto hazard =
6359 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
6360 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
6361 if (hazard.hazard) {
6362 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6363 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6364 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6365 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006366 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006367 break;
6368 }
6369 }
6370 }
6371 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6372 // 03839
6373 barrier_set_index += barrier_set_incr;
6374 }
John Zulaufd5115702021-01-18 12:34:33 -07006375
6376 // Note that we can't check for HOST in pEvents as we don't track that set event type
John Zulauf4edde622021-02-15 08:54:50 -07006377 const auto extra_stage_bits = (barrier_mask_params & ~VK_PIPELINE_STAGE_2_HOST_BIT_KHR) & ~event_stage_masks;
John Zulaufd5115702021-01-18 12:34:33 -07006378 if (extra_stage_bits) {
6379 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006380 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6381 const char *const vuid =
Tony-LunarG279601c2021-11-16 10:50:51 -07006382 (CMD_WAITEVENTS == cmd_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006383 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006384 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006385 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006386 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006387 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006388 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006389 " vkCmdSetEvent may be in previously submitted command buffer.");
6390 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006391 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006392 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006393 }
6394 }
6395 return skip;
6396}
6397
6398struct SyncOpWaitEventsFunctorFactory {
6399 using BarrierOpFunctor = WaitEventBarrierOp;
6400 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6401 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6402 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6403 using BufferRange = EventSimpleRangeGenerator;
6404 using ImageRange = EventImageRangeGenerator;
6405 using GlobalRange = EventSimpleRangeGenerator;
6406
6407 // Need to restrict to only valid exec and access scope for this event
6408 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6409 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006410 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006411 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6412 return barrier;
6413 }
6414 ApplyFunctor MakeApplyFunctor(const SyncBarrier &barrier_arg, bool layout_transition) const {
6415 auto barrier = RestrictToEvent(barrier_arg);
6416 return ApplyFunctor(BarrierOpFunctor(sync_event->first_scope_tag, barrier, layout_transition));
6417 }
John Zulauf14940722021-04-12 15:19:02 -06006418 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006419 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6420 }
6421 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const SyncBarrier &barrier_arg) const {
6422 auto barrier = RestrictToEvent(barrier_arg);
6423 return GlobalBarrierOpFunctor(sync_event->first_scope_tag, barrier, false);
6424 }
6425
6426 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6427 const AccessAddressType address_type = GetAccessAddressType(buffer);
6428 const auto base_address = ResourceBaseAddress(buffer);
6429 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6430 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6431 return filtered_range_gen;
6432 }
John Zulauf110413c2021-03-20 05:38:38 -06006433 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006434 if (!SimpleBinding(image)) return ImageRange();
6435 const auto address_type = GetAccessAddressType(image);
6436 const auto base_address = ResourceBaseAddress(image);
John Zulauf110413c2021-03-20 05:38:38 -06006437 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
John Zulaufd5115702021-01-18 12:34:33 -07006438 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6439
6440 return filtered_range_gen;
6441 }
6442 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6443 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6444 }
6445 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6446 SyncEventState *sync_event;
6447};
6448
John Zulauf8eda1562021-04-13 17:06:41 -06006449ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf36ef9282021-02-02 11:47:24 -07006450 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulaufd5115702021-01-18 12:34:33 -07006451 auto *access_context = cb_context->GetCurrentAccessContext();
6452 assert(access_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006453 if (!access_context) return tag;
John Zulauf669dfd52021-01-27 17:15:28 -07006454 auto *events_context = cb_context->GetCurrentEventsContext();
6455 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006456 if (!events_context) return tag;
John Zulaufd5115702021-01-18 12:34:33 -07006457
John Zulaufbb890452021-12-14 11:30:18 -07006458 ReplayRecord(tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006459 return tag;
6460}
6461
John Zulaufbb890452021-12-14 11:30:18 -07006462void SyncOpWaitEvents::ReplayRecord(ResourceUsageTag tag, AccessContext *access_context, SyncEventsContext *events_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006463 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6464 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6465 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
6466 access_context->ResolvePreviousAccesses();
6467
John Zulauf4edde622021-02-15 08:54:50 -07006468 size_t barrier_set_index = 0;
6469 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6470 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006471 for (auto &event_shared : events_) {
6472 if (!event_shared.get()) continue;
6473 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006474
John Zulauf4edde622021-02-15 08:54:50 -07006475 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006476 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006477
John Zulauf4edde622021-02-15 08:54:50 -07006478 const auto &barrier_set = barriers_[barrier_set_index];
6479 const auto &dst = barrier_set.dst_exec_scope;
6480 if (!sync_event->IsIgnoredByWait(cmd_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006481 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6482 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6483 // of the barriers is maintained.
6484 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf4edde622021-02-15 08:54:50 -07006485 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, tag, access_context);
6486 ApplyBarriers(barrier_set.image_memory_barriers, factory, tag, access_context);
6487 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006488
6489 // Apply the global barrier to the event itself (for race condition tracking)
6490 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6491 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6492 sync_event->barriers |= dst.exec_scope;
6493 } else {
6494 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6495 sync_event->barriers = 0U;
6496 }
John Zulauf4edde622021-02-15 08:54:50 -07006497 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006498 }
6499
6500 // Apply the pending barriers
6501 ResolvePendingBarrierFunctor apply_pending_action(tag);
6502 access_context->ApplyToContext(apply_pending_action);
6503}
6504
John Zulauf8eda1562021-04-13 17:06:41 -06006505bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006506 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6507 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006508}
6509
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006510bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6511 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6512 bool skip = false;
6513 const auto *cb_access_context = GetAccessContext(commandBuffer);
6514 assert(cb_access_context);
6515 if (!cb_access_context) return skip;
6516
6517 const auto *context = cb_access_context->GetCurrentAccessContext();
6518 assert(context);
6519 if (!context) return skip;
6520
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006521 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006522
6523 if (dst_buffer) {
6524 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6525 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6526 if (hazard.hazard) {
6527 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6528 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6529 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006530 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006531 }
6532 }
6533 return skip;
6534}
6535
John Zulauf669dfd52021-01-27 17:15:28 -07006536void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006537 events_.reserve(event_count);
6538 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006539 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006540 }
6541}
John Zulauf6ce24372021-01-30 05:56:25 -07006542
John Zulauf36ef9282021-02-02 11:47:24 -07006543SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006544 VkPipelineStageFlags2KHR stageMask)
Jeremy Gebben9f537102021-10-05 16:37:12 -06006545 : SyncOpBase(cmd), event_(sync_state.Get<EVENT_STATE>(event)), exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006546
John Zulauf1bf30522021-09-03 15:39:06 -06006547bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6548 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6549}
6550
John Zulaufbb890452021-12-14 11:30:18 -07006551bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6552 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006553 assert(events_context);
6554 bool skip = false;
6555 if (!events_context) return skip;
6556
John Zulaufbb890452021-12-14 11:30:18 -07006557 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006558 const auto *sync_event = events_context->Get(event_);
6559 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6560
John Zulauf1bf30522021-09-03 15:39:06 -06006561 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6562
John Zulauf6ce24372021-01-30 05:56:25 -07006563 const char *const set_wait =
6564 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6565 "hazards.";
6566 const char *message = set_wait; // Only one message this call.
6567 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6568 const char *vuid = nullptr;
6569 switch (sync_event->last_command) {
6570 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006571 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006572 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006573 // Needs a barrier between set and reset
6574 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6575 break;
John Zulauf4edde622021-02-15 08:54:50 -07006576 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006577 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006578 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006579 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6580 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6581 break;
6582 }
6583 default:
6584 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006585 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6586 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006587 break;
6588 }
6589 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006590 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6591 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006592 CommandTypeString(sync_event->last_command));
6593 }
6594 }
6595 return skip;
6596}
6597
John Zulauf8eda1562021-04-13 17:06:41 -06006598ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
6599 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf6ce24372021-01-30 05:56:25 -07006600 auto *events_context = cb_context->GetCurrentEventsContext();
6601 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006602 if (!events_context) return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006603
6604 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf8eda1562021-04-13 17:06:41 -06006605 if (!sync_event) return tag; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006606
6607 // Update the event state
John Zulauf36ef9282021-02-02 11:47:24 -07006608 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006609 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006610 sync_event->unsynchronized_set = CMD_NONE;
6611 sync_event->ResetFirstScope();
6612 sync_event->barriers = 0U;
John Zulauf8eda1562021-04-13 17:06:41 -06006613
6614 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006615}
6616
John Zulauf8eda1562021-04-13 17:06:41 -06006617bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006618 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6619 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006620}
6621
John Zulaufbb890452021-12-14 11:30:18 -07006622void SyncOpResetEvent::ReplayRecord(ResourceUsageTag tag, AccessContext *access_context, SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006623
John Zulauf36ef9282021-02-02 11:47:24 -07006624SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006625 VkPipelineStageFlags2KHR stageMask)
John Zulauf36ef9282021-02-02 11:47:24 -07006626 : SyncOpBase(cmd),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006627 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006628 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
6629 dep_info_() {}
6630
6631SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
6632 const VkDependencyInfoKHR &dep_info)
6633 : SyncOpBase(cmd),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006634 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006635 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
Tony-LunarG273f32f2021-09-28 08:56:30 -06006636 dep_info_(new safe_VkDependencyInfo(&dep_info)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006637
6638bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006639 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6640}
6641bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006642 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6643 assert(exec_context);
6644 return DoValidate(*exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006645}
6646
John Zulaufbb890452021-12-14 11:30:18 -07006647bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006648 bool skip = false;
6649
John Zulaufbb890452021-12-14 11:30:18 -07006650 const auto &sync_state = exec_context.GetSyncState();
6651 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006652 assert(events_context);
6653 if (!events_context) return skip;
6654
6655 const auto *sync_event = events_context->Get(event_);
6656 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6657
John Zulauf610e28c2021-08-03 17:46:23 -06006658 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6659
John Zulauf6ce24372021-01-30 05:56:25 -07006660 const char *const reset_set =
6661 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6662 "hazards.";
6663 const char *const wait =
6664 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6665
6666 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006667 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006668 const char *message = nullptr;
6669 switch (sync_event->last_command) {
6670 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006671 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006672 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006673 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006674 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006675 message = reset_set;
6676 break;
6677 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006678 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006679 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006680 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006681 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006682 message = reset_set;
6683 break;
6684 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006685 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006686 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006687 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006688 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006689 message = wait;
6690 break;
6691 default:
6692 // The only other valid last command that wasn't one.
6693 assert(sync_event->last_command == CMD_NONE);
6694 break;
6695 }
John Zulauf4edde622021-02-15 08:54:50 -07006696 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006697 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006698 std::string vuid("SYNC-");
6699 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006700 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6701 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006702 CommandTypeString(sync_event->last_command));
6703 }
6704 }
6705
6706 return skip;
6707}
6708
John Zulauf8eda1562021-04-13 17:06:41 -06006709ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf36ef9282021-02-02 11:47:24 -07006710 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf6ce24372021-01-30 05:56:25 -07006711 auto *events_context = cb_context->GetCurrentEventsContext();
6712 auto *access_context = cb_context->GetCurrentAccessContext();
6713 assert(events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006714 if (access_context && events_context) {
John Zulaufbb890452021-12-14 11:30:18 -07006715 ReplayRecord(tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006716 }
6717 return tag;
6718}
John Zulauf6ce24372021-01-30 05:56:25 -07006719
John Zulaufbb890452021-12-14 11:30:18 -07006720void SyncOpSetEvent::ReplayRecord(ResourceUsageTag tag, AccessContext *access_context, SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006721 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006722 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006723
6724 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6725 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6726 // any issues caused by naive scope setting here.
6727
6728 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6729 // Given:
6730 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6731 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6732
6733 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6734 sync_event->unsynchronized_set = sync_event->last_command;
6735 sync_event->ResetFirstScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006736 } else if (!sync_event->first_scope_set) {
John Zulauf6ce24372021-01-30 05:56:25 -07006737 // We only set the scope if there isn't one
6738 sync_event->scope = src_exec_scope_;
6739
6740 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
6741 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
6742 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
6743 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
6744 }
6745 };
6746 access_context->ForAll(set_scope);
6747 sync_event->unsynchronized_set = CMD_NONE;
John Zulauf78b1f892021-09-20 15:02:09 -06006748 sync_event->first_scope_set = true;
John Zulauf6ce24372021-01-30 05:56:25 -07006749 sync_event->first_scope_tag = tag;
6750 }
John Zulauf4edde622021-02-15 08:54:50 -07006751 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
6752 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006753 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006754 sync_event->barriers = 0U;
6755}
John Zulauf64ffe552021-02-06 10:25:07 -07006756
6757SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd, const SyncValidator &sync_state,
6758 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006759 const VkSubpassBeginInfo *pSubpassBeginInfo)
6760 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006761 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006762 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006763 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006764 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006765 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006766 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006767 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6768 // Note that this a safe to presist as long as shared_attachments is not cleared
6769 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006770 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006771 attachments_.emplace_back(attachment.get());
6772 }
6773 }
6774 if (pSubpassBeginInfo) {
6775 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6776 }
6777 }
6778}
6779
6780bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6781 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6782 bool skip = false;
6783
6784 assert(rp_state_.get());
6785 if (nullptr == rp_state_.get()) return skip;
6786 auto &rp_state = *rp_state_.get();
6787
6788 const uint32_t subpass = 0;
6789
6790 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6791 // hasn't happened yet)
6792 const std::vector<AccessContext> empty_context_vector;
6793 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6794 cb_context.GetCurrentAccessContext());
6795
6796 // Validate attachment operations
6797 if (attachments_.size() == 0) return skip;
6798 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07006799
6800 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
6801 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
6802 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
6803 // operations (though it's currently a messy approach)
6804 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
6805 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, CmdName());
John Zulauf64ffe552021-02-06 10:25:07 -07006806
6807 // Validate load operations if there were no layout transition hazards
6808 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06006809 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07006810 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, CmdName());
John Zulauf64ffe552021-02-06 10:25:07 -07006811 }
6812
6813 return skip;
6814}
6815
John Zulauf8eda1562021-04-13 17:06:41 -06006816ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07006817 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
6818 assert(rp_state_.get());
John Zulauf41a9c7c2021-12-07 15:59:53 -07006819 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_);
6820 return cb_context->RecordBeginRenderPass(cmd_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07006821}
6822
John Zulauf8eda1562021-04-13 17:06:41 -06006823bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006824 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006825 return false;
6826}
6827
John Zulaufbb890452021-12-14 11:30:18 -07006828void SyncOpBeginRenderPass::ReplayRecord(ResourceUsageTag tag, AccessContext *access_context,
6829 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006830
John Zulauf64ffe552021-02-06 10:25:07 -07006831SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd, const SyncValidator &sync_state, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07006832 const VkSubpassEndInfo *pSubpassEndInfo)
6833 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006834 if (pSubpassBeginInfo) {
6835 subpass_begin_info_.initialize(pSubpassBeginInfo);
6836 }
6837 if (pSubpassEndInfo) {
6838 subpass_end_info_.initialize(pSubpassEndInfo);
6839 }
6840}
6841
6842bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
6843 bool skip = false;
6844 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6845 if (!renderpass_context) return skip;
6846
6847 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), CmdName());
6848 return skip;
6849}
6850
John Zulauf8eda1562021-04-13 17:06:41 -06006851ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006852 return cb_context->RecordNextSubpass(cmd_);
John Zulauf8eda1562021-04-13 17:06:41 -06006853}
6854
6855bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006856 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006857 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07006858}
6859
sfricke-samsung85584a72021-09-30 21:43:38 -07006860SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd, const SyncValidator &sync_state, const VkSubpassEndInfo *pSubpassEndInfo)
6861 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006862 if (pSubpassEndInfo) {
6863 subpass_end_info_.initialize(pSubpassEndInfo);
6864 }
6865}
6866
John Zulaufbb890452021-12-14 11:30:18 -07006867void SyncOpNextSubpass::ReplayRecord(ResourceUsageTag tag, AccessContext *access_context, SyncEventsContext *events_context) const {
6868}
John Zulauf8eda1562021-04-13 17:06:41 -06006869
John Zulauf64ffe552021-02-06 10:25:07 -07006870bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6871 bool skip = false;
6872 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6873
6874 if (!renderpass_context) return skip;
6875 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), CmdName());
6876 return skip;
6877}
6878
John Zulauf8eda1562021-04-13 17:06:41 -06006879ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006880 return cb_context->RecordEndRenderPass(cmd_);
John Zulauf64ffe552021-02-06 10:25:07 -07006881}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006882
John Zulauf8eda1562021-04-13 17:06:41 -06006883bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006884 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006885 return false;
6886}
6887
John Zulaufbb890452021-12-14 11:30:18 -07006888void SyncOpEndRenderPass::ReplayRecord(ResourceUsageTag tag, AccessContext *access_context,
6889 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006890
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006891void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6892 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
6893 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
6894 auto *cb_access_context = GetAccessContext(commandBuffer);
6895 assert(cb_access_context);
6896 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
6897 auto *context = cb_access_context->GetCurrentAccessContext();
6898 assert(context);
6899
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006900 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006901
6902 if (dst_buffer) {
6903 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6904 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
6905 }
6906}
John Zulaufd05c5842021-03-26 11:32:16 -06006907
John Zulaufae842002021-04-15 18:20:55 -06006908bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6909 const VkCommandBuffer *pCommandBuffers) const {
6910 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
6911 const char *func_name = "vkCmdExecuteCommands";
6912 const auto *cb_context = GetAccessContext(commandBuffer);
6913 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006914
6915 // Heavyweight, but we need a proxy copy of the active command buffer access context
6916 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06006917
6918 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06006919 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006920 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
6921
John Zulaufae842002021-04-15 18:20:55 -06006922 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6923 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06006924
6925 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
6926 assert(recorded_context);
6927 skip |= recorded_cb_context->ValidateFirstUse(&proxy_cb_context, func_name, cb_index);
6928
6929 // The barriers have already been applied in ValidatFirstUse
6930 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06006931 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06006932 }
6933
John Zulaufae842002021-04-15 18:20:55 -06006934 return skip;
6935}
6936
6937void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6938 const VkCommandBuffer *pCommandBuffers) {
6939 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06006940 auto *cb_context = GetAccessContext(commandBuffer);
6941 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006942 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006943 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06006944 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6945 if (!recorded_cb_context) continue;
6946 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context, CMD_EXECUTECOMMANDS);
6947 }
John Zulaufae842002021-04-15 18:20:55 -06006948}
6949
John Zulauf1d5f9c12022-05-13 14:51:08 -06006950void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
6951 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
6952 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
6953
6954 const auto queue_state = GetQueueSyncStateShared(queue);
6955 if (!queue_state) return; // Invalid queue
6956 QueueId waited_queue = queue_state->GetQueueId();
6957
6958 // We need to go through every queue batch context and clear all accesses this wait synchronizes
6959 // As usual -- two groups, the "last batch" and the signaled semaphores
6960 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
6961 // QueueBatchContext, track which we've done to avoid duplicate traversals
6962 QueueBatchContext::BatchSet waited;
6963 for (auto &queue : queue_sync_states_) {
6964 auto batch = queue.second->LastBatch();
6965 if (batch) {
6966 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
6967 waited.emplace(batch);
6968 }
6969 }
6970
6971 for (const auto &signaled : signaled_semaphores_) {
6972 auto &sem_sig = signaled.second;
6973 if (sem_sig && sem_sig->batch && (waited.find(sem_sig->batch) == waited.end())) {
6974 sem_sig->batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
6975 waited.emplace(sem_sig->batch);
6976 }
6977 }
6978 // TODO: Update Events and Fences affected by Wait
6979}
6980
6981void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
6982 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
6983 for (auto &queue : queue_sync_states_) {
6984 auto batch = queue.second->LastBatch();
6985 if (batch) {
6986 batch->ApplyDeviceWait();
6987 }
6988 }
6989
6990 auto wait_no_list = [](std::shared_ptr<QueueBatchContext> &batch) {
6991 batch->ApplyDeviceWait();
6992 return false;
6993 };
6994
6995 GetQueueLastBatchSnapshot(wait_no_list);
6996
6997 // TODO: Update Events and Fences affected by Wait
6998}
6999
John Zulauf697c0e12022-04-19 16:31:12 -06007000struct QueueSubmitCmdState {
7001 std::shared_ptr<const QueueSyncState> queue;
7002 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007003 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007004 SignaledSemaphores signaled;
John Zulauf697c0e12022-04-19 16:31:12 -06007005 QueueSubmitCmdState(const AccessLogger &parent_log) : logger(&parent_log) {}
7006};
7007
7008template <>
7009thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7010
John Zulaufbbda4572022-04-19 16:20:45 -06007011bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7012 VkFence fence) const {
7013 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007014
7015 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007016 if (!enabled[sync_validation_queue_submit]) return skip;
7017
John Zulauf697c0e12022-04-19 16:31:12 -06007018 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_);
7019 const auto fence_state = Get<FENCE_STATE>(fence);
7020 cmd_state->queue = GetQueueSyncStateShared(queue);
7021 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007022
John Zulauf697c0e12022-04-19 16:31:12 -06007023 const char *func_name = "vkQueueSubmit";
7024
7025 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7026 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7027
7028 // verify each submit batch
7029 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7030 // most recently created batch
7031 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7032 std::shared_ptr<QueueBatchContext> batch;
7033 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7034 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007035 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7036 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007037 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
7038
7039 // For each submit in the batch...
7040 for (const auto &cb : *batch) {
7041 skip |= cb.cb->ValidateFirstUse(batch.get(), func_name, cb.index);
7042
7043 // The barriers have already been applied in ValidatFirstUse
7044 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007045 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
John Zulauf697c0e12022-04-19 16:31:12 -06007046 }
7047
John Zulauf697c0e12022-04-19 16:31:12 -06007048 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7049 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007050 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007051 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007052 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7053 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7054 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007055 }
7056 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7057 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7058 last_batch = batch;
7059 }
7060 // The most recently created batch will become the queue's "last batch" in the record phase
7061 if (batch) {
7062 cmd_state->last_batch = std::move(batch);
7063 }
7064
7065 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007066 return skip;
7067}
7068
7069void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7070 VkResult result) {
7071 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007072
John Zulaufcb7e1672022-05-04 13:46:08 -06007073 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007074 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7075
John Zulaufcb7e1672022-05-04 13:46:08 -06007076 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7077 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007078 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007079
7080 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007081 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7082
John Zulauf697c0e12022-04-19 16:31:12 -06007083 // Don't need to look up the queue state again, but we need a non-const version
7084 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007085
John Zulaufcb7e1672022-05-04 13:46:08 -06007086 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7087 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7088 // QBC's are those referenced by unwaited signals and the last batch.
7089 for (auto &sig_sem : cmd_state->signaled) {
7090 if (sig_sem.second && sig_sem.second->batch) {
7091 sig_sem.second->batch->ResetAccessLog();
7092 }
7093 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007094 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007095 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007096
John Zulaufcb7e1672022-05-04 13:46:08 -06007097 // Update the queue to point to the last batch from the submit
7098 if (cmd_state->last_batch) {
7099 cmd_state->last_batch->ResetAccessLog();
7100 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007101 }
7102
7103 // Update the global access log from the one built during validation
7104 global_access_log_.MergeMove(std::move(cmd_state->logger));
7105
John Zulauf697c0e12022-04-19 16:31:12 -06007106
7107 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007108}
7109
7110bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7111 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007112 bool skip = false;
7113 if (!enabled[sync_validation_queue_submit]) return skip;
7114
John Zulauf697c0e12022-04-19 16:31:12 -06007115 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007116 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007117}
7118
7119void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7120 VkFence fence, VkResult result) {
7121 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007122 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7123
7124 if (!enabled[sync_validation_queue_submit]) return;
7125
John Zulauf697c0e12022-04-19 16:31:12 -06007126 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007127}
7128
John Zulaufd0ec59f2021-03-13 14:25:08 -07007129AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7130 : view_(view), view_mask_(), gen_store_() {
7131 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7132 const IMAGE_STATE &image_state = *view_->image_state.get();
7133 const auto base_address = ResourceBaseAddress(image_state);
7134 const auto *encoder = image_state.fragment_encoder.get();
7135 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007136 // Get offset and extent for the view, accounting for possible depth slicing
7137 const VkOffset3D zero_offset = view->GetOffset();
7138 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007139 // Intentional copy
7140 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7141 view_mask_ = subres_range.aspectMask;
7142 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address);
7143 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address);
7144
7145 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7146 if (depth && (depth != view_mask_)) {
7147 subres_range.aspectMask = depth;
7148 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address);
7149 }
7150 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7151 if (stencil && (stencil != view_mask_)) {
7152 subres_range.aspectMask = stencil;
7153 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address);
7154 }
7155}
7156
7157const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7158 const ImageRangeGen *got = nullptr;
7159 switch (gen_type) {
7160 case kViewSubresource:
7161 got = &gen_store_[kViewSubresource];
7162 break;
7163 case kRenderArea:
7164 got = &gen_store_[kRenderArea];
7165 break;
7166 case kDepthOnlyRenderArea:
7167 got =
7168 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7169 break;
7170 case kStencilOnlyRenderArea:
7171 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7172 : &gen_store_[Gen::kStencilOnlyRenderArea];
7173 break;
7174 default:
7175 assert(got);
7176 }
7177 return got;
7178}
7179
7180AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7181 assert(IsValid());
7182 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7183 if (depth_op) {
7184 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7185 if (stencil_op) {
7186 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7187 return kRenderArea;
7188 }
7189 return kDepthOnlyRenderArea;
7190 }
7191 if (stencil_op) {
7192 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7193 return kStencilOnlyRenderArea;
7194 }
7195
7196 assert(depth_op || stencil_op);
7197 return kRenderArea;
7198}
7199
7200AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007201
7202void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
7203 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7204 for (auto &event_pair : map_) {
7205 assert(event_pair.second); // Shouldn't be storing empty
7206 auto &sync_event = *event_pair.second;
7207 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
7208 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
7209 sync_event.barriers |= dst.exec_scope;
7210 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7211 }
7212 }
7213}
John Zulaufbb890452021-12-14 11:30:18 -07007214
7215ReplayTrackbackBarriersAction::ReplayTrackbackBarriersAction(VkQueueFlags queue_flags,
7216 const SubpassDependencyGraphNode &subpass_dep,
7217 const std::vector<ReplayTrackbackBarriersAction> &replay_contexts) {
7218 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
7219 trackback_barriers.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
7220 for (const auto &prev_dep : subpass_dep.prev) {
7221 const auto prev_pass = prev_dep.first->pass;
7222 const auto &prev_barriers = prev_dep.second;
7223 trackback_barriers.emplace_back(&replay_contexts[prev_pass], queue_flags, prev_barriers);
7224 }
7225 if (has_barrier_from_external) {
7226 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
7227 trackback_barriers.emplace_back(nullptr, queue_flags, subpass_dep.barrier_from_external);
7228 }
7229}
7230
7231void ReplayTrackbackBarriersAction::operator()(ResourceAccessState *access) const {
7232 if (trackback_barriers.size() == 1) {
7233 trackback_barriers[0](access);
7234 } else {
7235 ResourceAccessState resolved;
7236 for (const auto &trackback : trackback_barriers) {
7237 ResourceAccessState access_copy = *access;
7238 trackback(&access_copy);
7239 resolved.Resolve(access_copy);
7240 }
7241 *access = resolved;
7242 }
7243}
7244
7245ReplayTrackbackBarriersAction::TrackbackBarriers::TrackbackBarriers(
7246 const ReplayTrackbackBarriersAction *source_subpass_, VkQueueFlags queue_flags_,
7247 const std::vector<const VkSubpassDependency2 *> &subpass_dependencies_)
7248 : Base(source_subpass_, queue_flags_, subpass_dependencies_) {}
7249
7250void ReplayTrackbackBarriersAction::TrackbackBarriers::operator()(ResourceAccessState *access) const {
7251 if (source_subpass) {
7252 (*source_subpass)(access);
7253 }
7254 access->ApplyBarriersImmediate(barriers);
7255}
John Zulauf697c0e12022-04-19 16:31:12 -06007256
John Zulaufcb7e1672022-05-04 13:46:08 -06007257QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7258 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7259
John Zulauf697c0e12022-04-19 16:31:12 -06007260template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007261void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7262 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007263 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007264 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007265}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007266void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
7267 QueueId queue_id = queue_state_->GetQueueId();
7268 auto tag_queue_op = [offset, queue_id](ResourceAccessState *access) {
7269 access->OffsetTag(offset);
7270 access->SetQueueId(queue_id);
7271 };
7272 GetCurrentAccessContext()->ResolveFromContext(tag_queue_op, recorded_context);
7273}
John Zulauf697c0e12022-04-19 16:31:12 -06007274
7275VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7276
John Zulauf1d5f9c12022-05-13 14:51:08 -06007277void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7278 QueueWaitWorm wait_worm(queue_id);
7279 access_context_.ForAll(wait_worm);
7280 if (wait_worm.erase_all) {
7281 access_context_.Reset();
7282 } else {
7283 // TODO: Profiling will tell us if we need a more efficient clean up.
7284 for (const auto &address : wait_worm.erase_list) {
7285 access_context_.DeleteAccess(address);
7286 }
7287 }
7288}
7289
7290// Clear all accesses
7291void QueueBatchContext::ApplyDeviceWait() { access_context_.Reset(); }
7292
John Zulaufcb7e1672022-05-04 13:46:08 -06007293void QueueBatchContext::WaitOneSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask, WaitBatchMap &batch_trackbacks,
7294 SignaledSemaphores &signaled) {
7295 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
7296 if (!sem_state) return; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007297
John Zulaufcb7e1672022-05-04 13:46:08 -06007298 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7299 auto signal_state = signaled.Unsignal(sem);
7300 if (!signal_state) return; // Invalid signal, skip it.
7301
7302 const auto &sem_batch = signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007303 assert(sem_batch);
7304
7305 const AccessContext *sem_context = sem_batch->GetCurrentAccessContext();
7306
7307 using TrackBackPtr = AccessContext::TrackBack *;
John Zulaufcb7e1672022-05-04 13:46:08 -06007308 const auto trackback_insert = batch_trackbacks.emplace(sem_batch.get(), TrackBackPtr());
John Zulauf697c0e12022-04-19 16:31:12 -06007309 const bool inserted = trackback_insert.second;
7310 const auto trackback_it = trackback_insert.first;
7311
John Zulaufcb7e1672022-05-04 13:46:08 -06007312 const SyncExecScope &sem_scope = signal_state->exec_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007313 const auto queue_flags = queue_state_->GetQueueFlags();
7314 SyncExecScope dst_mask = SyncExecScope::MakeDst(queue_flags, wait_mask);
7315 const SyncBarrier sem_barrier(sem_scope, sem_scope.valid_accesses, dst_mask, SyncStageAccessFlags());
7316 if (inserted) {
7317 // If this is the first time we referenced this QueueBatchContext
7318 trackback_it->second = access_context_.AddTrackBack(sem_context, sem_barrier);
7319 }
7320 assert(trackback_it->second);
7321 trackback_it->second->barriers.emplace_back(sem_barrier);
7322}
7323
7324// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7325template <>
7326class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7327 public:
7328 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7329 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7330 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7331 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7332 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7333 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7334
7335 private:
7336 const VkSubmitInfo &info_;
7337};
7338template <typename BatchInfo, typename Fn>
7339void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7340 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7341 Accessor batch(batch_info);
7342 const uint32_t wait_count = batch.WaitSemaphoreCount();
7343 for (uint32_t i = 0; i < wait_count; ++i) {
7344 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7345 }
7346}
7347
7348template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007349void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7350 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007351 // Create trackbacks for the access context for this batch based on the semaphores and the previous batch in this
7352 // queue.
7353 WaitBatchMap batch_trackbacks;
John Zulaufcb7e1672022-05-04 13:46:08 -06007354 ForEachWaitSemaphore(batch_info, [this, &batch_trackbacks, &signaled](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7355 WaitOneSemaphore(sem, wait_mask, batch_trackbacks, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007356 });
7357
John Zulauf78cb2082022-04-20 16:37:48 -06007358 // If there are no semaphores to the previous batch, make sure a "submit order" empty trackback is added
7359 if (prev && (batch_trackbacks.find(prev.get()) == batch_trackbacks.end())) {
7360 access_context_.AddTrackBack(prev->GetCurrentAccessContext(), SyncBarrier());
7361 }
7362
John Zulauf697c0e12022-04-19 16:31:12 -06007363 // Flatten all previous contexts into the current one (for dependency chaining reasons)
7364 access_context_.ResolvePreviousAccesses();
7365 access_context_.ClearTrackBacks();
7366
7367 // Gather async context information for hazard checks and conserve the QBC's for the async batches
7368 const auto end_it = batch_trackbacks.end();
John Zulauf78cb2082022-04-20 16:37:48 -06007369 async_batches_ = sync_state_->GetQueueLastBatchSnapshot(
7370 [&batch_trackbacks, end_it, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
John Zulauf697c0e12022-04-19 16:31:12 -06007371 const auto found_it = batch_trackbacks.find(batch.get());
John Zulauf78cb2082022-04-20 16:37:48 -06007372 return found_it == end_it && (batch != prev);
John Zulauf697c0e12022-04-19 16:31:12 -06007373 });
7374 for (const auto &async_batch : async_batches_) {
7375 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7376 }
7377}
7378
7379template <typename BatchInfo>
7380void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7381 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7382 Accessor batch(batch_info);
7383
7384 // Create the list of command buffers to submit
7385 const uint32_t cb_count = batch.CommandBufferCount();
7386 command_buffers_.reserve(cb_count);
7387 for (uint32_t index = 0; index < cb_count; ++index) {
7388 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7389 if (cb_context) {
7390 tag_range_.end += cb_context->GetTagLimit();
7391 command_buffers_.emplace_back(index, std::move(cb_context));
7392 }
7393 }
7394}
7395
7396// Look up the usage informaiton from the local or global logger
7397std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7398 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7399 std::stringstream out;
7400 AccessLogger::AccessRecord access = use_logger[tag];
7401 if (access.IsValid()) {
7402 const AccessLogger::BatchRecord &batch = *access.batch;
7403 const ResourceUsageRecord &record = *access.record;
7404 // Queue and Batch information
7405 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7406 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7407
7408 // Commandbuffer Usages Information
7409 out << record;
7410 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7411 out << ", reset_no: " << std::to_string(record.reset_count);
7412 }
7413 return out.str();
7414}
7415
7416VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7417
7418void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7419 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7420 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7421 SetTagBias(global_tags.begin);
7422 // Add an access log for the batches range and point the batch at it.
7423 logger_ = &logger;
7424 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7425}
7426
7427void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7428 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7429 batch_log_->Append(submitted_cb.GetAccessLog());
7430}
7431
7432void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7433 const auto size = tag_range_.size();
7434 tag_range_.begin = bias;
7435 tag_range_.end = bias + size;
7436 access_context_.SetStartTag(bias);
7437}
7438
John Zulauf1d5f9c12022-05-13 14:51:08 -06007439QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7440
7441void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7442 bool erased = access.second.ApplyQueueTagWait(predicate);
7443 if (erased) {
7444 erase_list.emplace_back(address_type, access.first);
7445 } else {
7446 erase_all = false;
7447 }
7448}
7449
John Zulauf697c0e12022-04-19 16:31:12 -06007450AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7451 const ResourceUsageRange &range) {
7452 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7453 assert(inserted.second);
7454 return &inserted.first->second;
7455}
7456
7457void AccessLogger::MergeMove(AccessLogger &&child) {
7458 for (auto &range : child.access_log_map_) {
7459 BatchLog &child_batch = range.second;
7460 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7461 insert_pair.first->second = std::move(child_batch);
7462 assert(insert_pair.second);
7463 }
7464 child.Reset();
7465}
7466
7467void AccessLogger::Reset() {
7468 prev_ = nullptr;
7469 access_log_map_.clear();
7470}
7471
7472// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7473// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7474// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7475// the contexts Resolve all history from previous all contexts when created
7476void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7477 last_batch_ = std::move(last);
7478 last_batch_->ResetAccessLog();
7479}
7480
7481// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7482// scope state.
7483// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7484// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7485uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7486
7487void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7488 log_.insert(log_.end(), other.cbegin(), other.cend());
7489 for (const auto &record : other) {
7490 assert(record.cb_state);
7491 cbs_referenced_.insert(record.cb_state->shared_from_this());
7492 }
7493}
7494
7495AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7496 assert(index < log_.size());
7497 return AccessRecord{&batch_, &log_[index]};
7498}
7499
7500AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7501 AccessRecord access_record = {nullptr, nullptr};
7502
7503 auto found_range = access_log_map_.find(tag);
7504 if (found_range != access_log_map_.cend()) {
7505 const ResourceUsageTag bias = found_range->first.begin;
7506 assert(tag >= bias);
7507 access_record = found_range->second[tag - bias];
7508 } else if (prev_) {
7509 access_record = (*prev_)[tag];
7510 }
7511
7512 return access_record;
7513}
John Zulaufcb7e1672022-05-04 13:46:08 -06007514
7515std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
7516 std::shared_ptr<Signal> prev_state;
7517 if (prev_) {
7518 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7519 }
7520 return prev_state;
7521}