blob: 56022f25b7ea677c58b66c33cb36d083c8e853c2 [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
John Zulaufdab327f2022-07-08 12:02:05 -0600272static void InitSubpassContexts(VkQueueFlags queue_flags, const RENDER_PASS_STATE &rp_state, const AccessContext *external_context,
273 std::vector<AccessContext> &subpass_contexts) {
274 const auto &create_info = rp_state.createInfo;
275 // Add this for all subpasses here so that they exsist during next subpass validation
276 subpass_contexts.clear();
277 subpass_contexts.reserve(create_info.subpassCount);
278 for (uint32_t pass = 0; pass < create_info.subpassCount; pass++) {
279 subpass_contexts.emplace_back(pass, queue_flags, rp_state.subpass_dependencies, subpass_contexts, external_context);
280 }
281}
282
John Zulauf4fa68462021-04-26 21:04:22 -0600283// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
284CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
285 : CommandBufferAccessContext(from.sync_state_) {
286 // Copy only the needed fields out of from for a temporary, proxy command buffer context
287 cb_state_ = from.cb_state_;
288 queue_flags_ = from.queue_flags_;
289 destroyed_ = from.destroyed_;
290 access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
291 command_number_ = from.command_number_;
292 subcommand_number_ = from.subcommand_number_;
293 reset_count_ = from.reset_count_;
294
295 const auto *from_context = from.GetCurrentAccessContext();
296 assert(from_context);
297
298 // Construct a fully resolved single access context out of from
299 const NoopBarrierAction noop_barrier;
300 for (AccessAddressType address_type : kAddressTypes) {
301 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
302 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
303 }
304 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
305 cb_access_context_.ImportAsyncContexts(*from_context);
306
307 events_context_ = from.events_context_;
308
309 // We don't want to copy the full render_pass_context_ history just for the proxy.
310}
311
312std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf397e68b2022-04-19 11:44:07 -0600313 if (tag >= access_log_.size()) return std::string();
314
John Zulauf4fa68462021-04-26 21:04:22 -0600315 std::stringstream out;
316 assert(tag < access_log_.size());
317 const auto &record = access_log_[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600318 out << record;
319 if (cb_state_.get() != record.cb_state) {
320 out << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600321 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600322 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600323 return out.str();
324}
John Zulauf397e68b2022-04-19 11:44:07 -0600325
John Zulauf4fa68462021-04-26 21:04:22 -0600326std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
327 std::stringstream out;
328 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
329 out << ", " << FormatUsage(access.tag) << ")";
330 return out.str();
331}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700332
John Zulauf397e68b2022-04-19 11:44:07 -0600333std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600334 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600335 out << hazard;
336 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600337 return out.str();
338}
339
John Zulaufdab327f2022-07-08 12:02:05 -0600340
John Zulauf0223f142022-07-06 09:05:39 -0600341bool CommandExecutionContext::ValidForSyncOps() const {
342 bool valid = GetCurrentEventsContext() && GetCurrentAccessContext();
343 assert(valid);
344 return valid;
345}
346
John Zulaufd14743a2020-07-03 09:42:39 -0600347// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
348// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
349// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700350static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700351static const SyncStageAccessFlags kColorAttachmentAccessScope =
352 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
353 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
354 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
355 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700356static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
357 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 -0700358static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
359 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
360 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
361 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700362static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700363static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600364
John Zulauf8e3c3e92021-01-06 11:19:36 -0700365ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700366 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700367 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
368 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
369 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
370
John Zulaufee984022022-04-13 16:39:50 -0600371// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
372static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600373
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600374static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600375
John Zulaufcb7e1672022-05-04 13:46:08 -0600376VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600377 if (size == VK_WHOLE_SIZE) {
378 return (whole_size - offset);
379 }
380 return size;
381}
382
John Zulauf3e86bf02020-09-12 10:47:57 -0600383static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
384 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
385}
386
John Zulauf16adfc92020-04-08 10:28:33 -0600387template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600388static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600389 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
390}
391
John Zulauf355e49b2020-04-24 15:11:15 -0600392static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600393
John Zulauf3e86bf02020-09-12 10:47:57 -0600394static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
395 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
396}
397
398static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
399 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
400}
401
John Zulauf4a6105a2020-11-17 15:11:05 -0700402// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
403//
John Zulauf10f1f522020-12-18 12:00:35 -0700404// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
405//
John Zulauf4a6105a2020-11-17 15:11:05 -0700406// Usage:
407// Constructor() -- initializes the generator to point to the begin of the space declared.
408// * -- the current range of the generator empty signfies end
409// ++ -- advance to the next non-empty range (or end)
410
411// A wrapper for a single range with the same semantics as the actual generators below
412template <typename KeyType>
413class SingleRangeGenerator {
414 public:
415 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700416 const KeyType &operator*() const { return current_; }
417 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700418 SingleRangeGenerator &operator++() {
419 current_ = KeyType(); // just one real range
420 return *this;
421 }
422
423 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
424
425 private:
426 SingleRangeGenerator() = default;
427 const KeyType range_;
428 KeyType current_;
429};
430
John Zulaufae842002021-04-15 18:20:55 -0600431// Generate the ranges that are the intersection of range and the entries in the RangeMap
432template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
433class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700434 public:
John Zulaufd5115702021-01-18 12:34:33 -0700435 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600436 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700437 // Default construction for KeyType *must* be empty range
438 assert(current_.empty());
439 }
John Zulaufae842002021-04-15 18:20:55 -0600440 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 SeekBegin();
442 }
John Zulaufae842002021-04-15 18:20:55 -0600443 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700444
John Zulauf4a6105a2020-11-17 15:11:05 -0700445 const KeyType &operator*() const { return current_; }
446 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600447 MapRangesRangeGenerator &operator++() {
448 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700449 UpdateCurrent();
450 return *this;
451 }
452
John Zulaufae842002021-04-15 18:20:55 -0600453 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700454
John Zulaufae842002021-04-15 18:20:55 -0600455 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700456 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600457 if (map_pos_ != map_->cend()) {
458 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700459 } else {
460 current_ = KeyType();
461 }
462 }
463 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600464 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700465 UpdateCurrent();
466 }
John Zulaufae842002021-04-15 18:20:55 -0600467
468 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
469 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
470 template <typename Pred>
471 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
472 do {
473 ++map_pos_;
474 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
475 UpdateCurrent();
476 return *this;
477 }
478
John Zulauf4a6105a2020-11-17 15:11:05 -0700479 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600480 const RangeMap *map_;
481 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700482 KeyType current_;
483};
John Zulaufd5115702021-01-18 12:34:33 -0700484using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600485using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700486
John Zulaufae842002021-04-15 18:20:55 -0600487// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
488template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
489class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
490 public:
491 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
492 // Default constructed is safe to dereference for "empty" test, but for no other operation.
493 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
494 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
495 : Base(filter, range), pred_(pred) {}
496 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
497
498 PredicatedMapRangesRangeGenerator &operator++() {
499 Base::PredicatedIncrement(pred_);
500 return *this;
501 }
502
503 protected:
504 Predicate pred_;
505};
John Zulauf4a6105a2020-11-17 15:11:05 -0700506
507// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600508// Templated to allow for different Range generators or map sources...
509template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700510class FilteredGeneratorGenerator {
511 public:
John Zulaufd5115702021-01-18 12:34:33 -0700512 // Default constructed is safe to dereference for "empty" test, but for no other operation.
513 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
514 // Default construction for KeyType *must* be empty range
515 assert(current_.empty());
516 }
John Zulaufae842002021-04-15 18:20:55 -0600517 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700518 SeekBegin();
519 }
John Zulaufd5115702021-01-18 12:34:33 -0700520 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700521 const KeyType &operator*() const { return current_; }
522 const KeyType *operator->() const { return &current_; }
523 FilteredGeneratorGenerator &operator++() {
524 KeyType gen_range = GenRange();
525 KeyType filter_range = FilterRange();
526 current_ = KeyType();
527 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
528 if (gen_range.end > filter_range.end) {
529 // if the generated range is beyond the filter_range, advance the filter range
530 filter_range = AdvanceFilter();
531 } else {
532 gen_range = AdvanceGen();
533 }
534 current_ = gen_range & filter_range;
535 }
536 return *this;
537 }
538
539 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
540
541 private:
542 KeyType AdvanceFilter() {
543 ++filter_pos_;
544 auto filter_range = FilterRange();
545 if (filter_range.valid()) {
546 FastForwardGen(filter_range);
547 }
548 return filter_range;
549 }
550 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700551 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700552 auto gen_range = GenRange();
553 if (gen_range.valid()) {
554 FastForwardFilter(gen_range);
555 }
556 return gen_range;
557 }
558
559 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700560 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700561
562 KeyType FastForwardFilter(const KeyType &range) {
563 auto filter_range = FilterRange();
564 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700565 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700566 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
567 if (retry_count < kRetryLimit) {
568 ++filter_pos_;
569 filter_range = FilterRange();
570 retry_count++;
571 } else {
572 // Okay we've tried walking, do a seek.
573 filter_pos_ = filter_->lower_bound(range);
574 break;
575 }
576 }
577 return FilterRange();
578 }
579
580 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
581 // faster.
582 KeyType FastForwardGen(const KeyType &range) {
583 auto gen_range = GenRange();
584 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700585 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700586 gen_range = GenRange();
587 }
588 return gen_range;
589 }
590
591 void SeekBegin() {
592 auto gen_range = GenRange();
593 if (gen_range.empty()) {
594 current_ = KeyType();
595 filter_pos_ = filter_->cend();
596 } else {
597 filter_pos_ = filter_->lower_bound(gen_range);
598 current_ = gen_range & FilterRange();
599 }
600 }
601
John Zulaufae842002021-04-15 18:20:55 -0600602 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700603 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600604 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700605 KeyType current_;
606};
607
608using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
609
John Zulauf5c5e88d2019-12-26 11:22:02 -0700610
John Zulauf3e86bf02020-09-12 10:47:57 -0600611ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
612 VkDeviceSize stride) {
613 VkDeviceSize range_start = offset + first_index * stride;
614 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600615 if (count == UINT32_MAX) {
616 range_size = buf_whole_size - range_start;
617 } else {
618 range_size = count * stride;
619 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600620 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600621}
622
locke-lunarg654e3692020-06-04 17:19:15 -0600623SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
624 VkShaderStageFlagBits stage_flag) {
625 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
626 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
627 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
628 }
629 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
630 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
631 assert(0);
632 }
633 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
634 return stage_access->second.uniform_read;
635 }
636
637 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
638 // Because if write hazard happens, read hazard might or might not happen.
639 // But if write hazard doesn't happen, read hazard is impossible to happen.
640 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700641 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600642 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700643 // TODO: sampled_read
644 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600645}
646
locke-lunarg37047832020-06-12 13:44:45 -0600647bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
648 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
649 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
650 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
651 ? true
652 : false;
653}
654
655bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
656 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
657 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
658 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
659 ? true
660 : false;
661}
662
John Zulauf355e49b2020-04-24 15:11:15 -0600663// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600664template <typename Action>
665static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
666 Action &action) {
667 // At this point the "apply over range" logic only supports a single memory binding
668 if (!SimpleBinding(image_state)) return;
669 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600670 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700671 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200672 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600673 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700674 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600675 }
676}
677
John Zulauf7635de32020-05-29 17:14:15 -0600678// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
679// Used by both validation and record operations
680//
681// The signature for Action() reflect the needs of both uses.
682template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
684 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600685 const auto &rp_ci = rp_state.createInfo;
686 const auto *attachment_ci = rp_ci.pAttachments;
687 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
688
689 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
690 const auto *color_attachments = subpass_ci.pColorAttachments;
691 const auto *color_resolve = subpass_ci.pResolveAttachments;
692 if (color_resolve && color_attachments) {
693 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
694 const auto &color_attach = color_attachments[i].attachment;
695 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
696 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
697 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700698 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
699 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600700 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700701 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
702 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600703 }
704 }
705 }
706
707 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700708 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600709 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
710 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
711 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
712 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
713 const auto src_ci = attachment_ci[src_at];
714 // The formats are required to match so we can pick either
715 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
716 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
717 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600718
719 // Figure out which aspects are actually touched during resolve operations
720 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700721 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600722 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600723 aspect_string = "depth/stencil";
724 } else if (resolve_depth) {
725 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700726 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600727 aspect_string = "depth";
728 } else if (resolve_stencil) {
729 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700730 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600731 aspect_string = "stencil";
732 }
733
John Zulaufd0ec59f2021-03-13 14:25:08 -0700734 if (aspect_string) {
735 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
736 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
737 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
738 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600739 }
740 }
741}
742
743// Action for validating resolve operations
744class ValidateResolveAction {
745 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700746 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
sjfricke0bea06e2022-06-05 09:22:26 +0900747 const CommandExecutionContext &exec_context, CMD_TYPE cmd_type)
John Zulauf7635de32020-05-29 17:14:15 -0600748 : render_pass_(render_pass),
749 subpass_(subpass),
750 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700751 exec_context_(exec_context),
sjfricke0bea06e2022-06-05 09:22:26 +0900752 cmd_type_(cmd_type),
John Zulauf7635de32020-05-29 17:14:15 -0600753 skip_(false) {}
754 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 -0700755 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
756 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600757 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700758 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600759 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +0900760 skip_ |= exec_context_.GetSyncState().LogError(
761 render_pass_, string_SyncHazardVUID(hazard.hazard),
762 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32
763 ". Access info %s.",
764 CommandTypeString(cmd_type_), string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at,
765 dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600766 }
767 }
768 // Providing a mechanism for the constructing caller to get the result of the validation
769 bool GetSkip() const { return skip_; }
770
771 private:
772 VkRenderPass render_pass_;
773 const uint32_t subpass_;
774 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700775 const CommandExecutionContext &exec_context_;
sjfricke0bea06e2022-06-05 09:22:26 +0900776 CMD_TYPE cmd_type_;
John Zulauf7635de32020-05-29 17:14:15 -0600777 bool skip_;
778};
779
780// Update action for resolve operations
781class UpdateStateResolveAction {
782 public:
John Zulauf14940722021-04-12 15:19:02 -0600783 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700784 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
785 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600786 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700787 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600788 }
789
790 private:
791 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600792 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600793};
794
John Zulauf59e25072020-07-17 10:55:21 -0600795void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600796 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600797 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600798 usage_index = usage_index_;
799 hazard = hazard_;
800 prior_access = prior_;
801 tag = tag_;
802}
803
John Zulauf4fa68462021-04-26 21:04:22 -0600804void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
805 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
806}
807
John Zulauf1d5f9c12022-05-13 14:51:08 -0600808void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
809
John Zulauf540266b2020-04-06 18:54:53 -0600810AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
811 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600812 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600813 Reset();
814 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700815 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
816 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600817 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600818 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600819 const auto prev_pass = prev_dep.first->pass;
820 const auto &prev_barriers = prev_dep.second;
821 assert(prev_dep.second.size());
822 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
823 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700824 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600825
826 async_.reserve(subpass_dep.async.size());
827 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700828 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600829 }
John Zulauf22aefed2021-03-11 18:14:35 -0700830 if (has_barrier_from_external) {
831 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
832 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
833 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600834 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600835 if (subpass_dep.barrier_to_external.size()) {
836 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600837 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700838}
839
John Zulauf5f13a792020-03-10 07:31:21 -0600840template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600841HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600842 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600843 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600844 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600845
846 HazardResult hazard;
847 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
848 hazard = detector.Detect(prev);
849 }
850 return hazard;
851}
852
John Zulauf4a6105a2020-11-17 15:11:05 -0700853template <typename Action>
854void AccessContext::ForAll(Action &&action) {
855 for (const auto address_type : kAddressTypes) {
856 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600857 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700858 action(address_type, access);
859 }
860 }
861}
862
John Zulauf3da08bb2022-08-01 17:56:56 -0600863template <typename Predicate>
864void AccessContext::EraseIf(Predicate &&pred) {
865 for (const auto address_type : kAddressTypes) {
866 auto &accesses = GetAccessStateMap(address_type);
867 // Note: Don't forward, we don't want r-values moved, since we're going to make multiple calls.
868 layer_data::EraseIf(accesses, pred);
869 }
870}
871
John Zulauf3d84f1b2020-03-09 13:33:25 -0600872// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
873// the DAG of the contexts (for example subpasses)
874template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600875HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600876 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600877 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600878
John Zulauf1a224292020-06-30 14:52:13 -0600879 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600880 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
881 // so we'll check these first
882 for (const auto &async_context : async_) {
883 hazard = async_context->DetectAsyncHazard(type, detector, range);
884 if (hazard.hazard) return hazard;
885 }
John Zulauf5f13a792020-03-10 07:31:21 -0600886 }
887
John Zulauf1a224292020-06-30 14:52:13 -0600888 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600889
John Zulauf69133422020-05-20 14:55:53 -0600890 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600891 const auto the_end = accesses.cend(); // End is not invalidated
892 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600893 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600894
John Zulauf3cafbf72021-03-26 16:55:19 -0600895 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600896 // Cover any leading gap, or gap between entries
897 if (detect_prev) {
898 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
899 // Cover any leading gap, or gap between entries
900 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600901 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600902 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600903 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600904 if (hazard.hazard) return hazard;
905 }
John Zulauf69133422020-05-20 14:55:53 -0600906 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
907 gap.begin = pos->first.end;
908 }
909
910 hazard = detector.Detect(pos);
911 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600912 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600913 }
914
915 if (detect_prev) {
916 // Detect in the trailing empty as needed
917 gap.end = range.end;
918 if (gap.non_empty()) {
919 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600920 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600921 }
922
923 return hazard;
924}
925
926// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
927template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700928HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
929 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600930 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600931 auto pos = accesses.lower_bound(range);
932 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600933
John Zulauf3d84f1b2020-03-09 13:33:25 -0600934 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600935 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700936 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600937 if (hazard.hazard) break;
938 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600939 }
John Zulauf16adfc92020-04-08 10:28:33 -0600940
John Zulauf3d84f1b2020-03-09 13:33:25 -0600941 return hazard;
942}
943
John Zulaufb02c1eb2020-10-06 16:33:36 -0600944struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700945 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600946 void operator()(ResourceAccessState *access) const {
947 assert(access);
948 access->ApplyBarriers(barriers, true);
949 }
950 const std::vector<SyncBarrier> &barriers;
951};
952
John Zulaufe0757ba2022-06-10 16:51:45 -0600953struct QueueTagOffsetBarrierAction {
954 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
955 void operator()(ResourceAccessState *access) const {
956 access->OffsetTag(tag_offset);
957 access->SetQueueId(queue_id);
958 };
959 QueueId queue_id;
960 ResourceUsageTag tag_offset;
961};
962
John Zulauf22aefed2021-03-11 18:14:35 -0700963struct ApplyTrackbackStackAction {
964 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
965 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
966 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600967 void operator()(ResourceAccessState *access) const {
968 assert(access);
969 assert(!access->HasPendingState());
970 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600971 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
972 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700973 if (previous_barrier) {
974 assert(bool(*previous_barrier));
975 (*previous_barrier)(access);
976 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977 }
978 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700979 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600980};
981
982// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
983// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
984// *different* map from dest.
985// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
986// range [first, last)
987template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600988static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
989 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600990 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600991 auto at = entry;
992 for (auto pos = first; pos != last; ++pos) {
993 // Every member of the input iterator range must fit within the remaining portion of entry
994 assert(at->first.includes(pos->first));
995 assert(at != dest->end());
996 // Trim up at to the same size as the entry to resolve
997 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600998 auto access = pos->second; // intentional copy
999 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -06001000 at->second.Resolve(access);
1001 ++at; // Go to the remaining unused section of entry
1002 }
1003}
1004
John Zulaufa0a98292020-09-18 09:30:10 -06001005static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
1006 SyncBarrier merged = {};
1007 for (const auto &barrier : barriers) {
1008 merged.Merge(barrier);
1009 }
1010 return merged;
1011}
1012
John Zulaufb02c1eb2020-10-06 16:33:36 -06001013template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -07001014void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -06001015 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
1016 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001017 if (!range.non_empty()) return;
1018
John Zulauf355e49b2020-04-24 15:11:15 -06001019 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
1020 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001021 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001022 if (current->pos_B->valid) {
1023 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001024 auto access = src_pos->second; // intentional copy
1025 barrier_action(&access);
1026
John Zulauf16adfc92020-04-08 10:28:33 -06001027 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001028 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1029 trimmed->second.Resolve(access);
1030 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001031 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001032 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001033 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001034 }
John Zulauf16adfc92020-04-08 10:28:33 -06001035 } else {
1036 // we have to descend to fill this gap
1037 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001038 ResourceAccessRange recurrence_range = current_range;
1039 // The current context is empty for the current range, so recur to fill the gap.
1040 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1041 // is not valid, to minimize that recurrence
1042 if (current->pos_B.at_end()) {
1043 // Do the remainder here....
1044 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001045 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001046 // Recur only over the range until B becomes valid (within the limits of range).
1047 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001048 }
John Zulauf22aefed2021-03-11 18:14:35 -07001049 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1050
John Zulauf355e49b2020-04-24 15:11:15 -06001051 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1052 // iterator of the outer while.
1053
1054 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1055 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1056 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001057 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 -06001058 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001059 current.seek(seek_to);
1060 } else if (!current->pos_A->valid && infill_state) {
1061 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1062 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1063 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001064 }
John Zulauf5f13a792020-03-10 07:31:21 -06001065 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001066 if (current->range.non_empty()) {
1067 ++current;
1068 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001069 }
John Zulauf1a224292020-06-30 14:52:13 -06001070
1071 // Infill if range goes passed both the current and resolve map prior contents
1072 if (recur_to_infill && (current->range.end < range.end)) {
1073 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001074 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001075 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001076}
1077
John Zulauf22aefed2021-03-11 18:14:35 -07001078template <typename BarrierAction>
1079void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1080 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1081 const BarrierAction &previous_barrier) const {
1082 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1083 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1084}
1085
John Zulauf43cc7462020-12-03 12:33:12 -07001086void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001087 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1088 const ResourceAccessStateFunction *previous_barrier) const {
1089 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001090 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001091 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1092 ResourceAccessState state_copy;
1093 if (previous_barrier) {
1094 assert(bool(*previous_barrier));
1095 state_copy = *infill_state;
1096 (*previous_barrier)(&state_copy);
1097 infill_state = &state_copy;
1098 }
1099 sparse_container::update_range_value(*descent_map, range, *infill_state,
1100 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001101 }
1102 } else {
1103 // Look for something to fill the gap further along.
1104 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001105 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001106 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001107 }
John Zulauf5f13a792020-03-10 07:31:21 -06001108 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001109}
1110
John Zulauf4a6105a2020-11-17 15:11:05 -07001111// Non-lazy import of all accesses, WaitEvents needs this.
1112void AccessContext::ResolvePreviousAccesses() {
1113 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001114 if (!prev_.size()) return; // If no previous contexts, nothing to do
1115
John Zulauf4a6105a2020-11-17 15:11:05 -07001116 for (const auto address_type : kAddressTypes) {
1117 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1118 }
1119}
1120
John Zulauf43cc7462020-12-03 12:33:12 -07001121AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1122 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001123}
1124
John Zulauf1507ee42020-05-18 11:33:09 -06001125static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001126 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1127 ? SYNC_ACCESS_INDEX_NONE
1128 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1129 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001130 return stage_access;
1131}
1132static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001133 const auto stage_access =
1134 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1135 ? SYNC_ACCESS_INDEX_NONE
1136 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1137 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001138 return stage_access;
1139}
1140
John Zulauf7635de32020-05-29 17:14:15 -06001141// Caller must manage returned pointer
1142static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001143 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001144 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001145 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1146 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001147 return proxy;
1148}
1149
John Zulaufb02c1eb2020-10-06 16:33:36 -06001150template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001151void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1152 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1153 const ResourceAccessState *infill_state) const {
1154 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1155 if (!attachment_gen) return;
1156
1157 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1158 const AccessAddressType address_type = view_gen.GetAddressType();
1159 for (; range_gen->non_empty(); ++range_gen) {
1160 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001161 }
John Zulauf62f10592020-04-03 12:20:02 -06001162}
1163
John Zulauf1d5f9c12022-05-13 14:51:08 -06001164template <typename ResolveOp>
1165void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1166 const ResourceAccessState *infill_state, bool recur_to_infill) {
1167 for (auto address_type : kAddressTypes) {
1168 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1169 recur_to_infill);
1170 }
1171}
1172
John Zulauf7635de32020-05-29 17:14:15 -06001173// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001174bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001175 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001176 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001177 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001178 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1179 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1180 // those affects have not been recorded yet.
1181 //
1182 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1183 // to apply and only copy then, if this proves a hot spot.
1184 std::unique_ptr<AccessContext> proxy_for_prev;
1185 TrackBack proxy_track_back;
1186
John Zulauf355e49b2020-04-24 15:11:15 -06001187 const auto &transitions = rp_state.subpass_transitions[subpass];
1188 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001189 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1190
1191 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001192 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001193 if (prev_needs_proxy) {
1194 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001195 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001196 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001197 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001198 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001199 }
1200 track_back = &proxy_track_back;
1201 }
1202 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001203 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001204 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001205 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001206 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001207 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1208 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1209 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1210 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1211 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1212 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001213 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001214 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1215 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1216 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1217 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1218 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001219 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001220 }
John Zulauf355e49b2020-04-24 15:11:15 -06001221 }
1222 }
1223 return skip;
1224}
1225
John Zulaufbb890452021-12-14 11:30:18 -07001226bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001227 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001228 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001229 bool skip = false;
1230 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001231
John Zulauf1507ee42020-05-18 11:33:09 -06001232 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1233 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001234 const auto &view_gen = attachment_views[i];
1235 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001236 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001237
1238 // Need check in the following way
1239 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1240 // vs. transition
1241 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1242 // for each aspect loaded.
1243
1244 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001245 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001246 const bool is_color = !(has_depth || has_stencil);
1247
1248 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001249 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001250
John Zulaufaff20662020-06-01 14:07:58 -06001251 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001252 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001253
John Zulaufb02c1eb2020-10-06 16:33:36 -06001254 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001255 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001256 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001257 aspect = "color";
1258 } else {
John Zulauf57261402021-08-13 11:32:06 -06001259 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001260 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1261 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001262 aspect = "depth";
1263 }
John Zulauf57261402021-08-13 11:32:06 -06001264 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001265 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1266 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001267 aspect = "stencil";
1268 checked_stencil = true;
1269 }
1270 }
1271
1272 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001273 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001274 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001275 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001276 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001277 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001278 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001279 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1280 " aspect %s during load with loadOp %s.",
1281 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1282 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001283 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001284 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001285 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001286 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001287 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001288 }
1289 }
1290 }
1291 }
1292 return skip;
1293}
1294
John Zulaufaff20662020-06-01 14:07:58 -06001295// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1296// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1297// store is part of the same Next/End operation.
1298// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001299bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001300 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001301 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001302 bool skip = false;
1303 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001304
1305 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1306 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001307 const AttachmentViewGen &view_gen = attachment_views[i];
1308 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001309 const auto &ci = attachment_ci[i];
1310
1311 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1312 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1313 // sake, we treat DONT_CARE as writing.
1314 const bool has_depth = FormatHasDepth(ci.format);
1315 const bool has_stencil = FormatHasStencil(ci.format);
1316 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001317 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001318 if (!has_stencil && !store_op_stores) continue;
1319
1320 HazardResult hazard;
1321 const char *aspect = nullptr;
1322 bool checked_stencil = false;
1323 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001324 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1325 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001326 aspect = "color";
1327 } else {
John Zulauf57261402021-08-13 11:32:06 -06001328 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001329 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001330 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1331 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001332 aspect = "depth";
1333 }
1334 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001335 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1336 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001337 aspect = "stencil";
1338 checked_stencil = true;
1339 }
1340 }
1341
1342 if (hazard.hazard) {
1343 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1344 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001345 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1346 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1347 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001348 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1349 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001350 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001351 }
1352 }
1353 }
1354 return skip;
1355}
1356
John Zulaufbb890452021-12-14 11:30:18 -07001357bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001358 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001359 CMD_TYPE cmd_type, uint32_t subpass) const {
1360 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001361 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001362 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001363}
1364
John Zulauf06f6f1e2022-04-19 15:28:11 -06001365void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1366
John Zulauf3d84f1b2020-03-09 13:33:25 -06001367class HazardDetector {
1368 SyncStageAccessIndex usage_index_;
1369
1370 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001371 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001372 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001373 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001374 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001375 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001376};
1377
John Zulauf69133422020-05-20 14:55:53 -06001378class HazardDetectorWithOrdering {
1379 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001380 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001381
1382 public:
1383 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001384 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001385 }
John Zulauf14940722021-04-12 15:19:02 -06001386 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001387 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001388 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001389 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001390};
1391
John Zulauf16adfc92020-04-08 10:28:33 -06001392HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001393 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001394 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001395 const auto base_address = ResourceBaseAddress(buffer);
1396 HazardDetector detector(usage_index);
1397 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001398}
1399
John Zulauf69133422020-05-20 14:55:53 -06001400template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001401HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1402 DetectOptions options) const {
1403 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1404 if (!attachment_gen) return HazardResult();
1405
1406 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1407 const auto address_type = view_gen.GetAddressType();
1408 for (; range_gen->non_empty(); ++range_gen) {
1409 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1410 if (hazard.hazard) return hazard;
1411 }
1412
1413 return HazardResult();
1414}
1415
1416template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001417HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1418 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001419 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001420 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001421 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001422 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001423 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001424 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001425 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001426 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001427 if (hazard.hazard) return hazard;
1428 }
1429 return HazardResult();
1430}
John Zulauf110413c2021-03-20 05:38:38 -06001431template <typename Detector>
1432HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001433 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1434 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001435 if (!SimpleBinding(image)) return HazardResult();
1436 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001437 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1438 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001439 const auto address_type = ImageAddressType(image);
1440 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001441 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1442 if (hazard.hazard) return hazard;
1443 }
1444 return HazardResult();
1445}
John Zulauf69133422020-05-20 14:55:53 -06001446
John Zulauf540266b2020-04-06 18:54:53 -06001447HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1448 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001449 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001450 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1451 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001452 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001453 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001454}
1455
1456HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001457 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001458 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001459 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001460}
1461
John Zulaufd0ec59f2021-03-13 14:25:08 -07001462HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1463 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1464 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1465 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1466}
1467
John Zulauf69133422020-05-20 14:55:53 -06001468HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001469 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001470 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001471 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001472 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001473}
1474
John Zulauf3d84f1b2020-03-09 13:33:25 -06001475class BarrierHazardDetector {
1476 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001477 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001478 SyncStageAccessFlags src_access_scope)
1479 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1480
John Zulauf5f13a792020-03-10 07:31:21 -06001481 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001482 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001483 }
John Zulauf14940722021-04-12 15:19:02 -06001484 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001485 // 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 -07001486 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001487 }
1488
1489 private:
1490 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001491 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001492 SyncStageAccessFlags src_access_scope_;
1493};
1494
John Zulauf4a6105a2020-11-17 15:11:05 -07001495class EventBarrierHazardDetector {
1496 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001497 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001498 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001499 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001500 : usage_index_(usage_index),
1501 src_exec_scope_(src_exec_scope),
1502 src_access_scope_(src_access_scope),
1503 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001504 scope_queue_id_(queue_id),
1505 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001506 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001507 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001508
John Zulaufe0757ba2022-06-10 16:51:45 -06001509 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1510 // Need to piece together coverage of pos->first range:
1511 // Copy the range as we'll be chopping it up as needed
1512 ResourceAccessRange range = pos->first;
1513 const ResourceAccessState &access = pos->second;
1514 HazardResult hazard;
1515
1516 bool in_scope = AdvanceScope(range);
1517 bool unscoped_tested = false;
1518 while (in_scope && !hazard.IsHazard()) {
1519 if (range.begin < ScopeBegin()) {
1520 if (!unscoped_tested) {
1521 unscoped_tested = true;
1522 hazard = access.DetectHazard(usage_index_);
1523 }
1524 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1525 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1526 range.begin = ScopeBegin();
1527 } else { // in_scope implied that ScopeRange and range intersect
1528 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1529 scope_tag_);
1530 if (!hazard.IsHazard()) {
1531 range.begin = ScopeEnd();
1532 in_scope = AdvanceScope(range); // contains a non_empty check
1533 }
1534 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001535 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001536 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1537 hazard = access.DetectHazard(usage_index_);
1538 }
1539 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001540 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001541
John Zulauf14940722021-04-12 15:19:02 -06001542 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001543 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1544 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1545 }
1546
1547 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001548 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1549 bool ScopeValid() const { return !ScopeInvalid(); }
1550 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1551
1552 // Hiding away the std::pair grunge...
1553 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1554 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1555 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1556 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1557
1558 bool AdvanceScope(const ResourceAccessRange &range) {
1559 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1560 if (!range.non_empty()) return false;
1561 if (ScopeInvalid()) return false;
1562
1563 if (ScopeRange().strictly_less(range)) {
1564 ScopeSeek(range);
1565 }
1566
1567 return ScopeValid() && ScopeRange().intersects(range);
1568 }
1569
John Zulauf4a6105a2020-11-17 15:11:05 -07001570 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001571 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001572 SyncStageAccessFlags src_access_scope_;
1573 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001574 QueueId scope_queue_id_;
1575 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001576 SyncEventState::ScopeMap::const_iterator scope_pos_;
1577 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001578};
1579
John Zulaufe0757ba2022-06-10 16:51:45 -06001580HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1581 VkPipelineStageFlags2KHR src_exec_scope,
1582 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1583 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001584 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1585 // first access scope map to use, and there's no easy way to plumb it in below.
1586 const auto address_type = ImageAddressType(image);
1587 const auto &event_scope = sync_event.FirstScope(address_type);
1588
1589 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001590 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001591 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001592}
1593
John Zulaufd0ec59f2021-03-13 14:25:08 -07001594HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1595 DetectOptions options) const {
1596 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1597 barrier.src_access_scope);
1598 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1599}
1600
Jeremy Gebben40a22942020-12-22 14:22:06 -07001601HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001602 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001603 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001604 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001605 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001606 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001607}
1608
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001609HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001610 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001611 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001612}
John Zulauf355e49b2020-04-24 15:11:15 -06001613
John Zulauf9cb530d2019-09-30 14:14:10 -06001614template <typename Flags, typename Map>
1615SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1616 SyncStageAccessFlags scope = 0;
1617 for (const auto &bit_scope : map) {
1618 if (flag_mask < bit_scope.first) break;
1619
1620 if (flag_mask & bit_scope.first) {
1621 scope |= bit_scope.second;
1622 }
1623 }
1624 return scope;
1625}
1626
Jeremy Gebben40a22942020-12-22 14:22:06 -07001627SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001628 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1629}
1630
Jeremy Gebben40a22942020-12-22 14:22:06 -07001631SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1632 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001633}
1634
Jeremy Gebben40a22942020-12-22 14:22:06 -07001635// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1636SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001637 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1638 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1639 // 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 -06001640 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1641}
1642
1643template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001644void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001645 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1646 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001647 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001648 auto pos = accesses->lower_bound(range);
1649 if (pos == accesses->end() || !pos->first.intersects(range)) {
1650 // The range is empty, fill it with a default value.
1651 pos = action.Infill(accesses, pos, range);
1652 } else if (range.begin < pos->first.begin) {
1653 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001654 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001655 } else if (pos->first.begin < range.begin) {
1656 // Trim the beginning if needed
1657 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1658 ++pos;
1659 }
1660
1661 const auto the_end = accesses->end();
1662 while ((pos != the_end) && pos->first.intersects(range)) {
1663 if (pos->first.end > range.end) {
1664 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1665 }
1666
1667 pos = action(accesses, pos);
1668 if (pos == the_end) break;
1669
1670 auto next = pos;
1671 ++next;
1672 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1673 // Need to infill if next is disjoint
1674 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001675 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001676 next = action.Infill(accesses, next, new_range);
1677 }
1678 pos = next;
1679 }
1680}
John Zulaufd5115702021-01-18 12:34:33 -07001681
1682// Give a comparable interface for range generators and ranges
1683template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001684void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001685 assert(range);
1686 UpdateMemoryAccessState(accesses, *range, action);
1687}
1688
John Zulauf4a6105a2020-11-17 15:11:05 -07001689template <typename Action, typename RangeGen>
1690void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1691 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001692 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 -07001693 for (; range_gen->non_empty(); ++range_gen) {
1694 UpdateMemoryAccessState(accesses, *range_gen, action);
1695 }
1696}
John Zulauf9cb530d2019-09-30 14:14:10 -06001697
John Zulaufd0ec59f2021-03-13 14:25:08 -07001698template <typename Action, typename RangeGen>
1699void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1700 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1701 for (; range_gen->non_empty(); ++range_gen) {
1702 UpdateMemoryAccessState(accesses, *range_gen, action);
1703 }
1704}
John Zulauf9cb530d2019-09-30 14:14:10 -06001705struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001706 using Iterator = ResourceAccessRangeMap::iterator;
1707 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001708 // this is only called on gaps, and never returns a gap.
1709 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001710 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001711 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001712 }
John Zulauf5f13a792020-03-10 07:31:21 -06001713
John Zulauf5c5e88d2019-12-26 11:22:02 -07001714 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001715 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001716 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001717 return pos;
1718 }
1719
John Zulauf43cc7462020-12-03 12:33:12 -07001720 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001721 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001722 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001723 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001724 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001725 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001726 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001727 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001728};
1729
John Zulauf4a6105a2020-11-17 15:11:05 -07001730// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001731struct PipelineBarrierOp {
1732 SyncBarrier barrier;
1733 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001734 ResourceAccessState::QueueScopeOps scope;
1735 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1736 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001737 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001738 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001739};
John Zulauf00119522022-05-23 19:07:42 -06001740
John Zulaufecf4ac52022-06-06 10:08:42 -06001741// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1742struct BatchBarrierOp : public PipelineBarrierOp {
1743 void operator()(ResourceAccessState *access_state) const {
1744 access_state->ApplyBarrier(scope, barrier, layout_transition);
1745 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1746 }
1747 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1748};
1749
John Zulauf4a6105a2020-11-17 15:11:05 -07001750// The barrier operation for wait events
1751struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001752 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001753 SyncBarrier barrier;
1754 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001755
1756 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001757 bool layout_transition_)
John Zulaufe0757ba2022-06-10 16:51:45 -06001758 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
John Zulaufb7578302022-05-19 13:50:18 -06001759 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001760};
John Zulauf1e331ec2020-12-04 18:29:38 -07001761
John Zulauf4a6105a2020-11-17 15:11:05 -07001762// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1763// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1764// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001765template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001766class ApplyBarrierOpsFunctor {
1767 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001768 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001769 // Only called with a gap, and pos at the lower_bound(range)
1770 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1771 if (!infill_default_) {
1772 return pos;
1773 }
1774 ResourceAccessState default_state;
1775 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1776 return inserted;
1777 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001778
John Zulauf5c628d02021-05-04 15:46:36 -06001779 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001780 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001781 for (const auto &op : barrier_ops_) {
1782 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001783 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001784
John Zulauf89311b42020-09-29 16:28:47 -06001785 if (resolve_) {
1786 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1787 // another walk
1788 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001789 }
1790 return pos;
1791 }
1792
John Zulauf89311b42020-09-29 16:28:47 -06001793 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001794 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1795 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001796 barrier_ops_.reserve(size_hint);
1797 }
John Zulauf5c628d02021-05-04 15:46:36 -06001798 void EmplaceBack(const BarrierOp &op) {
1799 barrier_ops_.emplace_back(op);
1800 infill_default_ |= op.layout_transition;
1801 }
John Zulauf89311b42020-09-29 16:28:47 -06001802
1803 private:
1804 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001805 bool infill_default_;
1806 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001807 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001808};
1809
John Zulauf4a6105a2020-11-17 15:11:05 -07001810// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1811// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1812template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001813class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1814 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1815
John Zulauf4a6105a2020-11-17 15:11:05 -07001816 public:
John Zulaufee984022022-04-13 16:39:50 -06001817 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001818};
1819
John Zulauf1e331ec2020-12-04 18:29:38 -07001820// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001821class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1822 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1823
John Zulauf1e331ec2020-12-04 18:29:38 -07001824 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001825 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001826};
1827
John Zulauf8e3c3e92021-01-06 11:19:36 -07001828void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001829 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001830 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001831 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001832}
1833
John Zulauf8e3c3e92021-01-06 11:19:36 -07001834void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001835 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001836 if (!SimpleBinding(buffer)) return;
1837 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001838 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001839}
John Zulauf355e49b2020-04-24 15:11:15 -06001840
John Zulauf8e3c3e92021-01-06 11:19:36 -07001841void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001842 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1843 if (!SimpleBinding(image)) return;
1844 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001845 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001846 const auto address_type = ImageAddressType(image);
1847 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1848 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1849}
1850void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001851 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001852 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001853 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001854 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001855 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001856 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001857 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001858 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001859 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001860}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001861
1862void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001863 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001864 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1865 if (!gen) return;
1866 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1867 const auto address_type = view_gen.GetAddressType();
1868 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1869 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001870}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001871
John Zulauf8e3c3e92021-01-06 11:19:36 -07001872void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001873 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001874 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001875 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1876 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001877 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001878}
1879
John Zulaufd0ec59f2021-03-13 14:25:08 -07001880template <typename Action, typename RangeGen>
1881void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1882 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1883 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001884}
1885
1886template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001887void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1888 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1889 if (!gen) return;
1890 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001891}
1892
John Zulaufd0ec59f2021-03-13 14:25:08 -07001893void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1894 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001895 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001896 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001897 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001898}
1899
John Zulaufd0ec59f2021-03-13 14:25:08 -07001900void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001901 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001902 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001903
1904 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1905 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001906 const auto &view_gen = attachment_views[i];
1907 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001908
1909 const auto &ci = attachment_ci[i];
1910 const bool has_depth = FormatHasDepth(ci.format);
1911 const bool has_stencil = FormatHasStencil(ci.format);
1912 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001913 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001914
1915 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001916 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1917 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001918 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001919 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001920 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1921 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001922 }
John Zulauf57261402021-08-13 11:32:06 -06001923 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001924 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001925 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1926 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001927 }
1928 }
1929 }
1930 }
1931}
1932
John Zulauf540266b2020-04-06 18:54:53 -06001933template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001934void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001935 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001936 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001937 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001938 }
1939}
1940
1941void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001942 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1943 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001944 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001945 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001946 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001947 }
1948 }
1949}
1950
John Zulauf4fa68462021-04-26 21:04:22 -06001951// Caller must ensure that lifespan of this is less than from
1952void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1953
John Zulauf355e49b2020-04-24 15:11:15 -06001954// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001955HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1956 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001957
John Zulauf355e49b2020-04-24 15:11:15 -06001958 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001959 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001960
1961 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001962 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1963 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001964 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001965 if (!hazard.hazard) {
1966 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001967 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001968 }
John Zulaufa0a98292020-09-18 09:30:10 -06001969
John Zulauf355e49b2020-04-24 15:11:15 -06001970 return hazard;
1971}
1972
John Zulaufb02c1eb2020-10-06 16:33:36 -06001973void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001974 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001975 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001976 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001977 for (const auto &transition : transitions) {
1978 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001979 const auto &view_gen = attachment_views[transition.attachment];
1980 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001981
1982 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1983 assert(trackback);
1984
1985 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001986 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001987 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001988 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001989 auto &target_map = GetAccessStateMap(address_type);
1990 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001991 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1992 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001993 }
1994
John Zulauf86356ca2020-10-19 11:46:41 -06001995 // If there were no transitions skip this global map walk
1996 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001997 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001998 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001999 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002000}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002001
sjfricke0bea06e2022-06-05 09:22:26 +09002002bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002003 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002004 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002005 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002006 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002007 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002008 return skip;
2009 }
sjfricke0bea06e2022-06-05 09:22:26 +09002010 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002011
2012 using DescriptorClass = cvdescriptorset::DescriptorClass;
2013 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2014 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002015 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2016
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002017 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002018 const auto raster_state = pipe->RasterizationState();
2019 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002020 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002021 }
locke-lunarg61870c22020-06-09 14:51:50 -06002022 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002023 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002024 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2025 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002026 SyncStageAccessIndex sync_index =
2027 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2028
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002029 for (uint32_t index = 0; index < binding->count; index++) {
2030 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002031 switch (descriptor->GetClass()) {
2032 case DescriptorClass::ImageSampler:
2033 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002034 if (descriptor->Invalid()) {
2035 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002036 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002037
2038 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2039 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2040 const auto *img_view_state = image_descriptor->GetImageViewState();
2041 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2042
John Zulauf361fb532020-07-22 10:45:39 -06002043 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002044 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2045 // Descriptors, so we do not have to worry about depth slicing here.
2046 // See: VUID 00343
2047 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002048 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002049 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002050
2051 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2052 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2053 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002054 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002055 hazard =
2056 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2057 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002058 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002059 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2060 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002061 }
John Zulauf110413c2021-03-20 05:38:38 -06002062
John Zulauf33fc1d52020-07-17 11:01:10 -06002063 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002064 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002065 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002066 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2067 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002068 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002069 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2070 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2071 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002072 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2073 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002074 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002075 }
2076 break;
2077 }
2078 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002079 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2080 if (texel_descriptor->Invalid()) {
2081 continue;
2082 }
2083 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2084 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002085 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002086 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002087 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002088 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002089 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002090 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002091 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002092 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2093 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2094 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002095 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002096 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002097 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002098 }
2099 break;
2100 }
2101 case DescriptorClass::GeneralBuffer: {
2102 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002103 if (buffer_descriptor->Invalid()) {
2104 continue;
2105 }
2106 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002107 const ResourceAccessRange range =
2108 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002109 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002110 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002111 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002112 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002113 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002114 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002115 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2116 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2117 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002118 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002119 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002120 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002121 }
2122 break;
2123 }
2124 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2125 default:
2126 break;
2127 }
2128 }
2129 }
2130 }
2131 return skip;
2132}
2133
2134void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002135 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002136 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002137 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002138 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002139 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002140 return;
2141 }
2142
2143 using DescriptorClass = cvdescriptorset::DescriptorClass;
2144 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2145 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002146 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2147
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002148 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002149 const auto raster_state = pipe->RasterizationState();
2150 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002151 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002152 }
locke-lunarg61870c22020-06-09 14:51:50 -06002153 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002154 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002155 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2156 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002157 SyncStageAccessIndex sync_index =
2158 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2159
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002160 for (uint32_t i = 0; i < binding->count; i++) {
2161 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002162 switch (descriptor->GetClass()) {
2163 case DescriptorClass::ImageSampler:
2164 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002165 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2166 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2167 if (image_descriptor->Invalid()) {
2168 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002169 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002170 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002171 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2172 // Descriptors, so we do not have to worry about depth slicing here.
2173 // See: VUID 00343
2174 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002175 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002176 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002177 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2178 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2179 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2180 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002181 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002182 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2183 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002184 }
locke-lunarg61870c22020-06-09 14:51:50 -06002185 break;
2186 }
2187 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002188 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2189 if (texel_descriptor->Invalid()) {
2190 continue;
2191 }
2192 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2193 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002194 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002195 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002196 break;
2197 }
2198 case DescriptorClass::GeneralBuffer: {
2199 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002200 if (buffer_descriptor->Invalid()) {
2201 continue;
2202 }
2203 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002204 const ResourceAccessRange range =
2205 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002206 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002207 break;
2208 }
2209 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2210 default:
2211 break;
2212 }
2213 }
2214 }
2215 }
2216}
2217
sjfricke0bea06e2022-06-05 09:22:26 +09002218bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002219 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002220 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002221 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002222 return skip;
2223 }
2224
2225 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2226 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002227 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002228
2229 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002230 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002231 if (binding_description.binding < binding_buffers_size) {
2232 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002233 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002234
locke-lunarg1ae57d62020-11-18 10:49:19 -07002235 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002236 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2237 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002238 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002239 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002240 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002241 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002242 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002243 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2244 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002245 }
2246 }
2247 }
2248 return skip;
2249}
2250
John Zulauf14940722021-04-12 15:19:02 -06002251void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002252 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002253 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002254 return;
2255 }
2256 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2257 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002258 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002259
2260 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002261 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002262 if (binding_description.binding < binding_buffers_size) {
2263 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002264 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002265
locke-lunarg1ae57d62020-11-18 10:49:19 -07002266 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002267 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2268 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002269 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2270 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002271 }
2272 }
2273}
2274
sjfricke0bea06e2022-06-05 09:22:26 +09002275bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002276 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002277 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002278 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002279 }
locke-lunarg61870c22020-06-09 14:51:50 -06002280
locke-lunarg1ae57d62020-11-18 10:49:19 -07002281 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002282 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002283 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2284 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002285 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002286 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002287 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002288 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002289 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2290 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002291 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002292 }
2293
2294 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2295 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002296 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002297 return skip;
2298}
2299
John Zulauf14940722021-04-12 15:19:02 -06002300void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002301 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 -06002302
locke-lunarg1ae57d62020-11-18 10:49:19 -07002303 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002304 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002305 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2306 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002307 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002308
2309 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2310 // We will detect more accurate range in the future.
2311 RecordDrawVertex(UINT32_MAX, 0, tag);
2312}
2313
sjfricke0bea06e2022-06-05 09:22:26 +09002314bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002315 bool skip = false;
2316 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002317 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002318 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002319}
2320
John Zulauf14940722021-04-12 15:19:02 -06002321void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002322 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002323 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002324 }
locke-lunarg61870c22020-06-09 14:51:50 -06002325}
2326
John Zulauf00119522022-05-23 19:07:42 -06002327QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2328
sjfricke0bea06e2022-06-05 09:22:26 +09002329ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002330 const VkRect2D &render_area,
2331 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002332 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002333 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2334 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002335 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002336 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002337 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002338 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002339 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002340}
2341
sjfricke0bea06e2022-06-05 09:22:26 +09002342ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002343 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002344 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002345
sjfricke0bea06e2022-06-05 09:22:26 +09002346 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2347 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2348 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002349
2350 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002351 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002352 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002353}
2354
sjfricke0bea06e2022-06-05 09:22:26 +09002355ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002356 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002357 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002358
sjfricke0bea06e2022-06-05 09:22:26 +09002359 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2360 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002361
2362 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002363 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002364 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002365 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002366}
2367
John Zulauf4a6105a2020-11-17 15:11:05 -07002368void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2369 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002370 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002371 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002372 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002373 }
2374}
2375
John Zulaufae842002021-04-15 18:20:55 -06002376// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002377bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002378 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002379 if (!exec_context.ValidForSyncOps()) return false;
2380
2381 const QueueId queue_id = exec_context.GetQueueId();
2382 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002383 bool skip = false;
2384 ResourceUsageRange tag_range = {0, 0};
2385 const AccessContext *recorded_context = GetCurrentAccessContext();
2386 assert(recorded_context);
2387 HazardResult hazard;
John Zulaufdab327f2022-07-08 12:02:05 -06002388 ReplayGuard replay_guard(exec_context, *this);
2389
John Zulaufbb890452021-12-14 11:30:18 -07002390 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002391 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002392 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002393 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002394 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002395 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002396 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2397 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002398 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002399 };
2400 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002401 // we update the range to any include layout transition first use writes,
2402 // as they are stored along with the source scope (as effective barrier) when recorded
2403 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002404 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002405
John Zulauf0223f142022-07-06 09:05:39 -06002406 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2407 // we need to fetch the current access context each time
John Zulaufdab327f2022-07-08 12:02:05 -06002408 hazard = exec_context.DetectFirstUseHazard(tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002409 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002410 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002411 }
2412 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002413 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002414 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002415 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002416 }
2417
2418 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002419 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002420 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002421 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002422 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002423 }
2424
2425 return skip;
2426}
2427
sjfricke0bea06e2022-06-05 09:22:26 +09002428void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002429 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2430 assert(recorded_context);
2431
2432 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2433 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002434 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002435 // we update the range to any include layout transition first use writes,
2436 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002437 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002438 }
2439
2440 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2441 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002442 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002443}
2444
John Zulauf1d5f9c12022-05-13 14:51:08 -06002445void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002446 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002447 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002448}
2449
John Zulaufdab327f2022-07-08 12:02:05 -06002450HazardResult CommandBufferAccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
2451 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, *GetCurrentAccessContext());
2452}
2453
John Zulauf3c788ef2022-02-22 12:12:30 -07002454ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002455 // The execution references ensure lifespan for the referenced child CB's...
2456 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002457 InsertRecordedAccessLogEntries(recorded_context);
2458 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002459 return tag_range;
2460}
2461
John Zulauf3c788ef2022-02-22 12:12:30 -07002462void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2463 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2464 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2465}
2466
John Zulauf41a9c7c2021-12-07 15:59:53 -07002467ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2468 ResourceUsageTag next = access_log_.size();
2469 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2470 return next;
2471}
2472
2473ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2474 command_number_++;
2475 subcommand_number_ = 0;
2476 ResourceUsageTag next = access_log_.size();
2477 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2478 return next;
2479}
2480
2481ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2482 if (index == 0) {
2483 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2484 }
2485 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2486}
2487
John Zulaufbb890452021-12-14 11:30:18 -07002488void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2489 auto tag = sync_op->Record(this);
2490 // As renderpass operations can have side effects on the command buffer access context,
2491 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002492 sync_ops_.emplace_back(tag, std::move(sync_op));
2493}
2494
John Zulaufae842002021-04-15 18:20:55 -06002495class HazardDetectFirstUse {
2496 public:
John Zulauf0223f142022-07-06 09:05:39 -06002497 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2498 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002499 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002500 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002501 }
2502 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2503 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2504 }
2505
2506 private:
2507 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002508 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002509 const ResourceUsageRange &tag_range_;
2510};
2511
2512// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2513// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002514HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002515 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002516 HazardResult hazard;
2517 for (const auto address_type : kAddressTypes) {
2518 const auto &recorded_access_map = GetAccessStateMap(address_type);
2519 for (const auto &recorded_access : recorded_access_map) {
2520 // Cull any entries not in the current tag range
2521 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002522 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002523 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2524 if (hazard.hazard) break;
2525 }
2526 }
2527
2528 return hazard;
2529}
2530
John Zulaufbb890452021-12-14 11:30:18 -07002531bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002532 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002533 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002534 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002535 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002536 if (!pipe) {
2537 return skip;
2538 }
2539
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002540 const auto raster_state = pipe->RasterizationState();
2541 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002542 return skip;
2543 }
sjfricke0bea06e2022-06-05 09:22:26 +09002544 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002545 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002546 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002547
John Zulauf1a224292020-06-30 14:52:13 -06002548 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002549 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002550 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2551 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002552 if (location >= subpass.colorAttachmentCount ||
2553 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002554 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002555 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002556 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2557 if (!view_gen.IsValid()) continue;
2558 HazardResult hazard =
2559 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2560 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002561 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002562 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002563 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002564 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002565 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002566 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002567 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2568 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002569 }
2570 }
2571 }
locke-lunarg37047832020-06-12 13:44:45 -06002572
2573 // PHASE1 TODO: Add layout based read/vs. write selection.
2574 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002575 const auto ds_state = pipe->DepthStencilState();
2576 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002577
2578 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2579 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2580 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002581 bool depth_write = false, stencil_write = false;
2582
2583 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002584 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002585 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2586 depth_write = true;
2587 }
2588 // PHASE1 TODO: It needs to check if stencil is writable.
2589 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2590 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2591 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002592 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002593 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2594 stencil_write = true;
2595 }
2596
2597 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2598 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002599 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2600 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2601 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002602 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002603 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002604 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002605 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002606 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002607 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002608 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002609 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002610 }
2611 }
2612 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002613 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2614 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2615 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002616 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002617 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002618 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002619 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002620 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002621 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002622 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002623 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002624 }
locke-lunarg61870c22020-06-09 14:51:50 -06002625 }
2626 }
2627 return skip;
2628}
2629
sjfricke0bea06e2022-06-05 09:22:26 +09002630void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2631 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002632 if (!pipe) {
2633 return;
2634 }
2635
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002636 const auto *raster_state = pipe->RasterizationState();
2637 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002638 return;
2639 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002640 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002641 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002642
John Zulauf1a224292020-06-30 14:52:13 -06002643 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002644 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002645 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2646 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002647 if (location >= subpass.colorAttachmentCount ||
2648 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002649 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002650 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002651 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2652 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2653 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2654 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002655 }
2656 }
locke-lunarg37047832020-06-12 13:44:45 -06002657
2658 // PHASE1 TODO: Add layout based read/vs. write selection.
2659 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002660 const auto *ds_state = pipe->DepthStencilState();
2661 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002662 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2663 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2664 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002665 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002666 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2667 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002668
2669 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002670 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2671 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002672 depth_write = true;
2673 }
2674 // PHASE1 TODO: It needs to check if stencil is writable.
2675 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2676 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2677 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002678 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002679 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2680 stencil_write = true;
2681 }
2682
John Zulaufd0ec59f2021-03-13 14:25:08 -07002683 if (depth_write || stencil_write) {
2684 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2685 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2686 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2687 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002688 }
locke-lunarg61870c22020-06-09 14:51:50 -06002689 }
2690}
2691
sjfricke0bea06e2022-06-05 09:22:26 +09002692bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002693 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002694 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002695 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002696 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002697 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002698 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002699
John Zulauf355e49b2020-04-24 15:11:15 -06002700 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002701 if (next_subpass >= subpass_contexts_.size()) {
2702 return skip;
2703 }
John Zulauf1507ee42020-05-18 11:33:09 -06002704 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002705 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002706 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002707 if (!skip) {
2708 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2709 // on a copy of the (empty) next context.
2710 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2711 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002712 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002713 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002714 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002715 }
John Zulauf7635de32020-05-29 17:14:15 -06002716 return skip;
2717}
sjfricke0bea06e2022-06-05 09:22:26 +09002718bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002719 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002720 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002721 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002722 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002723 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2724 cmd_type);
2725 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002726 return skip;
2727}
2728
John Zulauf64ffe552021-02-06 10:25:07 -07002729AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002730 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002731}
2732
John Zulaufbb890452021-12-14 11:30:18 -07002733bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002734 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002735 bool skip = false;
2736
John Zulauf7635de32020-05-29 17:14:15 -06002737 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2738 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2739 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2740 // to apply and only copy then, if this proves a hot spot.
2741 std::unique_ptr<AccessContext> proxy_for_current;
2742
John Zulauf355e49b2020-04-24 15:11:15 -06002743 // Validate the "finalLayout" transitions to external
2744 // Get them from where there we're hidding in the extra entry.
2745 const auto &final_transitions = rp_state_->subpass_transitions.back();
2746 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002747 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002748 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002749 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2750 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002751
2752 if (transition.prev_pass == current_subpass_) {
2753 if (!proxy_for_current) {
2754 // 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 -07002755 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002756 }
2757 context = proxy_for_current.get();
2758 }
2759
John Zulaufa0a98292020-09-18 09:30:10 -06002760 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2761 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002762 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002763 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002764 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002765 if (hazard.tag == kInvalidTag) {
2766 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002767 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002768 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2769 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2770 " final image layout transition (old_layout: %s, new_layout: %s).",
2771 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2772 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2773 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002774 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002775 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2776 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2777 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2778 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2779 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002780 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002781 }
John Zulauf355e49b2020-04-24 15:11:15 -06002782 }
2783 }
2784 return skip;
2785}
2786
John Zulauf14940722021-04-12 15:19:02 -06002787void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002788 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002789 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002790}
2791
John Zulauf14940722021-04-12 15:19:02 -06002792void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002793 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2794 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002795
2796 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2797 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002798 const AttachmentViewGen &view_gen = attachment_views_[i];
2799 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002800
2801 const auto &ci = attachment_ci[i];
2802 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002803 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002804 const bool is_color = !(has_depth || has_stencil);
2805
2806 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002807 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2808 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2809 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2810 SyncOrdering::kColorAttachment, tag);
2811 }
John Zulauf1507ee42020-05-18 11:33:09 -06002812 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002813 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002814 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2815 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2816 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2817 SyncOrdering::kDepthStencilAttachment, tag);
2818 }
John Zulauf1507ee42020-05-18 11:33:09 -06002819 }
2820 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002821 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2822 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2823 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2824 SyncOrdering::kDepthStencilAttachment, tag);
2825 }
John Zulauf1507ee42020-05-18 11:33:09 -06002826 }
2827 }
2828 }
2829 }
2830}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002831AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2832 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2833 AttachmentViewGenVector view_gens;
2834 VkExtent3D extent = CastTo3D(render_area.extent);
2835 VkOffset3D offset = CastTo3D(render_area.offset);
2836 view_gens.reserve(attachment_views.size());
2837 for (const auto *view : attachment_views) {
2838 view_gens.emplace_back(view, offset, extent);
2839 }
2840 return view_gens;
2841}
John Zulauf64ffe552021-02-06 10:25:07 -07002842RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2843 VkQueueFlags queue_flags,
2844 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2845 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002846 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulaufdab327f2022-07-08 12:02:05 -06002847 // Add this for all subpasses here so that they exist during next subpass validation
2848 InitSubpassContexts(queue_flags, rp_state, external_context, subpass_contexts_);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002849 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002850}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002851void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002852 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002853 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2854 RecordLayoutTransitions(barrier_tag);
2855 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002856}
John Zulauf1507ee42020-05-18 11:33:09 -06002857
John Zulauf41a9c7c2021-12-07 15:59:53 -07002858void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2859 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002860 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002861 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2862 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002863
ziga-lunarg31a3e772022-03-22 11:48:46 +01002864 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2865 return;
2866 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002867 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2868 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002869 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002870 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2871 RecordLayoutTransitions(barrier_tag);
2872 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002873}
2874
John Zulauf41a9c7c2021-12-07 15:59:53 -07002875void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2876 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002877 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002878 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2879 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002880
John Zulauf355e49b2020-04-24 15:11:15 -06002881 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002882 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002883
2884 // Add the "finalLayout" transitions to external
2885 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002886 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2887 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2888 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002889 const auto &final_transitions = rp_state_->subpass_transitions.back();
2890 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002891 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002892 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002893 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002894 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002895 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002896 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002897 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002898 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002899 }
2900}
2901
John Zulauf06f6f1e2022-04-19 15:28:11 -06002902SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2903 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002904 SyncExecScope result;
2905 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002906 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002907 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002908 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002909 return result;
2910}
2911
Jeremy Gebben40a22942020-12-22 14:22:06 -07002912SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002913 SyncExecScope result;
2914 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002915 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2916 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002917 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002918 return result;
2919}
2920
John Zulaufecf4ac52022-06-06 10:08:42 -06002921SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2922 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2923
2924SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2925 : src_exec_scope(src), src_access_scope(src.valid_accesses), dst_exec_scope(dst), dst_access_scope(src.valid_accesses) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002926
2927template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002928SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2929 : src_exec_scope(src),
2930 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2931 dst_exec_scope(dst),
2932 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002933
2934SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002935 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2936 if (barrier) {
2937 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002938 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002939 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002940
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002941 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002942 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002943 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2944
2945 } else {
2946 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002947 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002948 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2949
2950 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002951 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002952 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2953 }
2954}
2955
2956template <typename Barrier>
2957SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2958 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2959 src_exec_scope = src.exec_scope;
2960 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2961
2962 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002963 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002964 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002965}
2966
John Zulaufb02c1eb2020-10-06 16:33:36 -06002967// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2968void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002969 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002970 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002971 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002972 }
2973}
2974
John Zulauf89311b42020-09-29 16:28:47 -06002975// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2976// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2977// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002978void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002979 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002980 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002981 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002982 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002983 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002984 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002985 }
John Zulaufbb890452021-12-14 11:30:18 -07002986 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002987}
John Zulauf9cb530d2019-09-30 14:14:10 -06002988HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2989 HazardResult hazard;
2990 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002991 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002992 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002993 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002994 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002995 }
2996 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002997 // Write operation:
2998 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2999 // If reads exists -- test only against them because either:
3000 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
3001 // * 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
3002 // the current write happens after the reads, so just test the write against the reades
3003 // Otherwise test against last_write
3004 //
3005 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003006 if (last_reads.size()) {
3007 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003008 if (IsReadHazard(usage_stage, read_access)) {
3009 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3010 break;
3011 }
3012 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003013 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003014 // Write-After-Write check -- if we have a previous write to test against
3015 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003016 }
3017 }
3018 return hazard;
3019}
3020
John Zulaufec943ec2022-06-29 07:52:56 -06003021HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3022 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003023 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003024 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003025}
3026
John Zulaufec943ec2022-06-29 07:52:56 -06003027HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3028 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003029 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3030 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003031 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003032 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003033 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003034 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003035 if (IsRead(usage_bit)) {
3036 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3037 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3038 if (is_raw_hazard) {
3039 // NOTE: we know last_write is non-zero
3040 // See if the ordering rules save us from the simple RAW check above
3041 // First check to see if the current usage is covered by the ordering rules
3042 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3043 const bool usage_is_ordered =
3044 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3045 if (usage_is_ordered) {
3046 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003047 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003048 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003049 }
3050 }
John Zulauf4285ee92020-09-23 10:20:52 -06003051 if (is_raw_hazard) {
3052 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3053 }
John Zulauf5c628d02021-05-04 15:46:36 -06003054 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3055 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003056 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003057 } else {
3058 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003059 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003060 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003061 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003062 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003063 if (usage_write_is_ordered) {
3064 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003065 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003066 }
3067 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3068 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003069 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003070 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3071 if (IsReadHazard(usage_stage, read_access)) {
3072 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3073 break;
3074 }
John Zulaufd14743a2020-07-03 09:42:39 -06003075 }
3076 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003077 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3078 bool ilt_ilt_hazard = false;
3079 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3080 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3081 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3082 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3083 }
3084 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003085 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003086 }
John Zulauf69133422020-05-20 14:55:53 -06003087 }
3088 }
3089 return hazard;
3090}
3091
John Zulaufec943ec2022-06-29 07:52:56 -06003092HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3093 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003094 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003095 using Size = FirstAccesses::size_type;
3096 const auto &recorded_accesses = recorded_use.first_accesses_;
3097 Size count = recorded_accesses.size();
3098 if (count) {
3099 const auto &last_access = recorded_accesses.back();
3100 bool do_write_last = IsWrite(last_access.usage_index);
3101 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003102
John Zulauf4fa68462021-04-26 21:04:22 -06003103 for (Size i = 0; i < count; ++count) {
3104 const auto &first = recorded_accesses[i];
3105 // Skip and quit logic
3106 if (first.tag < tag_range.begin) continue;
3107 if (first.tag >= tag_range.end) {
3108 do_write_last = false; // ignore last since we know it can't be in tag_range
3109 break;
3110 }
3111
John Zulaufec943ec2022-06-29 07:52:56 -06003112 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003113 if (hazard.hazard) {
3114 hazard.AddRecordedAccess(first);
3115 break;
3116 }
3117 }
3118
3119 if (do_write_last && tag_range.includes(last_access.tag)) {
3120 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3121 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3122 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3123 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3124 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3125 // the barrier that applies them
3126 barrier |= recorded_use.first_write_layout_ordering_;
3127 }
3128 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3129 // the active context
3130 if (recorded_use.first_read_stages_) {
3131 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3132 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3133 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3134 // active context.
3135 barrier.exec_scope |= recorded_use.first_read_stages_;
3136 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3137 barrier.access_scope |= FlagBit(last_access.usage_index);
3138 }
John Zulaufec943ec2022-06-29 07:52:56 -06003139 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003140 if (hazard.hazard) {
3141 hazard.AddRecordedAccess(last_access);
3142 }
3143 }
John Zulaufae842002021-04-15 18:20:55 -06003144 }
3145 return hazard;
3146}
3147
John Zulauf2f952d22020-02-10 11:34:51 -07003148// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003149HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003150 HazardResult hazard;
3151 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003152 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3153 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3154 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003155 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003156 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003157 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003158 }
3159 } else {
John Zulauf14940722021-04-12 15:19:02 -06003160 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003161 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003162 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003163 // 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 -07003164 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003165 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003166 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003167 break;
3168 }
3169 }
John Zulauf2f952d22020-02-10 11:34:51 -07003170 }
3171 }
3172 return hazard;
3173}
3174
John Zulaufae842002021-04-15 18:20:55 -06003175HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3176 ResourceUsageTag start_tag) const {
3177 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003178 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003179 // Skip and quit logic
3180 if (first.tag < tag_range.begin) continue;
3181 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003182
3183 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003184 if (hazard.hazard) {
3185 hazard.AddRecordedAccess(first);
3186 break;
3187 }
John Zulaufae842002021-04-15 18:20:55 -06003188 }
3189 return hazard;
3190}
3191
John Zulaufec943ec2022-06-29 07:52:56 -06003192HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3193 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003194 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003195 // Only supporting image layout transitions for now
3196 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3197 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003198 // only test for WAW if there no intervening read operations.
3199 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003200 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003201 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003202 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003203 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003204 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003205 break;
3206 }
3207 }
John Zulaufec943ec2022-06-29 07:52:56 -06003208 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003209 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3210 }
3211
3212 return hazard;
3213}
3214
John Zulaufe0757ba2022-06-10 16:51:45 -06003215HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3216 VkPipelineStageFlags2KHR src_exec_scope,
3217 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3218 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003219 // Only supporting image layout transitions for now
3220 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3221 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003222
John Zulaufe0757ba2022-06-10 16:51:45 -06003223 if ((write_tag >= event_tag) && last_write.any()) {
3224 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3225 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3226 } else {
3227 // only test for WAW if there no intervening read operations.
3228 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3229 if (last_reads.size()) {
3230 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3231 // first scope, or they are a hazard.
3232 const ReadStates &scope_reads = scope_state.last_reads;
3233 const ReadStates::size_type scope_read_count = scope_reads.size();
3234 // Since the hasn't been a write:
3235 // * The current read state is a superset of the scoped one
3236 // * The stage order is the same.
3237 assert(last_reads.size() >= scope_read_count);
3238 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3239 const ReadState &scope_read = scope_reads[read_idx];
3240 const ReadState &current_read = last_reads[read_idx];
3241 assert(scope_read.stage == current_read.stage);
3242 if (current_read.tag > event_tag) {
3243 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3244 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3245 } else {
3246 // The read is in the events first synchronization scope, so we use a barrier hazard check
3247 // If the read stage is not in the src sync scope
3248 // *AND* not execution chained with an existing sync barrier (that's the or)
3249 // then the barrier access is unsafe (R/W after R)
3250 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3251 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3252 break;
3253 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003254 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003255 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003256 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3257 const ReadState &current_read = last_reads[scope_read_count];
3258 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3259 }
3260 } else if (last_write.any()) {
3261 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
John Zulauf4a6105a2020-11-17 15:11:05 -07003262 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3263 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003264 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3265 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003266 }
John Zulauf361fb532020-07-22 10:45:39 -06003267 }
John Zulaufd14743a2020-07-03 09:42:39 -06003268 }
John Zulauf361fb532020-07-22 10:45:39 -06003269
John Zulauf0cb5be22020-01-23 12:18:22 -07003270 return hazard;
3271}
3272
John Zulauf5f13a792020-03-10 07:31:21 -06003273// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3274// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3275// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3276void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003277 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003278 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3279 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003280 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003281 } else if (other.write_tag == write_tag) {
3282 // 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 -06003283 // dependency chaining logic or any stage expansion)
3284 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003285 pending_write_barriers |= other.pending_write_barriers;
3286 pending_layout_transition |= other.pending_layout_transition;
3287 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003288 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003289
John Zulaufd14743a2020-07-03 09:42:39 -06003290 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003291 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003292 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003293 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003294 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003295 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003296 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003297 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3298 // but we should wait on profiling data for that.
3299 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003300 auto &my_read = last_reads[my_read_index];
3301 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003302 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003303 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003304 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003305 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003306 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003307 my_read.pending_dep_chain = other_read.pending_dep_chain;
3308 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3309 // May require tracking more than one access per stage.
3310 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003311 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003312 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003313 // Since I'm overwriting the fragement stage read, also update the input attachment info
3314 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003315 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003316 }
John Zulauf14940722021-04-12 15:19:02 -06003317 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003318 // The read tags match so merge the barriers
3319 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003320 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003321 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003322 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003323
John Zulauf5f13a792020-03-10 07:31:21 -06003324 break;
3325 }
3326 }
3327 } else {
3328 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003329 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003330 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003331 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003332 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003333 }
John Zulauf5f13a792020-03-10 07:31:21 -06003334 }
3335 }
John Zulauf361fb532020-07-22 10:45:39 -06003336 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003337 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3338 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003339
3340 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3341 // of the copy and other into this using the update first logic.
3342 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3343 // of the other first_accesses... )
3344 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3345 FirstAccesses firsts(std::move(first_accesses_));
3346 first_accesses_.clear();
3347 first_read_stages_ = 0U;
3348 auto a = firsts.begin();
3349 auto a_end = firsts.end();
3350 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003351 // TODO: Determine whether some tag offset will be needed for PHASE II
3352 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003353 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3354 ++a;
3355 }
3356 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3357 }
3358 for (; a != a_end; ++a) {
3359 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3360 }
3361 }
John Zulauf5f13a792020-03-10 07:31:21 -06003362}
3363
John Zulauf14940722021-04-12 15:19:02 -06003364void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003365 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3366 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003367 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003368 // Mulitple outstanding reads may be of interest and do dependency chains independently
3369 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3370 const auto usage_stage = PipelineStageBit(usage_index);
3371 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003372 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003373 for (auto &read_access : last_reads) {
3374 if (read_access.stage == usage_stage) {
3375 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003376 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003377 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003378 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003379 } else {
3380 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3381 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3382 // that sync_stages is a subset of barriers may not apply.
3383 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003384 }
3385 }
3386 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003387 for (auto &read_access : last_reads) {
3388 if (read_access.barriers & usage_stage) {
3389 read_access.sync_stages |= usage_stage;
3390 }
3391 }
John Zulaufab7756b2020-12-29 16:10:16 -07003392 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003393 last_read_stages |= usage_stage;
3394 }
John Zulauf4285ee92020-09-23 10:20:52 -06003395
3396 // 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 -07003397 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003398 // TODO Revisit re: multiple reads for a given stage
3399 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003400 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003401 } else {
3402 // Assume write
3403 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003404 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003405 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003406 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003407}
John Zulauf5f13a792020-03-10 07:31:21 -06003408
John Zulauf89311b42020-09-29 16:28:47 -06003409// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3410// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3411// We can overwrite them as *this* write is now after them.
3412//
3413// 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 -06003414void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003415 ClearRead();
3416 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003417 write_tag = tag;
3418 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003419}
3420
John Zulauf1d5f9c12022-05-13 14:51:08 -06003421void ResourceAccessState::ClearWrite() {
3422 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3423 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3424 write_barriers.reset();
3425 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3426 last_write.reset();
3427
3428 write_tag = 0;
3429 write_queue = QueueSyncState::kQueueIdInvalid;
3430}
3431
3432void ResourceAccessState::ClearRead() {
3433 last_reads.clear();
3434 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3435}
3436
John Zulauf89311b42020-09-29 16:28:47 -06003437// Apply the memory barrier without updating the existing barriers. The execution barrier
3438// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3439// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3440// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003441template <typename ScopeOps>
3442void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003443 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3444 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003445 // 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 -06003446 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003447 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3448 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003449 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003450 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003451 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003452 if (layout_transition) {
3453 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3454 }
John Zulaufa0a98292020-09-18 09:30:10 -06003455 }
John Zulauf89311b42020-09-29 16:28:47 -06003456 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3457 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003458
John Zulauf89311b42020-09-29 16:28:47 -06003459 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003460 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3461 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003462 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3463
John Zulaufab7756b2020-12-29 16:10:16 -07003464 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003465 // 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 -06003466 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003467 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3468 stages_in_scope |= read_access.stage;
3469 }
3470 }
3471
3472 for (auto &read_access : last_reads) {
3473 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3474 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3475 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3476 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003477 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003478 }
3479 }
John Zulaufa0a98292020-09-18 09:30:10 -06003480 }
John Zulaufa0a98292020-09-18 09:30:10 -06003481}
3482
John Zulauf14940722021-04-12 15:19:02 -06003483void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003484 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003485 // 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 -06003486 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003487 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003488 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3489 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003490 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003491 }
John Zulauf89311b42020-09-29 16:28:47 -06003492
3493 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003494 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003495 for (auto &read_access : last_reads) {
3496 read_access.barriers |= read_access.pending_dep_chain;
3497 read_execution_barriers |= read_access.barriers;
3498 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003499 }
3500
3501 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3502 write_dependency_chain |= pending_write_dep_chain;
3503 write_barriers |= pending_write_barriers;
3504 pending_write_dep_chain = 0;
3505 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003506}
3507
John Zulaufecf4ac52022-06-06 10:08:42 -06003508// Assumes signal queue != wait queue
3509void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3510 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3511 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3512 assert(signal.queue != wait.queue);
3513 for (auto &read_access : last_reads) {
3514 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3515 // Deflects WAR on wait queue
3516 read_access.barriers = wait.exec_scope;
3517 } else {
3518 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3519 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3520 }
3521 }
3522 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3523 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3524 read_execution_barriers = wait.exec_scope;
3525 write_barriers = wait.valid_accesses;
3526 } else {
3527 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3528 write_barriers.reset();
3529 }
3530 write_dependency_chain = read_execution_barriers;
3531}
3532
John Zulauf3da08bb2022-08-01 17:56:56 -06003533bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) const {
3534 return (usage_queue == queue) && (usage_tag <= tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003535}
3536
John Zulauf3da08bb2022-08-01 17:56:56 -06003537bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) const { return queue == usage_queue; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003538
John Zulauf3da08bb2022-08-01 17:56:56 -06003539bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) const { return tag <= usage_tag; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003540
3541// Return if the resulting state is "empty"
3542template <typename Pred>
3543bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3544 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3545
3546 // Use the predicate to build a mask of the read stages we are synchronizing
3547 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003548 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003549 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003550 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3551 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003552 }
3553 }
3554
John Zulauf434c4e62022-05-19 16:03:56 -06003555 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3556 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3557 uint32_t unsync_count = 0;
3558 for (auto &read_access : last_reads) {
3559 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3560 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3561 sync_reads |= read_access.stage;
3562 } else {
3563 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003564 }
3565 }
3566
3567 if (unsync_count) {
3568 if (sync_reads) {
3569 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3570 ReadStates unsync_reads;
3571 unsync_reads.reserve(unsync_count);
3572 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3573 for (auto &read_access : last_reads) {
3574 if (0 == (read_access.stage & sync_reads)) {
3575 unsync_reads.emplace_back(read_access);
3576 unsync_read_stages |= read_access.stage;
3577 }
3578 }
3579 last_read_stages = unsync_read_stages;
3580 last_reads = std::move(unsync_reads);
3581 }
3582 } else {
3583 // Nothing remains (or it was empty to begin with)
3584 ClearRead();
3585 }
3586
3587 bool all_clear = last_reads.size() == 0;
3588 if (last_write.any()) {
3589 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3590 // Clear any predicated write, or any the write from any any access with synchronized reads.
3591 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3592 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3593 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3594 ClearWrite();
3595 } else {
3596 all_clear = false;
3597 }
3598 }
3599 return all_clear;
3600}
3601
John Zulaufae842002021-04-15 18:20:55 -06003602bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3603 if (!first_accesses_.size()) return false;
3604 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3605 return tag_range.intersects(first_access_range);
3606}
3607
John Zulauf1d5f9c12022-05-13 14:51:08 -06003608void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3609 if (last_write.any()) write_tag += offset;
3610 for (auto &read_access : last_reads) {
3611 read_access.tag += offset;
3612 }
3613 for (auto &first : first_accesses_) {
3614 first.tag += offset;
3615 }
3616}
3617
3618ResourceAccessState::ResourceAccessState()
3619 : write_barriers(~SyncStageAccessFlags(0)),
3620 write_dependency_chain(0),
3621 write_tag(),
3622 write_queue(QueueSyncState::kQueueIdInvalid),
3623 last_write(0),
3624 input_attachment_read(false),
3625 last_read_stages(0),
3626 read_execution_barriers(0),
3627 pending_write_dep_chain(0),
3628 pending_layout_transition(false),
3629 pending_write_barriers(0),
3630 pending_layout_ordering_(),
3631 first_accesses_(),
3632 first_read_stages_(0U),
3633 first_write_layout_ordering_() {}
3634
John Zulauf59e25072020-07-17 10:55:21 -06003635// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003636VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3637 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003638
John Zulaufab7756b2020-12-29 16:10:16 -07003639 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003640 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003641 barriers = read_access.barriers;
3642 break;
John Zulauf59e25072020-07-17 10:55:21 -06003643 }
3644 }
John Zulauf4285ee92020-09-23 10:20:52 -06003645
John Zulauf59e25072020-07-17 10:55:21 -06003646 return barriers;
3647}
3648
John Zulauf1d5f9c12022-05-13 14:51:08 -06003649void ResourceAccessState::SetQueueId(QueueId id) {
3650 for (auto &read_access : last_reads) {
3651 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3652 read_access.queue = id;
3653 }
3654 }
3655 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3656 write_queue = id;
3657 }
3658}
3659
John Zulauf00119522022-05-23 19:07:42 -06003660bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3661 return 0 != (write_dependency_chain & src_exec_scope);
3662}
3663
3664bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3665 return (src_access_scope & last_write).any();
3666}
3667
John Zulaufec943ec2022-06-29 07:52:56 -06003668bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3669 return (write_barriers & src_access_scope).any();
3670}
3671
John Zulaufb7578302022-05-19 13:50:18 -06003672bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3673 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003674 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3675}
3676
3677bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3678 SyncStageAccessFlags src_access_scope) const {
3679 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003680}
3681
John Zulaufe0757ba2022-06-10 16:51:45 -06003682bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3683 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003684 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3685 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3686 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003687 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003688}
3689
John Zulaufec943ec2022-06-29 07:52:56 -06003690bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3691 const SyncStageAccessFlags &src_access_scope) const {
3692 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3693}
3694
John Zulaufcb7e1672022-05-04 13:46:08 -06003695bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003696 assert(IsRead(usage));
3697 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3698 // * the previous reads are not hazards, and thus last_write must be visible and available to
3699 // any reads that happen after.
3700 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3701 // 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 -07003702 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003703}
3704
John Zulaufec943ec2022-06-29 07:52:56 -06003705VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3706 // At apply queue submission order limits on the effect of ordering
3707 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3708 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3709 for (const auto &read_access : last_reads) {
3710 if (read_access.queue != queue_id) {
3711 non_qso_stages |= read_access.stage;
3712 }
3713 }
3714 }
John Zulauf4285ee92020-09-23 10:20:52 -06003715 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003716 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3717 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003718 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003719 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003720 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003721 // 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 -07003722 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003723 }
3724
3725 return ordered_stages;
3726}
3727
John Zulauf14940722021-04-12 15:19:02 -06003728void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003729 // Only record until we record a write.
3730 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003731 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003732 if (0 == (usage_stage & first_read_stages_)) {
3733 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003734 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003735 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003736 if (0 == (read_execution_barriers & usage_stage)) {
3737 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3738 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3739 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003740 }
3741 }
3742}
3743
John Zulauf4fa68462021-04-26 21:04:22 -06003744void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3745 // Only call this after recording an image layout transition
3746 assert(first_accesses_.size());
3747 if (first_accesses_.back().tag == tag) {
3748 // 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 +02003749 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003750 first_write_layout_ordering_ = layout_ordering;
3751 }
3752}
3753
John Zulauf1d5f9c12022-05-13 14:51:08 -06003754ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3755 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3756 : stage(stage_),
3757 access(access_),
3758 barriers(barriers_),
3759 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3760 tag(tag_),
3761 queue(QueueSyncState::kQueueIdInvalid),
3762 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3763
John Zulaufee984022022-04-13 16:39:50 -06003764void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3765 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3766 stage = stage_;
3767 access = access_;
3768 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003769 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003770 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003771 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 -06003772}
3773
John Zulauf00119522022-05-23 19:07:42 -06003774// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3775// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3776// that have bee applied (via semaphore) to those accesses can be chained off of.
3777bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3778 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3779 return (exec_scope & effective_stages) != 0;
3780}
3781
John Zulauf697c0e12022-04-19 16:31:12 -06003782ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3783 ResourceUsageRange reserve;
3784 reserve.begin = tag_limit_.fetch_add(tag_count);
3785 reserve.end = reserve.begin + tag_count;
3786 return reserve;
3787}
3788
John Zulauf3da08bb2022-08-01 17:56:56 -06003789void SyncValidator::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
3790 // We need to go through every queue batch context and clear all accesses this wait synchronizes
3791 // As usual -- two groups, the "last batch" and the signaled semaphores
3792 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
3793 // QueueBatchContext, track which we've done to avoid duplicate traversals
3794 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
3795 for (auto &batch : queue_batch_contexts) {
3796 batch->ApplyTaggedWait(queue_id, tag);
3797 }
3798}
3799
3800void SyncValidator::UpdateFenceWaitInfo(VkFence fence, QueueId queue_id, ResourceUsageTag tag) {
3801 if (fence != VK_NULL_HANDLE) {
3802 // Overwrite the current fence wait information
3803 // NOTE: Not doing fence usage validation here, leaving that in CoreChecks intentionally
3804 auto fence_state = Get<FENCE_STATE>(fence);
3805 waitable_fences_[fence] = {fence_state, tag, queue_id};
3806 }
3807}
3808
3809void SyncValidator::WaitForFence(VkFence fence) {
3810 auto fence_it = waitable_fences_.find(fence);
3811 if (fence_it != waitable_fences_.end()) {
3812 // The fence may no longer be waitable for several valid reasons.
3813 FenceSyncState &wait_for = fence_it->second;
3814 ApplyTaggedWait(wait_for.queue_id, wait_for.tag);
3815 waitable_fences_.erase(fence_it);
3816 }
3817}
3818
John Zulaufbbda4572022-04-19 16:20:45 -06003819const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3820 return GetMappedPlainFromShared(queue_sync_states_, queue);
3821}
3822
3823QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3824
3825std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3826 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3827}
3828
3829std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3830 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3831}
3832
John Zulaufe0757ba2022-06-10 16:51:45 -06003833template <typename T>
3834struct GetBatchTraits {};
3835template <>
3836struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3837 using Batch = std::shared_ptr<QueueBatchContext>;
3838 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3839};
3840
3841template <>
3842struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3843 using Batch = std::shared_ptr<QueueBatchContext>;
3844 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3845};
3846
3847template <typename BatchSet, typename Map, typename Predicate>
3848static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003849 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003850 for (auto &entry : map) {
3851 // Intentional copy
3852 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003853 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003854 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003855 return snapshot;
3856}
3857
3858template <typename Predicate>
3859QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003860 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003861}
3862
3863template <typename Predicate>
3864QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003865 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3866}
3867
3868QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3869 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3870 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3871 if (batch && !layer_data::Contains(snapshot, batch)) {
3872 snapshot.emplace(batch);
3873 }
3874 return false;
3875 };
3876 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3877 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003878}
3879
John Zulaufcb7e1672022-05-04 13:46:08 -06003880bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3881 const std::shared_ptr<QueueBatchContext> &batch,
3882 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003883 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003884 const SyncExecScope exec_scope =
3885 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3886 const VkSemaphore sem = sem_state->semaphore();
3887 auto signal_it = signaled_.find(sem);
3888 std::shared_ptr<Signal> insert_signal;
3889 if (signal_it == signaled_.end()) {
3890 if (prev_) {
3891 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3892 if (prev_sig) {
3893 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3894 insert_signal = std::make_shared<Signal>(*prev_sig);
3895 }
3896 }
3897 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3898 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003899 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003900
3901 bool success = false;
3902 if (!signal_it->second) {
3903 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3904 success = true;
3905 }
3906
3907 return success;
3908}
3909
John Zulaufecf4ac52022-06-06 10:08:42 -06003910std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3911 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003912 const auto found_it = signaled_.find(sem);
3913 if (found_it != signaled_.end()) {
3914 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3915 // a bit.
3916 unsignaled = std::move(found_it->second);
3917 if (!prev_) {
3918 // No parent, not need to keep the entry
3919 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3920 signaled_.erase(found_it);
3921 }
3922 } else if (prev_) {
3923 // We can't unsignal prev_ because it's const * by design.
3924 // We put in an empty placeholder
3925 signaled_.emplace(sem, std::shared_ptr<Signal>());
3926 unsignaled = GetPrev(sem);
3927 }
3928 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3929 // but CoreChecks should have reported it
3930
3931 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003932 return unsignaled;
3933}
3934
John Zulaufcb7e1672022-05-04 13:46:08 -06003935void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3936 // Overwrite the s tate with the last state from this
3937 if (from) {
3938 assert(sem == from->sem_state->semaphore());
3939 signaled_[sem] = std::move(from);
3940 } else {
3941 signaled_.erase(sem);
3942 }
3943}
3944
3945void SignaledSemaphores::Reset() {
3946 signaled_.clear();
3947 prev_ = nullptr;
3948}
3949
John Zulaufea943c52022-02-22 11:05:17 -07003950std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3951 // If we don't have one, make it.
3952 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3953 assert(cb_state.get());
3954 auto queue_flags = cb_state->GetQueueFlags();
3955 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3956}
3957
John Zulaufcb7e1672022-05-04 13:46:08 -06003958std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003959 return GetMappedInsert(cb_access_state, command_buffer,
3960 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3961}
3962
3963std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3964 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3965}
3966
3967const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3968 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3969}
3970
3971CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3972 return GetAccessContextShared(command_buffer).get();
3973}
3974
3975CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3976 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3977}
3978
John Zulaufd1f85d42020-04-15 12:23:15 -06003979void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003980 auto *access_context = GetAccessContextNoInsert(command_buffer);
3981 if (access_context) {
3982 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003983 }
3984}
3985
John Zulaufd1f85d42020-04-15 12:23:15 -06003986void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3987 auto access_found = cb_access_state.find(command_buffer);
3988 if (access_found != cb_access_state.end()) {
3989 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003990 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003991 cb_access_state.erase(access_found);
3992 }
3993}
3994
John Zulauf9cb530d2019-09-30 14:14:10 -06003995bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3996 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3997 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003998 const auto *cb_context = GetAccessContext(commandBuffer);
3999 assert(cb_context);
4000 if (!cb_context) return skip;
4001 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06004002
John Zulauf3d84f1b2020-03-09 13:33:25 -06004003 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004004 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4005 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004006
4007 for (uint32_t region = 0; region < regionCount; region++) {
4008 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004009 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004010 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004011 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004012 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004013 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004014 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004015 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004016 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06004017 }
John Zulauf9cb530d2019-09-30 14:14:10 -06004018 }
John Zulauf16adfc92020-04-08 10:28:33 -06004019 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004020 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004021 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004022 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004023 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004024 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004025 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004026 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06004027 }
4028 }
4029 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06004030 }
4031 return skip;
4032}
4033
4034void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4035 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004036 auto *cb_context = GetAccessContext(commandBuffer);
4037 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004038 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004039 auto *context = cb_context->GetCurrentAccessContext();
4040
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004041 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4042 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004043
4044 for (uint32_t region = 0; region < regionCount; region++) {
4045 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004046 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004047 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004048 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004049 }
John Zulauf16adfc92020-04-08 10:28:33 -06004050 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004051 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004052 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004053 }
4054 }
4055}
4056
John Zulauf4a6105a2020-11-17 15:11:05 -07004057void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4058 // Clear out events from the command buffer contexts
4059 for (auto &cb_context : cb_access_state) {
4060 cb_context.second->RecordDestroyEvent(event);
4061 }
4062}
4063
Tony-LunarGef035472021-11-02 10:23:33 -06004064bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4065 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004066 bool skip = false;
4067 const auto *cb_context = GetAccessContext(commandBuffer);
4068 assert(cb_context);
4069 if (!cb_context) return skip;
4070 const auto *context = cb_context->GetCurrentAccessContext();
4071
4072 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004073 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4074 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004075
4076 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4077 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4078 if (src_buffer) {
4079 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004080 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004081 if (hazard.hazard) {
4082 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004083 skip |=
4084 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4085 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4086 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4087 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004088 }
4089 }
4090 if (dst_buffer && !skip) {
4091 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004092 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004093 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004094 skip |=
4095 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4096 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4097 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4098 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004099 }
4100 }
4101 if (skip) break;
4102 }
4103 return skip;
4104}
4105
Tony-LunarGef035472021-11-02 10:23:33 -06004106bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4107 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4108 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4109}
4110
4111bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4112 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4113}
4114
4115void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004116 auto *cb_context = GetAccessContext(commandBuffer);
4117 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004118 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004119 auto *context = cb_context->GetCurrentAccessContext();
4120
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004121 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4122 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004123
4124 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4125 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4126 if (src_buffer) {
4127 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004128 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004129 }
4130 if (dst_buffer) {
4131 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004132 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004133 }
4134 }
4135}
4136
Tony-LunarGef035472021-11-02 10:23:33 -06004137void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4138 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4139}
4140
4141void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4142 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4143}
4144
John Zulauf5c5e88d2019-12-26 11:22:02 -07004145bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4146 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4147 const VkImageCopy *pRegions) const {
4148 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004149 const auto *cb_access_context = GetAccessContext(commandBuffer);
4150 assert(cb_access_context);
4151 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004152
John Zulauf3d84f1b2020-03-09 13:33:25 -06004153 const auto *context = cb_access_context->GetCurrentAccessContext();
4154 assert(context);
4155 if (!context) return skip;
4156
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004157 auto src_image = Get<IMAGE_STATE>(srcImage);
4158 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004159 for (uint32_t region = 0; region < regionCount; region++) {
4160 const auto &copy_region = pRegions[region];
4161 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004162 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004163 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004164 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004165 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004166 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004167 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004168 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004169 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004170 }
4171
4172 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004173 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004174 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004175 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004176 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004177 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004178 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004179 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004180 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004181 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004182 }
4183 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004184
John Zulauf5c5e88d2019-12-26 11:22:02 -07004185 return skip;
4186}
4187
4188void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4189 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4190 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004191 auto *cb_access_context = GetAccessContext(commandBuffer);
4192 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004193 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004194 auto *context = cb_access_context->GetCurrentAccessContext();
4195 assert(context);
4196
Jeremy Gebben9f537102021-10-05 16:37:12 -06004197 auto src_image = Get<IMAGE_STATE>(srcImage);
4198 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004199
4200 for (uint32_t region = 0; region < regionCount; region++) {
4201 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004202 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004203 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004204 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004205 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004206 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004207 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004208 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004209 }
4210 }
4211}
4212
Tony-LunarGb61514a2021-11-02 12:36:51 -06004213bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4214 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004215 bool skip = false;
4216 const auto *cb_access_context = GetAccessContext(commandBuffer);
4217 assert(cb_access_context);
4218 if (!cb_access_context) return skip;
4219
4220 const auto *context = cb_access_context->GetCurrentAccessContext();
4221 assert(context);
4222 if (!context) return skip;
4223
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004224 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4225 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004226
Jeff Leger178b1e52020-10-05 12:22:23 -04004227 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4228 const auto &copy_region = pCopyImageInfo->pRegions[region];
4229 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004230 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004231 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004232 if (hazard.hazard) {
4233 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004234 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004235 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004236 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004237 }
4238 }
4239
4240 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004241 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004242 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004243 if (hazard.hazard) {
4244 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004245 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004246 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004247 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004248 }
4249 if (skip) break;
4250 }
4251 }
4252
4253 return skip;
4254}
4255
Tony-LunarGb61514a2021-11-02 12:36:51 -06004256bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4257 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4258 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4259}
4260
4261bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4262 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4263}
4264
4265void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004266 auto *cb_access_context = GetAccessContext(commandBuffer);
4267 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004268 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004269 auto *context = cb_access_context->GetCurrentAccessContext();
4270 assert(context);
4271
Jeremy Gebben9f537102021-10-05 16:37:12 -06004272 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4273 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004274
4275 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4276 const auto &copy_region = pCopyImageInfo->pRegions[region];
4277 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004278 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004279 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004280 }
4281 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004282 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004283 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004284 }
4285 }
4286}
4287
Tony-LunarGb61514a2021-11-02 12:36:51 -06004288void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4289 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4290}
4291
4292void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4293 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4294}
4295
John Zulauf9cb530d2019-09-30 14:14:10 -06004296bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4297 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4298 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4299 uint32_t bufferMemoryBarrierCount,
4300 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4301 uint32_t imageMemoryBarrierCount,
4302 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4303 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004304 const auto *cb_access_context = GetAccessContext(commandBuffer);
4305 assert(cb_access_context);
4306 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004307
John Zulauf36ef9282021-02-02 11:47:24 -07004308 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4309 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4310 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4311 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004312 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004313 return skip;
4314}
4315
4316void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4317 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4318 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4319 uint32_t bufferMemoryBarrierCount,
4320 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4321 uint32_t imageMemoryBarrierCount,
4322 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004323 auto *cb_access_context = GetAccessContext(commandBuffer);
4324 assert(cb_access_context);
4325 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004326
John Zulauf1bf30522021-09-03 15:39:06 -06004327 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4328 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4329 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4330 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004331}
4332
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004333bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4334 const VkDependencyInfoKHR *pDependencyInfo) const {
4335 bool skip = false;
4336 const auto *cb_access_context = GetAccessContext(commandBuffer);
4337 assert(cb_access_context);
4338 if (!cb_access_context) return skip;
4339
4340 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4341 skip = pipeline_barrier.Validate(*cb_access_context);
4342 return skip;
4343}
4344
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004345bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4346 const VkDependencyInfo *pDependencyInfo) const {
4347 bool skip = false;
4348 const auto *cb_access_context = GetAccessContext(commandBuffer);
4349 assert(cb_access_context);
4350 if (!cb_access_context) return skip;
4351
4352 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4353 skip = pipeline_barrier.Validate(*cb_access_context);
4354 return skip;
4355}
4356
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004357void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4358 auto *cb_access_context = GetAccessContext(commandBuffer);
4359 assert(cb_access_context);
4360 if (!cb_access_context) return;
4361
John Zulauf1bf30522021-09-03 15:39:06 -06004362 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4363 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004364}
4365
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004366void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4367 auto *cb_access_context = GetAccessContext(commandBuffer);
4368 assert(cb_access_context);
4369 if (!cb_access_context) return;
4370
4371 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4372 *pDependencyInfo);
4373}
4374
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004375void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004376 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004377 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004378
John Zulauf5f13a792020-03-10 07:31:21 -06004379 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4380 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004381 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004382 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4383 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004384
John Zulauf1d5f9c12022-05-13 14:51:08 -06004385 QueueId queue_id = QueueSyncState::kQueueIdBase;
4386 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004387 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004388 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004389 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4390 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004391}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004392
John Zulauf355e49b2020-04-24 15:11:15 -06004393bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004394 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004395 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004396 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004397 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004398 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004399 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004400 }
John Zulauf355e49b2020-04-24 15:11:15 -06004401 return skip;
4402}
4403
4404bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4405 VkSubpassContents contents) const {
4406 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004407 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004408 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004409 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004410 return skip;
4411}
4412
4413bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004414 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004415 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004416 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004417 return skip;
4418}
4419
4420bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4421 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004422 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004423 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004424 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004425 return skip;
4426}
4427
John Zulauf3d84f1b2020-03-09 13:33:25 -06004428void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4429 VkResult result) {
4430 // The state tracker sets up the command buffer state
4431 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4432
4433 // Create/initialize the structure that trackers accesses at the command buffer scope.
4434 auto cb_access_context = GetAccessContext(commandBuffer);
4435 assert(cb_access_context);
4436 cb_access_context->Reset();
4437}
4438
4439void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004440 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004441 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004442 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004443 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004444 }
4445}
4446
4447void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4448 VkSubpassContents contents) {
4449 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004450 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004451 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004452 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004453}
4454
4455void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4456 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4457 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004458 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004459}
4460
4461void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4462 const VkRenderPassBeginInfo *pRenderPassBegin,
4463 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4464 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004465 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004466}
4467
Mike Schuchardt2df08912020-12-15 16:28:09 -08004468bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004469 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004470 bool skip = false;
4471
4472 auto cb_context = GetAccessContext(commandBuffer);
4473 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004474 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004475 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004476 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004477}
4478
4479bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4480 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004481 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004482 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004483 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004484 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4485 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004486 return skip;
4487}
4488
Mike Schuchardt2df08912020-12-15 16:28:09 -08004489bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4490 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004491 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004492 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004493 return skip;
4494}
4495
4496bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4497 const VkSubpassEndInfo *pSubpassEndInfo) const {
4498 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004499 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004500 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004501}
4502
4503void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004504 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004505 auto cb_context = GetAccessContext(commandBuffer);
4506 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004507 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004508
sjfricke0bea06e2022-06-05 09:22:26 +09004509 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004510}
4511
4512void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4513 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004514 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004515 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004516 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004517}
4518
4519void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4520 const VkSubpassEndInfo *pSubpassEndInfo) {
4521 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004522 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004523}
4524
4525void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4526 const VkSubpassEndInfo *pSubpassEndInfo) {
4527 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004528 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004529}
4530
sfricke-samsung85584a72021-09-30 21:43:38 -07004531bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004532 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004533 bool skip = false;
4534
4535 auto cb_context = GetAccessContext(commandBuffer);
4536 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004537 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004538
sjfricke0bea06e2022-06-05 09:22:26 +09004539 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004540 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004541 return skip;
4542}
4543
4544bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4545 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004546 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004547 return skip;
4548}
4549
Mike Schuchardt2df08912020-12-15 16:28:09 -08004550bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004551 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004552 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004553 return skip;
4554}
4555
4556bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004557 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004558 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004559 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004560 return skip;
4561}
4562
sjfricke0bea06e2022-06-05 09:22:26 +09004563void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4564 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004565 // Resolve the all subpass contexts to the command buffer contexts
4566 auto cb_context = GetAccessContext(commandBuffer);
4567 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004568 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004569
sjfricke0bea06e2022-06-05 09:22:26 +09004570 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004571}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004572
John Zulauf33fc1d52020-07-17 11:01:10 -06004573// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4574// updates to a resource which do not conflict at the byte level.
4575// TODO: Revisit this rule to see if it needs to be tighter or looser
4576// TODO: Add programatic control over suppression heuristics
4577bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4578 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4579}
4580
John Zulauf3d84f1b2020-03-09 13:33:25 -06004581void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004582 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004583 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004584}
4585
4586void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004587 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004588 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004589}
4590
4591void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004592 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004593 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004594}
locke-lunarga19c71d2020-03-02 18:17:04 -07004595
sfricke-samsung71f04e32022-03-16 01:21:21 -05004596template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004597bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004598 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4599 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004600 bool skip = false;
4601 const auto *cb_access_context = GetAccessContext(commandBuffer);
4602 assert(cb_access_context);
4603 if (!cb_access_context) return skip;
4604
4605 const auto *context = cb_access_context->GetCurrentAccessContext();
4606 assert(context);
4607 if (!context) return skip;
4608
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004609 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4610 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004611
4612 for (uint32_t region = 0; region < regionCount; region++) {
4613 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004614 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004615 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004616 if (src_buffer) {
4617 ResourceAccessRange src_range =
4618 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004619 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004620 if (hazard.hazard) {
4621 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004622 skip |=
4623 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4624 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4625 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4626 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004627 }
4628 }
4629
Jeremy Gebben40a22942020-12-22 14:22:06 -07004630 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004631 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004632 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004633 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004634 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004635 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004636 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004637 }
4638 if (skip) break;
4639 }
4640 if (skip) break;
4641 }
4642 return skip;
4643}
4644
Jeff Leger178b1e52020-10-05 12:22:23 -04004645bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4646 VkImageLayout dstImageLayout, uint32_t regionCount,
4647 const VkBufferImageCopy *pRegions) const {
4648 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004649 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004650}
4651
4652bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4653 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4654 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4655 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004656 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4657}
4658
4659bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4660 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4661 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4662 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4663 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004664}
4665
sfricke-samsung71f04e32022-03-16 01:21:21 -05004666template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004667void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004668 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4669 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004670 auto *cb_access_context = GetAccessContext(commandBuffer);
4671 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004672
Jeff Leger178b1e52020-10-05 12:22:23 -04004673 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004674 auto *context = cb_access_context->GetCurrentAccessContext();
4675 assert(context);
4676
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004677 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4678 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004679
4680 for (uint32_t region = 0; region < regionCount; region++) {
4681 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004682 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004683 if (src_buffer) {
4684 ResourceAccessRange src_range =
4685 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004686 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004687 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004688 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004689 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004690 }
4691 }
4692}
4693
Jeff Leger178b1e52020-10-05 12:22:23 -04004694void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4695 VkImageLayout dstImageLayout, uint32_t regionCount,
4696 const VkBufferImageCopy *pRegions) {
4697 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004698 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004699}
4700
4701void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4702 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4703 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4704 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4705 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004706 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4707}
4708
4709void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4710 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4711 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4712 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4713 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4714 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004715}
4716
sfricke-samsung71f04e32022-03-16 01:21:21 -05004717template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004718bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004719 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4720 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004721 bool skip = false;
4722 const auto *cb_access_context = GetAccessContext(commandBuffer);
4723 assert(cb_access_context);
4724 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004725
locke-lunarga19c71d2020-03-02 18:17:04 -07004726 const auto *context = cb_access_context->GetCurrentAccessContext();
4727 assert(context);
4728 if (!context) return skip;
4729
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004730 auto src_image = Get<IMAGE_STATE>(srcImage);
4731 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004732 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004733 for (uint32_t region = 0; region < regionCount; region++) {
4734 const auto &copy_region = pRegions[region];
4735 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004736 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004737 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004738 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004739 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004740 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004741 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004742 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004743 }
John Zulauf477700e2021-01-06 11:41:49 -07004744 if (dst_mem) {
4745 ResourceAccessRange dst_range =
4746 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004747 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004748 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004749 skip |=
4750 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4751 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4752 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4753 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004754 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004755 }
4756 }
4757 if (skip) break;
4758 }
4759 return skip;
4760}
4761
Jeff Leger178b1e52020-10-05 12:22:23 -04004762bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4763 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4764 const VkBufferImageCopy *pRegions) const {
4765 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004766 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004767}
4768
4769bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4770 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4771 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4772 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004773 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4774}
4775
4776bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4777 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4778 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4779 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4780 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004781}
4782
sfricke-samsung71f04e32022-03-16 01:21:21 -05004783template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004784void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004785 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004786 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004787 auto *cb_access_context = GetAccessContext(commandBuffer);
4788 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004789
Jeff Leger178b1e52020-10-05 12:22:23 -04004790 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004791 auto *context = cb_access_context->GetCurrentAccessContext();
4792 assert(context);
4793
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004794 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004795 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004796 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004797 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004798
4799 for (uint32_t region = 0; region < regionCount; region++) {
4800 const auto &copy_region = pRegions[region];
4801 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004802 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004803 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004804 if (dst_buffer) {
4805 ResourceAccessRange dst_range =
4806 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004807 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004808 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004809 }
4810 }
4811}
4812
Jeff Leger178b1e52020-10-05 12:22:23 -04004813void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4814 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4815 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004816 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004817}
4818
4819void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4820 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4821 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4822 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4823 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004824 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4825}
4826
4827void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4828 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4829 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4830 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4831 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4832 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004833}
4834
4835template <typename RegionType>
4836bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4837 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004838 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004839 bool skip = false;
4840 const auto *cb_access_context = GetAccessContext(commandBuffer);
4841 assert(cb_access_context);
4842 if (!cb_access_context) return skip;
4843
4844 const auto *context = cb_access_context->GetCurrentAccessContext();
4845 assert(context);
4846 if (!context) return skip;
4847
sjfricke0bea06e2022-06-05 09:22:26 +09004848 const char *caller_name = CommandTypeString(cmd_type);
4849
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004850 auto src_image = Get<IMAGE_STATE>(srcImage);
4851 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004852
4853 for (uint32_t region = 0; region < regionCount; region++) {
4854 const auto &blit_region = pRegions[region];
4855 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004856 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4857 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4858 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4859 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4860 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4861 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004862 auto hazard =
4863 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004864 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004865 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004866 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004867 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004868 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004869 }
4870 }
4871
4872 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004873 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4874 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4875 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4876 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4877 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4878 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004879 auto hazard =
4880 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004881 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004882 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004883 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004884 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004885 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004886 }
4887 if (skip) break;
4888 }
4889 }
4890
4891 return skip;
4892}
4893
Jeff Leger178b1e52020-10-05 12:22:23 -04004894bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4895 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4896 const VkImageBlit *pRegions, VkFilter filter) const {
4897 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004898 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004899}
4900
4901bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4902 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4903 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4904 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004905 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004906}
4907
Tony-LunarG542ae912021-11-04 16:06:44 -06004908bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4909 const VkBlitImageInfo2 *pBlitImageInfo) const {
4910 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004911 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4912 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004913}
4914
Jeff Leger178b1e52020-10-05 12:22:23 -04004915template <typename RegionType>
4916void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4917 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4918 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004919 auto *cb_access_context = GetAccessContext(commandBuffer);
4920 assert(cb_access_context);
4921 auto *context = cb_access_context->GetCurrentAccessContext();
4922 assert(context);
4923
Jeremy Gebben9f537102021-10-05 16:37:12 -06004924 auto src_image = Get<IMAGE_STATE>(srcImage);
4925 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004926
4927 for (uint32_t region = 0; region < regionCount; region++) {
4928 const auto &blit_region = pRegions[region];
4929 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004930 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4931 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4932 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4933 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4934 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4935 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004936 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004937 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004938 }
4939 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004940 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4941 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4942 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4943 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4944 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4945 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004946 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004947 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004948 }
4949 }
4950}
locke-lunarg36ba2592020-04-03 09:42:04 -06004951
Jeff Leger178b1e52020-10-05 12:22:23 -04004952void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4953 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4954 const VkImageBlit *pRegions, VkFilter filter) {
4955 auto *cb_access_context = GetAccessContext(commandBuffer);
4956 assert(cb_access_context);
4957 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4958 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4959 pRegions, filter);
4960 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4961}
4962
4963void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4964 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4965 auto *cb_access_context = GetAccessContext(commandBuffer);
4966 assert(cb_access_context);
4967 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4968 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4969 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4970 pBlitImageInfo->filter, tag);
4971}
4972
Tony-LunarG542ae912021-11-04 16:06:44 -06004973void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4974 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4975 auto *cb_access_context = GetAccessContext(commandBuffer);
4976 assert(cb_access_context);
4977 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4978 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4979 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4980 pBlitImageInfo->filter, tag);
4981}
4982
John Zulauffaea0ee2021-01-14 14:01:32 -07004983bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4984 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4985 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004986 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004987 bool skip = false;
4988 if (drawCount == 0) return skip;
4989
sjfricke0bea06e2022-06-05 09:22:26 +09004990 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004991 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004992 VkDeviceSize size = struct_size;
4993 if (drawCount == 1 || stride == size) {
4994 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004995 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004996 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4997 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004998 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004999 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06005000 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005001 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005002 }
5003 } else {
5004 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005005 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06005006 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5007 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005008 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005009 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
5010 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5011 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005012 break;
5013 }
5014 }
5015 }
5016 return skip;
5017}
5018
John Zulauf14940722021-04-12 15:19:02 -06005019void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06005020 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
5021 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005022 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005023 VkDeviceSize size = struct_size;
5024 if (drawCount == 1 || stride == size) {
5025 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005026 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005027 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005028 } else {
5029 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005030 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005031 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
5032 tag);
locke-lunargff255f92020-05-13 18:53:52 -06005033 }
5034 }
5035}
5036
John Zulauffaea0ee2021-01-14 14:01:32 -07005037bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5038 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005039 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005040 bool skip = false;
5041
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005042 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005043 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005044 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5045 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005046 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005047 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5048 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5049 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005050 }
5051 return skip;
5052}
5053
John Zulauf14940722021-04-12 15:19:02 -06005054void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005055 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005056 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005057 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005058}
5059
locke-lunarg36ba2592020-04-03 09:42:04 -06005060bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005061 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005062 const auto *cb_access_context = GetAccessContext(commandBuffer);
5063 assert(cb_access_context);
5064 if (!cb_access_context) return skip;
5065
sjfricke0bea06e2022-06-05 09:22:26 +09005066 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005067 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005068}
5069
5070void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005071 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005072 auto *cb_access_context = GetAccessContext(commandBuffer);
5073 assert(cb_access_context);
5074 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005075
locke-lunarg61870c22020-06-09 14:51:50 -06005076 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005077}
locke-lunarge1a67022020-04-29 00:15:36 -06005078
5079bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005080 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005081 const auto *cb_access_context = GetAccessContext(commandBuffer);
5082 assert(cb_access_context);
5083 if (!cb_access_context) return skip;
5084
5085 const auto *context = cb_access_context->GetCurrentAccessContext();
5086 assert(context);
5087 if (!context) return skip;
5088
sjfricke0bea06e2022-06-05 09:22:26 +09005089 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005090 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005091 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005092 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005093}
5094
5095void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005096 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005097 auto *cb_access_context = GetAccessContext(commandBuffer);
5098 assert(cb_access_context);
5099 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5100 auto *context = cb_access_context->GetCurrentAccessContext();
5101 assert(context);
5102
locke-lunarg61870c22020-06-09 14:51:50 -06005103 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5104 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005105}
5106
5107bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5108 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005109 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005110 const auto *cb_access_context = GetAccessContext(commandBuffer);
5111 assert(cb_access_context);
5112 if (!cb_access_context) return skip;
5113
sjfricke0bea06e2022-06-05 09:22:26 +09005114 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5115 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5116 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005117 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005118}
5119
5120void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5121 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005122 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005123 auto *cb_access_context = GetAccessContext(commandBuffer);
5124 assert(cb_access_context);
5125 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005126
locke-lunarg61870c22020-06-09 14:51:50 -06005127 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5128 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5129 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005130}
5131
5132bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5133 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005134 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005135 const auto *cb_access_context = GetAccessContext(commandBuffer);
5136 assert(cb_access_context);
5137 if (!cb_access_context) return skip;
5138
sjfricke0bea06e2022-06-05 09:22:26 +09005139 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5140 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5141 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005142 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005143}
5144
5145void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5146 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005147 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005148 auto *cb_access_context = GetAccessContext(commandBuffer);
5149 assert(cb_access_context);
5150 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005151
locke-lunarg61870c22020-06-09 14:51:50 -06005152 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5153 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5154 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005155}
5156
5157bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5158 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005159 bool skip = false;
5160 if (drawCount == 0) return skip;
5161
locke-lunargff255f92020-05-13 18:53:52 -06005162 const auto *cb_access_context = GetAccessContext(commandBuffer);
5163 assert(cb_access_context);
5164 if (!cb_access_context) return skip;
5165
5166 const auto *context = cb_access_context->GetCurrentAccessContext();
5167 assert(context);
5168 if (!context) return skip;
5169
sjfricke0bea06e2022-06-05 09:22:26 +09005170 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5171 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005172 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005173 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005174
5175 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5176 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5177 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005178 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005179 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005180}
5181
5182void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5183 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005184 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005185 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005186 auto *cb_access_context = GetAccessContext(commandBuffer);
5187 assert(cb_access_context);
5188 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5189 auto *context = cb_access_context->GetCurrentAccessContext();
5190 assert(context);
5191
locke-lunarg61870c22020-06-09 14:51:50 -06005192 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5193 cb_access_context->RecordDrawSubpassAttachment(tag);
5194 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005195
5196 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5197 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5198 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005199 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005200}
5201
5202bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5203 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005204 bool skip = false;
5205 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005206 const auto *cb_access_context = GetAccessContext(commandBuffer);
5207 assert(cb_access_context);
5208 if (!cb_access_context) return skip;
5209
5210 const auto *context = cb_access_context->GetCurrentAccessContext();
5211 assert(context);
5212 if (!context) return skip;
5213
sjfricke0bea06e2022-06-05 09:22:26 +09005214 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5215 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005216 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005217 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005218
5219 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5220 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5221 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005222 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005223 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005224}
5225
5226void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5227 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005228 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005229 auto *cb_access_context = GetAccessContext(commandBuffer);
5230 assert(cb_access_context);
5231 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5232 auto *context = cb_access_context->GetCurrentAccessContext();
5233 assert(context);
5234
locke-lunarg61870c22020-06-09 14:51:50 -06005235 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5236 cb_access_context->RecordDrawSubpassAttachment(tag);
5237 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005238
5239 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5240 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5241 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005242 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005243}
5244
5245bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5246 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005247 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005248 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005249 const auto *cb_access_context = GetAccessContext(commandBuffer);
5250 assert(cb_access_context);
5251 if (!cb_access_context) return skip;
5252
5253 const auto *context = cb_access_context->GetCurrentAccessContext();
5254 assert(context);
5255 if (!context) return skip;
5256
sjfricke0bea06e2022-06-05 09:22:26 +09005257 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5258 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005259 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005260 maxDrawCount, stride, cmd_type);
5261 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005262
5263 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5264 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5265 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005266 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005267 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005268}
5269
5270bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5271 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5272 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005273 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005274 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005275}
5276
sfricke-samsung85584a72021-09-30 21:43:38 -07005277void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5278 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5279 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005280 auto *cb_access_context = GetAccessContext(commandBuffer);
5281 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005282 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005283 auto *context = cb_access_context->GetCurrentAccessContext();
5284 assert(context);
5285
locke-lunarg61870c22020-06-09 14:51:50 -06005286 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5287 cb_access_context->RecordDrawSubpassAttachment(tag);
5288 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5289 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005290
5291 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5292 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5293 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005294 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005295}
5296
sfricke-samsung85584a72021-09-30 21:43:38 -07005297void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5298 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5299 uint32_t stride) {
5300 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5301 stride);
5302 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5303 CMD_DRAWINDIRECTCOUNT);
5304}
locke-lunarge1a67022020-04-29 00:15:36 -06005305bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5306 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5307 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005308 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005309 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005310}
5311
5312void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5313 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5314 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005315 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5316 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005317 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5318 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005319}
5320
5321bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5322 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5323 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005324 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005325 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005326}
5327
5328void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5329 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5330 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005331 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5332 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005333 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5334 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005335}
5336
5337bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5338 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005339 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005340 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005341 const auto *cb_access_context = GetAccessContext(commandBuffer);
5342 assert(cb_access_context);
5343 if (!cb_access_context) return skip;
5344
5345 const auto *context = cb_access_context->GetCurrentAccessContext();
5346 assert(context);
5347 if (!context) return skip;
5348
sjfricke0bea06e2022-06-05 09:22:26 +09005349 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5350 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005351 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005352 offset, maxDrawCount, stride, cmd_type);
5353 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005354
5355 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5356 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5357 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005358 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005359 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005360}
5361
5362bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5363 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5364 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005365 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005366 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005367}
5368
sfricke-samsung85584a72021-09-30 21:43:38 -07005369void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5370 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5371 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005372 auto *cb_access_context = GetAccessContext(commandBuffer);
5373 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005374 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005375 auto *context = cb_access_context->GetCurrentAccessContext();
5376 assert(context);
5377
locke-lunarg61870c22020-06-09 14:51:50 -06005378 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5379 cb_access_context->RecordDrawSubpassAttachment(tag);
5380 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5381 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005382
5383 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5384 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005385 // We will update the index and vertex buffer in SubmitQueue in the future.
5386 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005387}
5388
sfricke-samsung85584a72021-09-30 21:43:38 -07005389void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5390 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5391 uint32_t maxDrawCount, uint32_t stride) {
5392 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5393 maxDrawCount, stride);
5394 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5395 CMD_DRAWINDEXEDINDIRECTCOUNT);
5396}
5397
locke-lunarge1a67022020-04-29 00:15:36 -06005398bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5399 VkDeviceSize offset, VkBuffer countBuffer,
5400 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5401 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005402 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005403 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005404}
5405
5406void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5407 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5408 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005409 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5410 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005411 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5412 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005413}
5414
5415bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5416 VkDeviceSize offset, VkBuffer countBuffer,
5417 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5418 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005419 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005420 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005421}
5422
5423void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5424 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5425 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005426 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5427 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005428 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5429 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005430}
5431
5432bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5433 const VkClearColorValue *pColor, uint32_t rangeCount,
5434 const VkImageSubresourceRange *pRanges) const {
5435 bool skip = false;
5436 const auto *cb_access_context = GetAccessContext(commandBuffer);
5437 assert(cb_access_context);
5438 if (!cb_access_context) return skip;
5439
5440 const auto *context = cb_access_context->GetCurrentAccessContext();
5441 assert(context);
5442 if (!context) return skip;
5443
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005444 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005445
5446 for (uint32_t index = 0; index < rangeCount; index++) {
5447 const auto &range = pRanges[index];
5448 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005449 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005450 if (hazard.hazard) {
5451 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005452 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005453 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005454 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005455 }
5456 }
5457 }
5458 return skip;
5459}
5460
5461void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5462 const VkClearColorValue *pColor, uint32_t rangeCount,
5463 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005464 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005465 auto *cb_access_context = GetAccessContext(commandBuffer);
5466 assert(cb_access_context);
5467 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5468 auto *context = cb_access_context->GetCurrentAccessContext();
5469 assert(context);
5470
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005471 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005472
5473 for (uint32_t index = 0; index < rangeCount; index++) {
5474 const auto &range = pRanges[index];
5475 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005476 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005477 }
5478 }
5479}
5480
5481bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5482 VkImageLayout imageLayout,
5483 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5484 const VkImageSubresourceRange *pRanges) const {
5485 bool skip = false;
5486 const auto *cb_access_context = GetAccessContext(commandBuffer);
5487 assert(cb_access_context);
5488 if (!cb_access_context) return skip;
5489
5490 const auto *context = cb_access_context->GetCurrentAccessContext();
5491 assert(context);
5492 if (!context) return skip;
5493
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005494 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005495
5496 for (uint32_t index = 0; index < rangeCount; index++) {
5497 const auto &range = pRanges[index];
5498 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005499 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005500 if (hazard.hazard) {
5501 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005502 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005503 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005504 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005505 }
5506 }
5507 }
5508 return skip;
5509}
5510
5511void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5512 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5513 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005514 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005515 auto *cb_access_context = GetAccessContext(commandBuffer);
5516 assert(cb_access_context);
5517 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5518 auto *context = cb_access_context->GetCurrentAccessContext();
5519 assert(context);
5520
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005521 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005522
5523 for (uint32_t index = 0; index < rangeCount; index++) {
5524 const auto &range = pRanges[index];
5525 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005526 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005527 }
5528 }
5529}
5530
5531bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5532 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5533 VkDeviceSize dstOffset, VkDeviceSize stride,
5534 VkQueryResultFlags flags) const {
5535 bool skip = false;
5536 const auto *cb_access_context = GetAccessContext(commandBuffer);
5537 assert(cb_access_context);
5538 if (!cb_access_context) return skip;
5539
5540 const auto *context = cb_access_context->GetCurrentAccessContext();
5541 assert(context);
5542 if (!context) return skip;
5543
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005544 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005545
5546 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005547 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005548 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005549 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005550 skip |=
5551 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5552 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005553 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005554 }
5555 }
locke-lunargff255f92020-05-13 18:53:52 -06005556
5557 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005558 return skip;
5559}
5560
5561void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5562 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5563 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005564 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5565 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005566 auto *cb_access_context = GetAccessContext(commandBuffer);
5567 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005568 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005569 auto *context = cb_access_context->GetCurrentAccessContext();
5570 assert(context);
5571
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005572 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005573
5574 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005575 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005576 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005577 }
locke-lunargff255f92020-05-13 18:53:52 -06005578
5579 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005580}
5581
5582bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5583 VkDeviceSize size, uint32_t data) const {
5584 bool skip = false;
5585 const auto *cb_access_context = GetAccessContext(commandBuffer);
5586 assert(cb_access_context);
5587 if (!cb_access_context) return skip;
5588
5589 const auto *context = cb_access_context->GetCurrentAccessContext();
5590 assert(context);
5591 if (!context) return skip;
5592
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005593 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005594
5595 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005596 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
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 "vkCmdFillBuffer: 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::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5608 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005609 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
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_FILLBUFFER);
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 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005620 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005621 }
5622}
5623
5624bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5625 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5626 const VkImageResolve *pRegions) 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 src_image = Get<IMAGE_STATE>(srcImage);
5637 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005638
5639 for (uint32_t region = 0; region < regionCount; region++) {
5640 const auto &resolve_region = pRegions[region];
5641 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005642 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005643 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005644 if (hazard.hazard) {
5645 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005646 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005647 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005648 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005649 }
5650 }
5651
5652 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005653 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005654 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005655 if (hazard.hazard) {
5656 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005657 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005658 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005659 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005660 }
5661 if (skip) break;
5662 }
5663 }
5664
5665 return skip;
5666}
5667
5668void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5669 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5670 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005671 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5672 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005673 auto *cb_access_context = GetAccessContext(commandBuffer);
5674 assert(cb_access_context);
5675 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5676 auto *context = cb_access_context->GetCurrentAccessContext();
5677 assert(context);
5678
Jeremy Gebben9f537102021-10-05 16:37:12 -06005679 auto src_image = Get<IMAGE_STATE>(srcImage);
5680 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005681
5682 for (uint32_t region = 0; region < regionCount; region++) {
5683 const auto &resolve_region = pRegions[region];
5684 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005685 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005686 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005687 }
5688 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005689 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005690 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005691 }
5692 }
5693}
5694
Tony-LunarG562fc102021-11-12 13:58:35 -07005695bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5696 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005697 bool skip = false;
5698 const auto *cb_access_context = GetAccessContext(commandBuffer);
5699 assert(cb_access_context);
5700 if (!cb_access_context) return skip;
5701
5702 const auto *context = cb_access_context->GetCurrentAccessContext();
5703 assert(context);
5704 if (!context) return skip;
5705
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005706 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5707 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005708
5709 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5710 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5711 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005712 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005713 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005714 if (hazard.hazard) {
5715 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005716 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005717 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005718 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005719 }
5720 }
5721
5722 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005723 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005724 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005725 if (hazard.hazard) {
5726 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005727 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005728 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005729 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005730 }
5731 if (skip) break;
5732 }
5733 }
5734
5735 return skip;
5736}
5737
Tony-LunarG562fc102021-11-12 13:58:35 -07005738bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5739 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5740 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5741}
5742
5743bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5744 const VkResolveImageInfo2 *pResolveImageInfo) const {
5745 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5746}
5747
5748void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5749 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005750 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5751 auto *cb_access_context = GetAccessContext(commandBuffer);
5752 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005753 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005754 auto *context = cb_access_context->GetCurrentAccessContext();
5755 assert(context);
5756
Jeremy Gebben9f537102021-10-05 16:37:12 -06005757 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5758 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005759
5760 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5761 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5762 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005763 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005764 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005765 }
5766 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005767 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005768 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005769 }
5770 }
5771}
5772
Tony-LunarG562fc102021-11-12 13:58:35 -07005773void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5774 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5775 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5776}
5777
5778void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5779 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5780}
5781
locke-lunarge1a67022020-04-29 00:15:36 -06005782bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5783 VkDeviceSize dataSize, const void *pData) const {
5784 bool skip = false;
5785 const auto *cb_access_context = GetAccessContext(commandBuffer);
5786 assert(cb_access_context);
5787 if (!cb_access_context) return skip;
5788
5789 const auto *context = cb_access_context->GetCurrentAccessContext();
5790 assert(context);
5791 if (!context) return skip;
5792
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005793 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005794
5795 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005796 // VK_WHOLE_SIZE not allowed
5797 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005798 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005799 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005800 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005801 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005802 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005803 }
5804 }
5805 return skip;
5806}
5807
5808void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5809 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005810 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005811 auto *cb_access_context = GetAccessContext(commandBuffer);
5812 assert(cb_access_context);
5813 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5814 auto *context = cb_access_context->GetCurrentAccessContext();
5815 assert(context);
5816
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005817 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005818
5819 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005820 // VK_WHOLE_SIZE not allowed
5821 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005822 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005823 }
5824}
locke-lunargff255f92020-05-13 18:53:52 -06005825
5826bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5827 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5828 bool skip = false;
5829 const auto *cb_access_context = GetAccessContext(commandBuffer);
5830 assert(cb_access_context);
5831 if (!cb_access_context) return skip;
5832
5833 const auto *context = cb_access_context->GetCurrentAccessContext();
5834 assert(context);
5835 if (!context) return skip;
5836
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005837 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005838
5839 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005840 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005841 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005842 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005843 skip |=
5844 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5845 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005846 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005847 }
5848 }
5849 return skip;
5850}
5851
5852void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5853 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005854 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005855 auto *cb_access_context = GetAccessContext(commandBuffer);
5856 assert(cb_access_context);
5857 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5858 auto *context = cb_access_context->GetCurrentAccessContext();
5859 assert(context);
5860
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005861 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005862
5863 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005864 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005865 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005866 }
5867}
John Zulauf49beb112020-11-04 16:06:31 -07005868
5869bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5870 bool skip = false;
5871 const auto *cb_context = GetAccessContext(commandBuffer);
5872 assert(cb_context);
5873 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005874 const auto *access_context = cb_context->GetCurrentAccessContext();
5875 assert(access_context);
5876 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005877
John Zulaufe0757ba2022-06-10 16:51:45 -06005878 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005879 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005880}
5881
5882void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5883 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5884 auto *cb_context = GetAccessContext(commandBuffer);
5885 assert(cb_context);
5886 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005887
5888 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5889 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005890}
5891
John Zulauf4edde622021-02-15 08:54:50 -07005892bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5893 const VkDependencyInfoKHR *pDependencyInfo) const {
5894 bool skip = false;
5895 const auto *cb_context = GetAccessContext(commandBuffer);
5896 assert(cb_context);
5897 if (!cb_context || !pDependencyInfo) return skip;
5898
John Zulaufe0757ba2022-06-10 16:51:45 -06005899 const auto *access_context = cb_context->GetCurrentAccessContext();
5900 assert(access_context);
5901 if (!access_context) return skip;
5902
5903 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005904 return set_event_op.Validate(*cb_context);
5905}
5906
Tony-LunarGc43525f2021-11-15 16:12:38 -07005907bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5908 const VkDependencyInfo *pDependencyInfo) const {
5909 bool skip = false;
5910 const auto *cb_context = GetAccessContext(commandBuffer);
5911 assert(cb_context);
5912 if (!cb_context || !pDependencyInfo) return skip;
5913
John Zulaufe0757ba2022-06-10 16:51:45 -06005914 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005915 return set_event_op.Validate(*cb_context);
5916}
5917
John Zulauf4edde622021-02-15 08:54:50 -07005918void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5919 const VkDependencyInfoKHR *pDependencyInfo) {
5920 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5921 auto *cb_context = GetAccessContext(commandBuffer);
5922 assert(cb_context);
5923 if (!cb_context || !pDependencyInfo) return;
5924
John Zulaufe0757ba2022-06-10 16:51:45 -06005925 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5926 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005927}
5928
Tony-LunarGc43525f2021-11-15 16:12:38 -07005929void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5930 const VkDependencyInfo *pDependencyInfo) {
5931 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5932 auto *cb_context = GetAccessContext(commandBuffer);
5933 assert(cb_context);
5934 if (!cb_context || !pDependencyInfo) return;
5935
John Zulaufe0757ba2022-06-10 16:51:45 -06005936 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5937 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005938}
5939
John Zulauf49beb112020-11-04 16:06:31 -07005940bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5941 VkPipelineStageFlags stageMask) const {
5942 bool skip = false;
5943 const auto *cb_context = GetAccessContext(commandBuffer);
5944 assert(cb_context);
5945 if (!cb_context) return skip;
5946
John Zulauf36ef9282021-02-02 11:47:24 -07005947 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005948 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005949}
5950
5951void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5952 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5953 auto *cb_context = GetAccessContext(commandBuffer);
5954 assert(cb_context);
5955 if (!cb_context) return;
5956
John Zulauf1bf30522021-09-03 15:39:06 -06005957 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005958}
5959
John Zulauf4edde622021-02-15 08:54:50 -07005960bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5961 VkPipelineStageFlags2KHR stageMask) const {
5962 bool skip = false;
5963 const auto *cb_context = GetAccessContext(commandBuffer);
5964 assert(cb_context);
5965 if (!cb_context) return skip;
5966
5967 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5968 return reset_event_op.Validate(*cb_context);
5969}
5970
Tony-LunarGa2662db2021-11-16 07:26:24 -07005971bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5972 VkPipelineStageFlags2 stageMask) const {
5973 bool skip = false;
5974 const auto *cb_context = GetAccessContext(commandBuffer);
5975 assert(cb_context);
5976 if (!cb_context) return skip;
5977
5978 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5979 return reset_event_op.Validate(*cb_context);
5980}
5981
John Zulauf4edde622021-02-15 08:54:50 -07005982void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5983 VkPipelineStageFlags2KHR stageMask) {
5984 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5985 auto *cb_context = GetAccessContext(commandBuffer);
5986 assert(cb_context);
5987 if (!cb_context) return;
5988
John Zulauf1bf30522021-09-03 15:39:06 -06005989 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005990}
5991
Tony-LunarGa2662db2021-11-16 07:26:24 -07005992void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5993 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5994 auto *cb_context = GetAccessContext(commandBuffer);
5995 assert(cb_context);
5996 if (!cb_context) return;
5997
5998 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5999}
6000
John Zulauf49beb112020-11-04 16:06:31 -07006001bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6002 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6003 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6004 uint32_t bufferMemoryBarrierCount,
6005 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6006 uint32_t imageMemoryBarrierCount,
6007 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
6008 bool skip = false;
6009 const auto *cb_context = GetAccessContext(commandBuffer);
6010 assert(cb_context);
6011 if (!cb_context) return skip;
6012
John Zulauf36ef9282021-02-02 11:47:24 -07006013 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
6014 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
6015 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07006016 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07006017}
6018
6019void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6020 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6021 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6022 uint32_t bufferMemoryBarrierCount,
6023 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6024 uint32_t imageMemoryBarrierCount,
6025 const VkImageMemoryBarrier *pImageMemoryBarriers) {
6026 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
6027 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
6028 imageMemoryBarrierCount, pImageMemoryBarriers);
6029
6030 auto *cb_context = GetAccessContext(commandBuffer);
6031 assert(cb_context);
6032 if (!cb_context) return;
6033
John Zulauf1bf30522021-09-03 15:39:06 -06006034 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06006035 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06006036 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07006037}
6038
John Zulauf4edde622021-02-15 08:54:50 -07006039bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6040 const VkDependencyInfoKHR *pDependencyInfos) const {
6041 bool skip = false;
6042 const auto *cb_context = GetAccessContext(commandBuffer);
6043 assert(cb_context);
6044 if (!cb_context) return skip;
6045
6046 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6047 skip |= wait_events_op.Validate(*cb_context);
6048 return skip;
6049}
6050
6051void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6052 const VkDependencyInfoKHR *pDependencyInfos) {
6053 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6054
6055 auto *cb_context = GetAccessContext(commandBuffer);
6056 assert(cb_context);
6057 if (!cb_context) return;
6058
John Zulauf1bf30522021-09-03 15:39:06 -06006059 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6060 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006061}
6062
Tony-LunarG1364cf52021-11-17 16:10:11 -07006063bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6064 const VkDependencyInfo *pDependencyInfos) const {
6065 bool skip = false;
6066 const auto *cb_context = GetAccessContext(commandBuffer);
6067 assert(cb_context);
6068 if (!cb_context) return skip;
6069
6070 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6071 skip |= wait_events_op.Validate(*cb_context);
6072 return skip;
6073}
6074
6075void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6076 const VkDependencyInfo *pDependencyInfos) {
6077 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6078
6079 auto *cb_context = GetAccessContext(commandBuffer);
6080 assert(cb_context);
6081 if (!cb_context) return;
6082
6083 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6084 pDependencyInfos);
6085}
6086
John Zulauf4a6105a2020-11-17 15:11:05 -07006087void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006088 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006089 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006090 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006091}
6092
6093// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006094SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006095 IgnoreReason reason = NotIgnored;
6096
sjfricke0bea06e2022-06-05 09:22:26 +09006097 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006098 reason = SetVsWait2;
6099 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6100 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006101 } else if (unsynchronized_set) {
6102 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006103 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006104 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006105 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006106 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006107 } else {
6108 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006109 }
6110
6111 return reason;
6112}
6113
Jeremy Gebben40a22942020-12-22 14:22:06 -07006114bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006115 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6116 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6117 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006118}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006119
sjfricke0bea06e2022-06-05 09:22:26 +09006120SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006121 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6122 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006123 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6124 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6125 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006126 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006127 auto &barrier_set = barriers_[0];
6128 barrier_set.dependency_flags = dependencyFlags;
6129 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6130 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006131 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006132 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6133 pMemoryBarriers);
6134 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6135 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6136 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6137 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006138}
6139
sjfricke0bea06e2022-06-05 09:22:26 +09006140SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006141 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006142 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006143 for (uint32_t i = 0; i < event_count; i++) {
6144 const auto &dep_info = dep_infos[i];
6145 auto &barrier_set = barriers_[i];
6146 barrier_set.dependency_flags = dep_info.dependencyFlags;
6147 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6148 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6149 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6150 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6151 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6152 dep_info.pMemoryBarriers);
6153 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6154 dep_info.pBufferMemoryBarriers);
6155 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6156 dep_info.pImageMemoryBarriers);
6157 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006158}
6159
sjfricke0bea06e2022-06-05 09:22:26 +09006160SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006161 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6162 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6163 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6164 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6165 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006166 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6167 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6168 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006169
sjfricke0bea06e2022-06-05 09:22:26 +09006170SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006171 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006172 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006173
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006174bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6175 bool skip = false;
6176 const auto *context = cb_context.GetCurrentAccessContext();
6177 assert(context);
6178 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006179 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6180
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006181 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006182 const auto &barrier_set = barriers_[0];
6183 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6184 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6185 const auto *image_state = image_barrier.image.get();
6186 if (!image_state) continue;
6187 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6188 if (hazard.hazard) {
6189 // PHASE1 TODO -- add tag information to log msg when useful.
6190 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006191 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006192 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6193 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6194 string_SyncHazard(hazard.hazard), image_barrier.index,
6195 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006196 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006197 }
6198 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006199 return skip;
6200}
6201
John Zulaufd5115702021-01-18 12:34:33 -07006202struct SyncOpPipelineBarrierFunctorFactory {
6203 using BarrierOpFunctor = PipelineBarrierOp;
6204 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6205 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6206 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6207 using BufferRange = ResourceAccessRange;
6208 using ImageRange = subresource_adapter::ImageRangeGenerator;
6209 using GlobalRange = ResourceAccessRange;
6210
John Zulauf00119522022-05-23 19:07:42 -06006211 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6212 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006213 }
John Zulauf14940722021-04-12 15:19:02 -06006214 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006215 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6216 }
John Zulauf00119522022-05-23 19:07:42 -06006217 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6218 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006219 }
6220
6221 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6222 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6223 const auto base_address = ResourceBaseAddress(buffer);
6224 return (range + base_address);
6225 }
John Zulauf110413c2021-03-20 05:38:38 -06006226 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006227 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006228
6229 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006230 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006231 return range_gen;
6232 }
6233 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6234};
6235
6236template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006237void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6238 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006239 for (const auto &barrier : barriers) {
6240 const auto *state = barrier.GetState();
6241 if (state) {
6242 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006243 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006244 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6245 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6246 }
6247 }
6248}
6249
6250template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006251void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6252 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006253 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6254 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006255 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006256 }
6257 for (const auto address_type : kAddressTypes) {
6258 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6259 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6260 }
6261}
6262
John Zulaufdab327f2022-07-08 12:02:05 -06006263ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006264 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006265 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006266 return tag;
6267}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006268
John Zulauf0223f142022-07-06 09:05:39 -06006269void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006270 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006271 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6272 assert(barriers_.size() == 1);
6273 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006274 if (!exec_context.ValidForSyncOps()) return;
6275
6276 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6277 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6278 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006279 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6280 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6281 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006282 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006283 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006284 } else {
6285 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006286 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006287 }
6288 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006289}
6290
John Zulauf8eda1562021-04-13 17:06:41 -06006291bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006292 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006293 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6294 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006295 return false;
6296}
6297
John Zulauf4edde622021-02-15 08:54:50 -07006298void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6299 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6300 const VkMemoryBarrier *barriers) {
6301 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006302 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006303 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006304 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006305 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006306 }
6307 if (0 == memory_barrier_count) {
6308 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006309 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006310 }
John Zulauf4edde622021-02-15 08:54:50 -07006311 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006312}
6313
John Zulauf4edde622021-02-15 08:54:50 -07006314void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6315 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6316 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6317 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006318 for (uint32_t index = 0; index < barrier_count; index++) {
6319 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006320 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006321 if (buffer) {
6322 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6323 const auto range = MakeRange(barrier.offset, barrier_size);
6324 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006325 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006326 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006327 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006328 }
6329 }
6330}
6331
John Zulauf4edde622021-02-15 08:54:50 -07006332void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006333 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006334 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006335 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006336 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006337 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6338 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6339 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006340 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006341 }
John Zulauf4edde622021-02-15 08:54:50 -07006342 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006343}
6344
John Zulauf4edde622021-02-15 08:54:50 -07006345void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6346 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006347 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006348 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006349 for (uint32_t index = 0; index < barrier_count; index++) {
6350 const auto &barrier = barriers[index];
6351 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6352 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006353 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006354 if (buffer) {
6355 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6356 const auto range = MakeRange(barrier.offset, barrier_size);
6357 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006358 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006359 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006360 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006361 }
6362 }
6363}
6364
John Zulauf4edde622021-02-15 08:54:50 -07006365void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6366 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6367 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6368 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006369 for (uint32_t index = 0; index < barrier_count; index++) {
6370 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006371 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006372 if (image) {
6373 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6374 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006375 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006376 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006377 image_memory_barriers.emplace_back();
6378 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006379 }
6380 }
6381}
John Zulaufd5115702021-01-18 12:34:33 -07006382
John Zulauf4edde622021-02-15 08:54:50 -07006383void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6384 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006385 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006386 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006387 for (uint32_t index = 0; index < barrier_count; index++) {
6388 const auto &barrier = barriers[index];
6389 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6390 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006391 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006392 if (image) {
6393 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6394 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006395 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006396 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006397 image_memory_barriers.emplace_back();
6398 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006399 }
6400 }
6401}
6402
sjfricke0bea06e2022-06-05 09:22:26 +09006403SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6404 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6405 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6406 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6407 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6408 const VkImageMemoryBarrier *pImageMemoryBarriers)
6409 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006410 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6411 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006412 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006413}
6414
sjfricke0bea06e2022-06-05 09:22:26 +09006415SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6416 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6417 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006418 MakeEventsList(sync_state, eventCount, pEvents);
6419 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6420}
6421
John Zulauf610e28c2021-08-03 17:46:23 -06006422const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6423
John Zulaufd5115702021-01-18 12:34:33 -07006424bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006425 bool skip = false;
6426 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006427 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006428
John Zulauf610e28c2021-08-03 17:46:23 -06006429 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006430 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6431 const auto &barrier_set = barriers_[barrier_set_index];
6432 if (barrier_set.single_exec_scope) {
6433 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6434 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6435 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6436 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6437 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6438 } else {
6439 const auto &barriers = barrier_set.memory_barriers;
6440 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6441 const auto &barrier = barriers[barrier_index];
6442 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6443 const std::string vuid =
6444 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6445 skip =
6446 sync_state.LogInfo(command_buffer_handle, vuid,
6447 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6448 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6449 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6450 }
6451 }
6452 }
6453 }
John Zulaufd5115702021-01-18 12:34:33 -07006454 }
6455
John Zulauf610e28c2021-08-03 17:46:23 -06006456 // The rest is common to record time and replay time.
6457 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6458 return skip;
6459}
6460
John Zulaufbb890452021-12-14 11:30:18 -07006461bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006462 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006463 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006464 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006465
Jeremy Gebben40a22942020-12-22 14:22:06 -07006466 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006467 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006468 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006469 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006470 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006471 size_t barrier_set_index = 0;
6472 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006473 for (const auto &event : events_) {
6474 const auto *sync_event = events_context->Get(event.get());
6475 const auto &barrier_set = barriers_[barrier_set_index];
6476 if (!sync_event) {
6477 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6478 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6479 // new validation error... wait without previously submitted set event...
6480 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 -07006481 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006482 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006483 }
John Zulauf610e28c2021-08-03 17:46:23 -06006484
6485 // For replay calls, don't revalidate "same command buffer" events
6486 if (sync_event->last_command_tag > base_tag) continue;
6487
John Zulauf78394fc2021-07-12 15:41:40 -06006488 const auto event_handle = sync_event->event->event();
6489 // TODO add "destroyed" checks
6490
John Zulaufe0757ba2022-06-10 16:51:45 -06006491 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006492 // Only accumulate barrier and event stages if there is a pending set in the current context
6493 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6494 event_stage_masks |= sync_event->scope.mask_param;
6495 }
6496
John Zulauf78394fc2021-07-12 15:41:40 -06006497 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006498
sjfricke0bea06e2022-06-05 09:22:26 +09006499 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006500 if (ignore_reason) {
6501 switch (ignore_reason) {
6502 case SyncEventState::ResetWaitRace:
6503 case SyncEventState::Reset2WaitRace: {
6504 // Four permuations of Reset and Wait calls...
6505 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006506 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006507 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006508 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6509 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006510 }
6511 const char *const message =
6512 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6513 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6514 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006515 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006516 break;
6517 }
6518 case SyncEventState::SetRace: {
6519 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6520 // this event
6521 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6522 const char *const message =
6523 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6524 const char *const reason = "First synchronization scope is undefined.";
6525 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6526 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006527 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006528 break;
6529 }
6530 case SyncEventState::MissingStageBits: {
6531 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6532 // Issue error message that event waited for is not in wait events scope
6533 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6534 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6535 ". Bits missing from srcStageMask %s. %s";
6536 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6537 sync_state.report_data->FormatHandle(event_handle).c_str(),
6538 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006539 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006540 break;
6541 }
6542 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006543 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006544 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6545 sync_state.report_data->FormatHandle(event_handle).c_str(),
6546 CommandTypeString(sync_event->last_command));
6547 break;
6548 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006549 case SyncEventState::MissingSetEvent: {
6550 // TODO: There are conditions at queue submit time where we can definitively say that
6551 // a missing set event is an error. Add those if not captured in CoreChecks
6552 break;
6553 }
John Zulauf78394fc2021-07-12 15:41:40 -06006554 default:
6555 assert(ignore_reason == SyncEventState::NotIgnored);
6556 }
6557 } else if (barrier_set.image_memory_barriers.size()) {
6558 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006559 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006560 assert(context);
6561 for (const auto &image_memory_barrier : image_memory_barriers) {
6562 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6563 const auto *image_state = image_memory_barrier.image.get();
6564 if (!image_state) continue;
6565 const auto &subresource_range = image_memory_barrier.range;
6566 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006567 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6568 src_access_scope, queue_id, *sync_event,
6569 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006570 if (hazard.hazard) {
6571 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6572 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6573 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6574 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006575 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006576 break;
6577 }
6578 }
6579 }
6580 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6581 // 03839
6582 barrier_set_index += barrier_set_incr;
6583 }
John Zulaufd5115702021-01-18 12:34:33 -07006584
6585 // 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 -07006586 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 -07006587 if (extra_stage_bits) {
6588 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006589 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6590 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006591 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006592 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006593 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006594 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006595 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006596 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006597 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006598 " vkCmdSetEvent may be in previously submitted command buffer.");
6599 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006600 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006601 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006602 }
6603 }
6604 return skip;
6605}
6606
6607struct SyncOpWaitEventsFunctorFactory {
6608 using BarrierOpFunctor = WaitEventBarrierOp;
6609 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6610 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6611 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6612 using BufferRange = EventSimpleRangeGenerator;
6613 using ImageRange = EventImageRangeGenerator;
6614 using GlobalRange = EventSimpleRangeGenerator;
6615
6616 // Need to restrict to only valid exec and access scope for this event
6617 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6618 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006619 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006620 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6621 return barrier;
6622 }
John Zulauf00119522022-05-23 19:07:42 -06006623 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006624 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006625 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006626 }
John Zulauf14940722021-04-12 15:19:02 -06006627 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006628 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6629 }
John Zulauf00119522022-05-23 19:07:42 -06006630 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006631 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006632 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006633 }
6634
6635 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6636 const AccessAddressType address_type = GetAccessAddressType(buffer);
6637 const auto base_address = ResourceBaseAddress(buffer);
6638 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6639 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6640 return filtered_range_gen;
6641 }
John Zulauf110413c2021-03-20 05:38:38 -06006642 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006643 if (!SimpleBinding(image)) return ImageRange();
6644 const auto address_type = GetAccessAddressType(image);
6645 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006646 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6647 false);
John Zulaufd5115702021-01-18 12:34:33 -07006648 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6649
6650 return filtered_range_gen;
6651 }
6652 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6653 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6654 }
6655 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6656 SyncEventState *sync_event;
6657};
6658
John Zulaufdab327f2022-07-08 12:02:05 -06006659ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006660 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006661
John Zulauf0223f142022-07-06 09:05:39 -06006662 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006663 return tag;
6664}
6665
John Zulauf0223f142022-07-06 09:05:39 -06006666void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006667 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6668 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6669 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
John Zulauf0223f142022-07-06 09:05:39 -06006670 if (!exec_context.ValidForSyncOps()) return;
6671 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6672 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6673 const QueueId queue_id = exec_context.GetQueueId();
6674
John Zulaufd5115702021-01-18 12:34:33 -07006675 access_context->ResolvePreviousAccesses();
6676
John Zulauf4edde622021-02-15 08:54:50 -07006677 size_t barrier_set_index = 0;
6678 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6679 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006680 for (auto &event_shared : events_) {
6681 if (!event_shared.get()) continue;
6682 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006683
sjfricke0bea06e2022-06-05 09:22:26 +09006684 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006685 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006686
John Zulauf4edde622021-02-15 08:54:50 -07006687 const auto &barrier_set = barriers_[barrier_set_index];
6688 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006689 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006690 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6691 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6692 // of the barriers is maintained.
6693 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006694 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6695 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6696 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006697
6698 // Apply the global barrier to the event itself (for race condition tracking)
6699 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6700 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6701 sync_event->barriers |= dst.exec_scope;
6702 } else {
6703 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6704 sync_event->barriers = 0U;
6705 }
John Zulauf4edde622021-02-15 08:54:50 -07006706 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006707 }
6708
6709 // Apply the pending barriers
6710 ResolvePendingBarrierFunctor apply_pending_action(tag);
6711 access_context->ApplyToContext(apply_pending_action);
6712}
6713
John Zulauf8eda1562021-04-13 17:06:41 -06006714bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006715 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6716 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006717}
6718
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006719bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6720 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6721 bool skip = false;
6722 const auto *cb_access_context = GetAccessContext(commandBuffer);
6723 assert(cb_access_context);
6724 if (!cb_access_context) return skip;
6725
6726 const auto *context = cb_access_context->GetCurrentAccessContext();
6727 assert(context);
6728 if (!context) return skip;
6729
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006730 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006731
6732 if (dst_buffer) {
6733 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6734 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6735 if (hazard.hazard) {
6736 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6737 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6738 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006739 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006740 }
6741 }
6742 return skip;
6743}
6744
John Zulauf669dfd52021-01-27 17:15:28 -07006745void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006746 events_.reserve(event_count);
6747 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006748 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006749 }
6750}
John Zulauf6ce24372021-01-30 05:56:25 -07006751
sjfricke0bea06e2022-06-05 09:22:26 +09006752SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006753 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006754 : SyncOpBase(cmd_type),
6755 event_(sync_state.Get<EVENT_STATE>(event)),
6756 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006757
John Zulauf1bf30522021-09-03 15:39:06 -06006758bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6759 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6760}
6761
John Zulaufbb890452021-12-14 11:30:18 -07006762bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6763 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006764 assert(events_context);
6765 bool skip = false;
6766 if (!events_context) return skip;
6767
John Zulaufbb890452021-12-14 11:30:18 -07006768 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006769 const auto *sync_event = events_context->Get(event_);
6770 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6771
John Zulauf1bf30522021-09-03 15:39:06 -06006772 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6773
John Zulauf6ce24372021-01-30 05:56:25 -07006774 const char *const set_wait =
6775 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6776 "hazards.";
6777 const char *message = set_wait; // Only one message this call.
6778 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6779 const char *vuid = nullptr;
6780 switch (sync_event->last_command) {
6781 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006782 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006783 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006784 // Needs a barrier between set and reset
6785 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6786 break;
John Zulauf4edde622021-02-15 08:54:50 -07006787 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006788 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006789 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006790 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6791 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6792 break;
6793 }
6794 default:
6795 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006796 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6797 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006798 break;
6799 }
6800 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006801 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6802 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006803 CommandTypeString(sync_event->last_command));
6804 }
6805 }
6806 return skip;
6807}
6808
John Zulaufdab327f2022-07-08 12:02:05 -06006809ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006810 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006811 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006812 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006813}
6814
John Zulauf8eda1562021-04-13 17:06:41 -06006815bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006816 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6817 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006818}
6819
John Zulauf0223f142022-07-06 09:05:39 -06006820void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6821 if (!exec_context.ValidForSyncOps()) return;
6822 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6823
John Zulaufe0757ba2022-06-10 16:51:45 -06006824 auto *sync_event = events_context->GetFromShared(event_);
6825 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6826
6827 // Update the event state
6828 sync_event->last_command = cmd_type_;
6829 sync_event->last_command_tag = tag;
6830 sync_event->unsynchronized_set = CMD_NONE;
6831 sync_event->ResetFirstScope();
6832 sync_event->barriers = 0U;
6833}
John Zulauf8eda1562021-04-13 17:06:41 -06006834
sjfricke0bea06e2022-06-05 09:22:26 +09006835SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006836 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006837 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006838 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006839 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006840 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006841 dep_info_() {
6842 // Snapshot the current access_context for later inspection at wait time.
6843 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6844 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6845 // or Submit time reference.
6846 if (access_context) {
6847 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6848 }
6849}
John Zulauf4edde622021-02-15 08:54:50 -07006850
sjfricke0bea06e2022-06-05 09:22:26 +09006851SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006852 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006853 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006854 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006855 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006856 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006857 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6858 if (access_context) {
6859 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6860 }
6861}
John Zulauf6ce24372021-01-30 05:56:25 -07006862
6863bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006864 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6865}
6866bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006867 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6868 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006869}
6870
John Zulaufbb890452021-12-14 11:30:18 -07006871bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006872 bool skip = false;
6873
John Zulaufbb890452021-12-14 11:30:18 -07006874 const auto &sync_state = exec_context.GetSyncState();
6875 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006876 assert(events_context);
6877 if (!events_context) return skip;
6878
6879 const auto *sync_event = events_context->Get(event_);
6880 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6881
John Zulauf610e28c2021-08-03 17:46:23 -06006882 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6883
John Zulauf6ce24372021-01-30 05:56:25 -07006884 const char *const reset_set =
6885 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6886 "hazards.";
6887 const char *const wait =
6888 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6889
6890 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006891 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006892 const char *message = nullptr;
6893 switch (sync_event->last_command) {
6894 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006895 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006896 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006897 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006898 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006899 message = reset_set;
6900 break;
6901 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006902 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006903 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006904 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006905 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006906 message = reset_set;
6907 break;
6908 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006909 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006910 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006911 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006912 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006913 message = wait;
6914 break;
6915 default:
6916 // The only other valid last command that wasn't one.
6917 assert(sync_event->last_command == CMD_NONE);
6918 break;
6919 }
John Zulauf4edde622021-02-15 08:54:50 -07006920 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006921 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006922 std::string vuid("SYNC-");
6923 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006924 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6925 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006926 CommandTypeString(sync_event->last_command));
6927 }
6928 }
6929
6930 return skip;
6931}
6932
John Zulaufdab327f2022-07-08 12:02:05 -06006933ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006934 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006935 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006936 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006937 assert(recorded_context_);
6938 if (recorded_context_ && events_context) {
6939 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006940 }
6941 return tag;
6942}
John Zulauf6ce24372021-01-30 05:56:25 -07006943
John Zulauf0223f142022-07-06 09:05:39 -06006944void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006945 // Create a copy of the current context, and merge in the state snapshot at record set event time
6946 // Note: we mustn't change the recorded context copy, as a given CB could be submitted more than once (in generaL)
John Zulauf0223f142022-07-06 09:05:39 -06006947 if (!exec_context.ValidForSyncOps()) return;
6948 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6949 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6950 const QueueId queue_id = exec_context.GetQueueId();
6951
John Zulaufe0757ba2022-06-10 16:51:45 -06006952 auto merged_context = std::make_shared<AccessContext>(*access_context);
6953 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6954 DoRecord(queue_id, tag, merged_context, events_context);
6955}
6956
6957void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6958 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006959 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006960 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006961
6962 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6963 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6964 // any issues caused by naive scope setting here.
6965
6966 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6967 // Given:
6968 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6969 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6970
6971 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6972 sync_event->unsynchronized_set = sync_event->last_command;
6973 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006974 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006975 // We only set the scope if there isn't one
6976 sync_event->scope = src_exec_scope_;
6977
John Zulaufe0757ba2022-06-10 16:51:45 -06006978 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6979 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006980 sync_event->unsynchronized_set = CMD_NONE;
6981 sync_event->first_scope_tag = tag;
6982 }
John Zulauf4edde622021-02-15 08:54:50 -07006983 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006984 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006985 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006986 sync_event->barriers = 0U;
6987}
John Zulauf64ffe552021-02-06 10:25:07 -07006988
sjfricke0bea06e2022-06-05 09:22:26 +09006989SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006990 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006991 const VkSubpassBeginInfo *pSubpassBeginInfo)
John Zulaufdab327f2022-07-08 12:02:05 -06006992 : SyncOpBase(cmd_type), rp_context_(nullptr) {
John Zulauf64ffe552021-02-06 10:25:07 -07006993 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006994 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006995 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006996 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006997 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006998 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006999 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
7000 // Note that this a safe to presist as long as shared_attachments is not cleared
7001 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08007002 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07007003 attachments_.emplace_back(attachment.get());
7004 }
7005 }
7006 if (pSubpassBeginInfo) {
7007 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
7008 }
7009 }
7010}
7011
7012bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7013 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
7014 bool skip = false;
7015
7016 assert(rp_state_.get());
7017 if (nullptr == rp_state_.get()) return skip;
7018 auto &rp_state = *rp_state_.get();
7019
7020 const uint32_t subpass = 0;
7021
7022 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
7023 // hasn't happened yet)
7024 const std::vector<AccessContext> empty_context_vector;
7025 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
7026 cb_context.GetCurrentAccessContext());
7027
7028 // Validate attachment operations
7029 if (attachments_.size() == 0) return skip;
7030 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007031
7032 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7033 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7034 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7035 // operations (though it's currently a messy approach)
7036 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007037 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007038
7039 // Validate load operations if there were no layout transition hazards
7040 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007041 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007042 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007043 }
7044
7045 return skip;
7046}
7047
John Zulaufdab327f2022-07-08 12:02:05 -06007048ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) {
John Zulauf64ffe552021-02-06 10:25:07 -07007049 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007050 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
John Zulaufdab327f2022-07-08 12:02:05 -06007051 const ResourceUsageTag begin_tag =
7052 cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
7053
7054 // Note: this state update must be after RecordBeginRenderPass as there is no current render pass until that function runs
7055 rp_context_ = cb_context->GetCurrentRenderPassContext();
7056
7057 return begin_tag;
John Zulauf64ffe552021-02-06 10:25:07 -07007058}
7059
John Zulauf8eda1562021-04-13 17:06:41 -06007060bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007061 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007062 return false;
7063}
7064
John Zulaufdab327f2022-07-08 12:02:05 -06007065void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7066 // Need to update the exec_contexts state (which for RenderPass operations *must* be a QueueBatchContext, as
7067 // render pass operations are not allowed in secondary command buffers.
7068 const QueueId queue_id = exec_context.GetQueueId();
7069 assert(queue_id != QueueSyncState::kQueueIdInvalid); // Renderpass replay only valid at submit (not exec) time
7070 if (queue_id == QueueSyncState::kQueueIdInvalid) return;
7071
7072 exec_context.BeginRenderPassReplay(*this, tag);
7073}
John Zulauf8eda1562021-04-13 17:06:41 -06007074
sjfricke0bea06e2022-06-05 09:22:26 +09007075SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7076 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7077 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007078 if (pSubpassBeginInfo) {
7079 subpass_begin_info_.initialize(pSubpassBeginInfo);
7080 }
7081 if (pSubpassEndInfo) {
7082 subpass_end_info_.initialize(pSubpassEndInfo);
7083 }
7084}
7085
7086bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7087 bool skip = false;
7088 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7089 if (!renderpass_context) return skip;
7090
sjfricke0bea06e2022-06-05 09:22:26 +09007091 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007092 return skip;
7093}
7094
John Zulaufdab327f2022-07-08 12:02:05 -06007095ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007096 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007097}
7098
7099bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007100 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007101 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007102}
7103
sjfricke0bea06e2022-06-05 09:22:26 +09007104SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7105 const VkSubpassEndInfo *pSubpassEndInfo)
7106 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007107 if (pSubpassEndInfo) {
7108 subpass_end_info_.initialize(pSubpassEndInfo);
7109 }
7110}
7111
John Zulaufdab327f2022-07-08 12:02:05 -06007112void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7113 exec_context.NextSubpassReplay();
7114}
John Zulauf8eda1562021-04-13 17:06:41 -06007115
John Zulauf64ffe552021-02-06 10:25:07 -07007116bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7117 bool skip = false;
7118 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7119
7120 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007121 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007122 return skip;
7123}
7124
John Zulaufdab327f2022-07-08 12:02:05 -06007125ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007126 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007127}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007128
John Zulauf8eda1562021-04-13 17:06:41 -06007129bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007130 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007131 return false;
7132}
7133
John Zulaufdab327f2022-07-08 12:02:05 -06007134void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7135 exec_context.EndRenderPassReplay();
7136}
John Zulauf8eda1562021-04-13 17:06:41 -06007137
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007138void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7139 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7140 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7141 auto *cb_access_context = GetAccessContext(commandBuffer);
7142 assert(cb_access_context);
7143 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7144 auto *context = cb_access_context->GetCurrentAccessContext();
7145 assert(context);
7146
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007147 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007148
7149 if (dst_buffer) {
7150 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7151 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7152 }
7153}
John Zulaufd05c5842021-03-26 11:32:16 -06007154
John Zulaufae842002021-04-15 18:20:55 -06007155bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7156 const VkCommandBuffer *pCommandBuffers) const {
7157 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007158 const auto *cb_context = GetAccessContext(commandBuffer);
7159 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007160
7161 // Heavyweight, but we need a proxy copy of the active command buffer access context
7162 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007163
7164 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007165 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007166 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7167
John Zulaufae842002021-04-15 18:20:55 -06007168 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7169 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007170
7171 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7172 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007173 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007174
7175 // The barriers have already been applied in ValidatFirstUse
7176 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007177 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007178 }
7179
John Zulaufae842002021-04-15 18:20:55 -06007180 return skip;
7181}
7182
7183void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7184 const VkCommandBuffer *pCommandBuffers) {
7185 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007186 auto *cb_context = GetAccessContext(commandBuffer);
7187 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007188 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007189 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007190 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7191 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007192 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007193 }
John Zulaufae842002021-04-15 18:20:55 -06007194}
7195
John Zulauf1d5f9c12022-05-13 14:51:08 -06007196void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7197 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7198 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7199
7200 const auto queue_state = GetQueueSyncStateShared(queue);
7201 if (!queue_state) return; // Invalid queue
7202 QueueId waited_queue = queue_state->GetQueueId();
John Zulauf3da08bb2022-08-01 17:56:56 -06007203 ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007204
John Zulauf3da08bb2022-08-01 17:56:56 -06007205 // Eliminate waitable fences from the current queue.
7206 layer_data::EraseIf(waitable_fences_, [waited_queue](const SignaledFence &sf) { return sf.second.queue_id == waited_queue; });
John Zulauf1d5f9c12022-05-13 14:51:08 -06007207}
7208
7209void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7210 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007211
7212 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7213 for (auto &batch : queue_batch_contexts) {
7214 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007215 }
7216
John Zulauf3da08bb2022-08-01 17:56:56 -06007217 // As we we've waited for everything on device, any waits are mooted.
7218 waitable_fences_.clear();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007219}
7220
John Zulauf697c0e12022-04-19 16:31:12 -06007221struct QueueSubmitCmdState {
7222 std::shared_ptr<const QueueSyncState> queue;
7223 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007224 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007225 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007226 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7227 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007228};
7229
7230template <>
7231thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7232
John Zulaufbbda4572022-04-19 16:20:45 -06007233bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7234 VkFence fence) const {
7235 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007236
7237 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007238 if (!enabled[sync_validation_queue_submit]) return skip;
7239
John Zulauf00119522022-05-23 19:07:42 -06007240 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007241 const auto fence_state = Get<FENCE_STATE>(fence);
7242 cmd_state->queue = GetQueueSyncStateShared(queue);
7243 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007244
John Zulauf697c0e12022-04-19 16:31:12 -06007245 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7246 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7247
7248 // verify each submit batch
7249 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7250 // most recently created batch
7251 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7252 std::shared_ptr<QueueBatchContext> batch;
7253 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7254 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007255 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7256 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007257
John Zulaufe0757ba2022-06-10 16:51:45 -06007258 // Skip import and validation of empty batches
7259 if (batch->GetTagRange().size()) {
7260 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007261
John Zulaufe0757ba2022-06-10 16:51:45 -06007262 // For each submit in the batch...
7263 for (const auto &cb : *batch) {
7264 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
John Zulauf0223f142022-07-06 09:05:39 -06007265 skip |= cb.cb->ValidateFirstUse(*batch.get(), "vkQueueSubmit", cb.index);
John Zulaufe0757ba2022-06-10 16:51:45 -06007266
7267 // The barriers have already been applied in ValidatFirstUse
7268 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7269 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7270 }
John Zulauf697c0e12022-04-19 16:31:12 -06007271 }
7272
John Zulaufe0757ba2022-06-10 16:51:45 -06007273 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007274 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7275 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007276 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007277 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007278 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7279 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7280 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007281 }
7282 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7283 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7284 last_batch = batch;
7285 }
7286 // The most recently created batch will become the queue's "last batch" in the record phase
7287 if (batch) {
7288 cmd_state->last_batch = std::move(batch);
7289 }
7290
7291 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007292 return skip;
7293}
7294
7295void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7296 VkResult result) {
7297 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007298
John Zulaufcb7e1672022-05-04 13:46:08 -06007299 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007300 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7301
John Zulaufcb7e1672022-05-04 13:46:08 -06007302 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7303 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007304 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007305
7306 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007307 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7308
John Zulauf697c0e12022-04-19 16:31:12 -06007309 // Don't need to look up the queue state again, but we need a non-const version
7310 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007311
John Zulaufcb7e1672022-05-04 13:46:08 -06007312 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7313 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7314 // QBC's are those referenced by unwaited signals and the last batch.
7315 for (auto &sig_sem : cmd_state->signaled) {
7316 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007317 auto &sig_batch = sig_sem.second->batch;
7318 sig_batch->ResetAccessLog();
7319 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7320 if (sig_batch != cmd_state->last_batch) {
7321 sig_batch->ResetEventsContext();
7322 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007323 }
7324 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007325 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007326 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007327
John Zulaufcb7e1672022-05-04 13:46:08 -06007328 // Update the queue to point to the last batch from the submit
7329 if (cmd_state->last_batch) {
7330 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007331
7332 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7333 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7334 auto last_batch = queue_state->LastBatch();
7335 if (last_batch) {
7336 last_batch->ResetEventsContext();
7337 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007338 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007339 }
7340
7341 // Update the global access log from the one built during validation
7342 global_access_log_.MergeMove(std::move(cmd_state->logger));
7343
John Zulauf3da08bb2022-08-01 17:56:56 -06007344 ResourceUsageRange fence_tag_range = ReserveGlobalTagRange(1U);
7345 UpdateFenceWaitInfo(fence, queue_state->GetQueueId(), fence_tag_range.begin);
John Zulaufbbda4572022-04-19 16:20:45 -06007346}
7347
7348bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7349 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007350 bool skip = false;
7351 if (!enabled[sync_validation_queue_submit]) return skip;
7352
John Zulauf697c0e12022-04-19 16:31:12 -06007353 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007354 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007355}
7356
7357void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7358 VkFence fence, VkResult result) {
7359 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007360 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7361
7362 if (!enabled[sync_validation_queue_submit]) return;
7363
John Zulauf697c0e12022-04-19 16:31:12 -06007364 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007365}
7366
John Zulauf3da08bb2022-08-01 17:56:56 -06007367void SyncValidator::PostCallRecordGetFenceStatus(VkDevice device, VkFence fence, VkResult result) {
7368 StateTracker::PostCallRecordGetFenceStatus(device, fence, result);
7369 if (!enabled[sync_validation_queue_submit]) return;
7370 if (result == VK_SUCCESS) {
7371 // fence is signalled, mark it as waited for
7372 WaitForFence(fence);
7373 }
7374}
7375
7376void SyncValidator::PostCallRecordWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
7377 uint64_t timeout, VkResult result) {
7378 StateTracker::PostCallRecordWaitForFences(device, fenceCount, pFences, waitAll, timeout, result);
7379 if (!enabled[sync_validation_queue_submit]) return;
7380 if ((result == VK_SUCCESS) && ((VK_TRUE == waitAll) || (1 == fenceCount))) {
7381 // We can only know the pFences have signal if we waited for all of them, or there was only one of them
7382 for (uint32_t i = 0; i < fenceCount; i++) {
7383 WaitForFence(pFences[i]);
7384 }
7385 }
7386}
7387
John Zulaufd0ec59f2021-03-13 14:25:08 -07007388AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7389 : view_(view), view_mask_(), gen_store_() {
7390 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7391 const IMAGE_STATE &image_state = *view_->image_state.get();
7392 const auto base_address = ResourceBaseAddress(image_state);
7393 const auto *encoder = image_state.fragment_encoder.get();
7394 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007395 // Get offset and extent for the view, accounting for possible depth slicing
7396 const VkOffset3D zero_offset = view->GetOffset();
7397 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007398 // Intentional copy
7399 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7400 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007401 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7402 view->IsDepthSliced());
7403 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007404
7405 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7406 if (depth && (depth != view_mask_)) {
7407 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007408 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007409 }
7410 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7411 if (stencil && (stencil != view_mask_)) {
7412 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007413 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7414 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007415 }
7416}
7417
7418const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7419 const ImageRangeGen *got = nullptr;
7420 switch (gen_type) {
7421 case kViewSubresource:
7422 got = &gen_store_[kViewSubresource];
7423 break;
7424 case kRenderArea:
7425 got = &gen_store_[kRenderArea];
7426 break;
7427 case kDepthOnlyRenderArea:
7428 got =
7429 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7430 break;
7431 case kStencilOnlyRenderArea:
7432 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7433 : &gen_store_[Gen::kStencilOnlyRenderArea];
7434 break;
7435 default:
7436 assert(got);
7437 }
7438 return got;
7439}
7440
7441AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7442 assert(IsValid());
7443 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7444 if (depth_op) {
7445 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7446 if (stencil_op) {
7447 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7448 return kRenderArea;
7449 }
7450 return kDepthOnlyRenderArea;
7451 }
7452 if (stencil_op) {
7453 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7454 return kStencilOnlyRenderArea;
7455 }
7456
7457 assert(depth_op || stencil_op);
7458 return kRenderArea;
7459}
7460
7461AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007462
John Zulaufe0757ba2022-06-10 16:51:45 -06007463void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007464 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7465 for (auto &event_pair : map_) {
7466 assert(event_pair.second); // Shouldn't be storing empty
7467 auto &sync_event = *event_pair.second;
7468 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
John Zulaufe0757ba2022-06-10 16:51:45 -06007469 // But only if occuring before the tag
7470 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007471 sync_event.barriers |= dst.exec_scope;
7472 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7473 }
7474 }
7475}
John Zulaufbb890452021-12-14 11:30:18 -07007476
John Zulaufe0757ba2022-06-10 16:51:45 -06007477void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7478 const SyncExecScope src_scope =
7479 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7480 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7481 ApplyBarrier(src_scope, dst_scope, tag);
7482}
7483
7484SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7485 // We need a deep copy of the const context to update during validation phase
7486 for (const auto &event : from.map_) {
7487 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7488 }
7489 return *this;
7490}
7491
John Zulaufcb7e1672022-05-04 13:46:08 -06007492QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
John Zulaufdab327f2022-07-08 12:02:05 -06007493 : CommandExecutionContext(&sync_state),
7494 queue_state_(&queue_state),
7495 tag_range_(0, 0),
7496 current_access_context_(&access_context_),
7497 batch_log_(nullptr) {}
John Zulaufcb7e1672022-05-04 13:46:08 -06007498
John Zulauf697c0e12022-04-19 16:31:12 -06007499template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007500void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7501 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007502 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007503 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007504}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007505void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007506 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007507}
John Zulauf697c0e12022-04-19 16:31:12 -06007508
7509VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7510
John Zulauf1d5f9c12022-05-13 14:51:08 -06007511void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
John Zulauf3da08bb2022-08-01 17:56:56 -06007512 ResourceAccessState::QueueTagPredicate predicate{queue_id, tag};
7513 access_context_.EraseIf([&predicate](ResourceAccessRangeMap::value_type &access) {
7514 // Apply..Wait returns true if the waited access is empty...
7515 return access.second.ApplyQueueTagWait(predicate);
7516 });
John Zulaufe0757ba2022-06-10 16:51:45 -06007517
7518 if (queue_id == GetQueueId()) {
7519 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7520 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007521}
7522
7523// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007524void QueueBatchContext::ApplyDeviceWait() {
7525 access_context_.Reset();
7526 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7527}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007528
John Zulaufdab327f2022-07-08 12:02:05 -06007529HazardResult QueueBatchContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
7530 // Queue batch handling requires dealing with renderpass state and picking the correct access context
7531 if (rp_replay_) {
7532 return rp_replay_.replay_context->DetectFirstUseHazard(GetQueueId(), tag_range, *current_access_context_);
7533 }
7534 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, access_context_);
7535}
7536
7537void QueueBatchContext::BeginRenderPassReplay(const SyncOpBeginRenderPass &begin_op, const ResourceUsageTag tag) {
7538 current_access_context_ = rp_replay_.Begin(GetQueueFlags(), begin_op, access_context_);
7539 current_access_context_->ResolvePreviousAccesses();
7540}
7541
7542void QueueBatchContext::NextSubpassReplay() {
7543 current_access_context_ = rp_replay_.Next();
7544 current_access_context_->ResolvePreviousAccesses();
7545}
7546
7547void QueueBatchContext::EndRenderPassReplay() {
7548 rp_replay_.End(access_context_);
7549 current_access_context_ = &access_context_;
7550}
7551
7552AccessContext *QueueBatchContext::RenderPassReplayState::Begin(VkQueueFlags queue_flags, const SyncOpBeginRenderPass &begin_op_,
7553 const AccessContext &external_context) {
7554 Reset();
7555
7556 begin_op = &begin_op_;
7557 subpass = 0;
7558
7559 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7560 assert(rp_context);
7561 replay_context = &rp_context->GetContexts()[0];
7562
7563 InitSubpassContexts(queue_flags, *rp_context->GetRenderPassState(), &external_context, subpass_contexts);
7564 return &subpass_contexts[0];
7565}
7566
7567AccessContext *QueueBatchContext::RenderPassReplayState::Next() {
7568 subpass++;
7569
7570 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7571
7572 replay_context = &rp_context->GetContexts()[subpass];
7573 return &subpass_contexts[subpass];
7574}
7575
7576void QueueBatchContext::RenderPassReplayState::End(AccessContext &external_context) {
7577 external_context.ResolveChildContexts(subpass_contexts);
7578 Reset();
7579}
7580
John Zulaufecf4ac52022-06-06 10:08:42 -06007581class ApplySemaphoreBarrierAction {
7582 public:
7583 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7584 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7585
7586 private:
7587 const SemaphoreScope &signal_;
7588 const SemaphoreScope wait_;
7589};
7590
7591std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7592 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007593 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007594 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007595
John Zulaufcb7e1672022-05-04 13:46:08 -06007596 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7597 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007598 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007599
John Zulaufecf4ac52022-06-06 10:08:42 -06007600 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007601
John Zulaufecf4ac52022-06-06 10:08:42 -06007602 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007603 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007604 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7605 if (signal_scope.queue == wait_scope.queue) {
7606 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7607 // valid accesses for the sync scope.
7608 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7609 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7610 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007611 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007612 } else {
7613 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7614 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007615 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007616 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7617 // enforce deep constness.
7618 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007619}
7620
7621// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7622template <>
7623class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7624 public:
7625 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7626 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7627 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7628 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7629 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7630 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7631
7632 private:
7633 const VkSubmitInfo &info_;
7634};
7635template <typename BatchInfo, typename Fn>
7636void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7637 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7638 Accessor batch(batch_info);
7639 const uint32_t wait_count = batch.WaitSemaphoreCount();
7640 for (uint32_t i = 0; i < wait_count; ++i) {
7641 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7642 }
7643}
7644
7645template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007646void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7647 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007648 // Copy in the event state from the previous batch (on this queue)
7649 if (prev) {
7650 events_context_.DeepCopy(prev->events_context_);
7651 }
7652
John Zulaufecf4ac52022-06-06 10:08:42 -06007653 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7654 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7655 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7656 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7657 if (resolved) {
7658 batches_resolved.emplace(std::move(resolved));
7659 }
John Zulauf697c0e12022-04-19 16:31:12 -06007660 });
7661
John Zulaufecf4ac52022-06-06 10:08:42 -06007662 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7663 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7664 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007665 }
7666
John Zulauf697c0e12022-04-19 16:31:12 -06007667 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007668 async_batches_ =
7669 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7670 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007671 });
7672 for (const auto &async_batch : async_batches_) {
7673 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7674 }
7675}
7676
7677template <typename BatchInfo>
7678void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7679 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7680 Accessor batch(batch_info);
7681
7682 // Create the list of command buffers to submit
7683 const uint32_t cb_count = batch.CommandBufferCount();
7684 command_buffers_.reserve(cb_count);
7685 for (uint32_t index = 0; index < cb_count; ++index) {
7686 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7687 if (cb_context) {
7688 tag_range_.end += cb_context->GetTagLimit();
7689 command_buffers_.emplace_back(index, std::move(cb_context));
7690 }
7691 }
7692}
7693
7694// Look up the usage informaiton from the local or global logger
7695std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7696 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7697 std::stringstream out;
7698 AccessLogger::AccessRecord access = use_logger[tag];
7699 if (access.IsValid()) {
7700 const AccessLogger::BatchRecord &batch = *access.batch;
7701 const ResourceUsageRecord &record = *access.record;
7702 // Queue and Batch information
7703 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7704 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7705
7706 // Commandbuffer Usages Information
7707 out << record;
7708 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7709 out << ", reset_no: " << std::to_string(record.reset_count);
7710 }
7711 return out.str();
7712}
7713
7714VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7715
John Zulauf00119522022-05-23 19:07:42 -06007716QueueId QueueBatchContext::GetQueueId() const {
7717 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7718 return id;
7719}
7720
John Zulauf697c0e12022-04-19 16:31:12 -06007721void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7722 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7723 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7724 SetTagBias(global_tags.begin);
7725 // Add an access log for the batches range and point the batch at it.
7726 logger_ = &logger;
7727 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7728}
7729
7730void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7731 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7732 batch_log_->Append(submitted_cb.GetAccessLog());
7733}
7734
7735void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7736 const auto size = tag_range_.size();
7737 tag_range_.begin = bias;
7738 tag_range_.end = bias + size;
7739 access_context_.SetStartTag(bias);
7740}
7741
John Zulauf697c0e12022-04-19 16:31:12 -06007742AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7743 const ResourceUsageRange &range) {
7744 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7745 assert(inserted.second);
7746 return &inserted.first->second;
7747}
7748
7749void AccessLogger::MergeMove(AccessLogger &&child) {
7750 for (auto &range : child.access_log_map_) {
7751 BatchLog &child_batch = range.second;
7752 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7753 insert_pair.first->second = std::move(child_batch);
7754 assert(insert_pair.second);
7755 }
7756 child.Reset();
7757}
7758
7759void AccessLogger::Reset() {
7760 prev_ = nullptr;
7761 access_log_map_.clear();
7762}
7763
7764// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7765// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7766// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7767// the contexts Resolve all history from previous all contexts when created
7768void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7769 last_batch_ = std::move(last);
7770 last_batch_->ResetAccessLog();
7771}
7772
7773// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7774// scope state.
7775// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7776// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7777uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7778
7779void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7780 log_.insert(log_.end(), other.cbegin(), other.cend());
7781 for (const auto &record : other) {
7782 assert(record.cb_state);
7783 cbs_referenced_.insert(record.cb_state->shared_from_this());
7784 }
7785}
7786
7787AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7788 assert(index < log_.size());
7789 return AccessRecord{&batch_, &log_[index]};
7790}
7791
7792AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7793 AccessRecord access_record = {nullptr, nullptr};
7794
7795 auto found_range = access_log_map_.find(tag);
7796 if (found_range != access_log_map_.cend()) {
7797 const ResourceUsageTag bias = found_range->first.begin;
7798 assert(tag >= bias);
7799 access_record = found_range->second[tag - bias];
7800 } else if (prev_) {
7801 access_record = (*prev_)[tag];
7802 }
7803
7804 return access_record;
7805}
John Zulaufcb7e1672022-05-04 13:46:08 -06007806
John Zulaufecf4ac52022-06-06 10:08:42 -06007807// This is a const method, force the returned value to be const
7808std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007809 std::shared_ptr<Signal> prev_state;
7810 if (prev_) {
7811 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7812 }
7813 return prev_state;
7814}
John Zulaufecf4ac52022-06-06 10:08:42 -06007815
7816SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7817 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7818 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7819 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7820 assert(batch);
7821 assert(sem_state);
7822}
John Zulauf3da08bb2022-08-01 17:56:56 -06007823
7824FenceSyncState::FenceSyncState() : fence(), tag(kInvalidTag), queue_id(QueueSyncState::kQueueIdInvalid) {}