blob: 2df8b200e3fa539fd644b105c2066b2bd699ad7b [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 Zulauf3d84f1b2020-03-09 13:33:25 -0600863// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
864// the DAG of the contexts (for example subpasses)
865template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600866HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600867 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600868 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600869
John Zulauf1a224292020-06-30 14:52:13 -0600870 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600871 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
872 // so we'll check these first
873 for (const auto &async_context : async_) {
874 hazard = async_context->DetectAsyncHazard(type, detector, range);
875 if (hazard.hazard) return hazard;
876 }
John Zulauf5f13a792020-03-10 07:31:21 -0600877 }
878
John Zulauf1a224292020-06-30 14:52:13 -0600879 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600880
John Zulauf69133422020-05-20 14:55:53 -0600881 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600882 const auto the_end = accesses.cend(); // End is not invalidated
883 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600884 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600885
John Zulauf3cafbf72021-03-26 16:55:19 -0600886 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600887 // Cover any leading gap, or gap between entries
888 if (detect_prev) {
889 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
890 // Cover any leading gap, or gap between entries
891 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600892 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600893 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600894 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600895 if (hazard.hazard) return hazard;
896 }
John Zulauf69133422020-05-20 14:55:53 -0600897 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
898 gap.begin = pos->first.end;
899 }
900
901 hazard = detector.Detect(pos);
902 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600903 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600904 }
905
906 if (detect_prev) {
907 // Detect in the trailing empty as needed
908 gap.end = range.end;
909 if (gap.non_empty()) {
910 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600911 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600912 }
913
914 return hazard;
915}
916
917// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
918template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700919HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
920 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600921 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600922 auto pos = accesses.lower_bound(range);
923 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600924
John Zulauf3d84f1b2020-03-09 13:33:25 -0600925 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600926 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700927 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600928 if (hazard.hazard) break;
929 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600930 }
John Zulauf16adfc92020-04-08 10:28:33 -0600931
John Zulauf3d84f1b2020-03-09 13:33:25 -0600932 return hazard;
933}
934
John Zulaufb02c1eb2020-10-06 16:33:36 -0600935struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700936 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600937 void operator()(ResourceAccessState *access) const {
938 assert(access);
939 access->ApplyBarriers(barriers, true);
940 }
941 const std::vector<SyncBarrier> &barriers;
942};
943
John Zulaufe0757ba2022-06-10 16:51:45 -0600944struct QueueTagOffsetBarrierAction {
945 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
946 void operator()(ResourceAccessState *access) const {
947 access->OffsetTag(tag_offset);
948 access->SetQueueId(queue_id);
949 };
950 QueueId queue_id;
951 ResourceUsageTag tag_offset;
952};
953
John Zulauf22aefed2021-03-11 18:14:35 -0700954struct ApplyTrackbackStackAction {
955 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
956 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
957 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600958 void operator()(ResourceAccessState *access) const {
959 assert(access);
960 assert(!access->HasPendingState());
961 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600962 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
963 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700964 if (previous_barrier) {
965 assert(bool(*previous_barrier));
966 (*previous_barrier)(access);
967 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600968 }
969 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700970 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600971};
972
973// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
974// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
975// *different* map from dest.
976// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
977// range [first, last)
978template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600979static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
980 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600981 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600982 auto at = entry;
983 for (auto pos = first; pos != last; ++pos) {
984 // Every member of the input iterator range must fit within the remaining portion of entry
985 assert(at->first.includes(pos->first));
986 assert(at != dest->end());
987 // Trim up at to the same size as the entry to resolve
988 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600989 auto access = pos->second; // intentional copy
990 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600991 at->second.Resolve(access);
992 ++at; // Go to the remaining unused section of entry
993 }
994}
995
John Zulaufa0a98292020-09-18 09:30:10 -0600996static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
997 SyncBarrier merged = {};
998 for (const auto &barrier : barriers) {
999 merged.Merge(barrier);
1000 }
1001 return merged;
1002}
1003
John Zulaufb02c1eb2020-10-06 16:33:36 -06001004template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -07001005void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -06001006 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
1007 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001008 if (!range.non_empty()) return;
1009
John Zulauf355e49b2020-04-24 15:11:15 -06001010 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
1011 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001012 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001013 if (current->pos_B->valid) {
1014 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001015 auto access = src_pos->second; // intentional copy
1016 barrier_action(&access);
1017
John Zulauf16adfc92020-04-08 10:28:33 -06001018 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001019 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1020 trimmed->second.Resolve(access);
1021 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001022 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001023 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001024 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001025 }
John Zulauf16adfc92020-04-08 10:28:33 -06001026 } else {
1027 // we have to descend to fill this gap
1028 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001029 ResourceAccessRange recurrence_range = current_range;
1030 // The current context is empty for the current range, so recur to fill the gap.
1031 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1032 // is not valid, to minimize that recurrence
1033 if (current->pos_B.at_end()) {
1034 // Do the remainder here....
1035 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001036 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001037 // Recur only over the range until B becomes valid (within the limits of range).
1038 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001039 }
John Zulauf22aefed2021-03-11 18:14:35 -07001040 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1041
John Zulauf355e49b2020-04-24 15:11:15 -06001042 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1043 // iterator of the outer while.
1044
1045 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1046 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1047 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001048 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 -06001049 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001050 current.seek(seek_to);
1051 } else if (!current->pos_A->valid && infill_state) {
1052 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1053 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1054 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001055 }
John Zulauf5f13a792020-03-10 07:31:21 -06001056 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001057 if (current->range.non_empty()) {
1058 ++current;
1059 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001060 }
John Zulauf1a224292020-06-30 14:52:13 -06001061
1062 // Infill if range goes passed both the current and resolve map prior contents
1063 if (recur_to_infill && (current->range.end < range.end)) {
1064 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001065 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001066 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001067}
1068
John Zulauf22aefed2021-03-11 18:14:35 -07001069template <typename BarrierAction>
1070void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1071 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1072 const BarrierAction &previous_barrier) const {
1073 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1074 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1075}
1076
John Zulauf43cc7462020-12-03 12:33:12 -07001077void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001078 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1079 const ResourceAccessStateFunction *previous_barrier) const {
1080 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001081 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001082 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1083 ResourceAccessState state_copy;
1084 if (previous_barrier) {
1085 assert(bool(*previous_barrier));
1086 state_copy = *infill_state;
1087 (*previous_barrier)(&state_copy);
1088 infill_state = &state_copy;
1089 }
1090 sparse_container::update_range_value(*descent_map, range, *infill_state,
1091 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001092 }
1093 } else {
1094 // Look for something to fill the gap further along.
1095 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001096 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001097 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001098 }
John Zulauf5f13a792020-03-10 07:31:21 -06001099 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001100}
1101
John Zulauf4a6105a2020-11-17 15:11:05 -07001102// Non-lazy import of all accesses, WaitEvents needs this.
1103void AccessContext::ResolvePreviousAccesses() {
1104 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001105 if (!prev_.size()) return; // If no previous contexts, nothing to do
1106
John Zulauf4a6105a2020-11-17 15:11:05 -07001107 for (const auto address_type : kAddressTypes) {
1108 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1109 }
1110}
1111
John Zulauf43cc7462020-12-03 12:33:12 -07001112AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1113 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001114}
1115
John Zulauf1507ee42020-05-18 11:33:09 -06001116static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001117 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1118 ? SYNC_ACCESS_INDEX_NONE
1119 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1120 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001121 return stage_access;
1122}
1123static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001124 const auto stage_access =
1125 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1126 ? SYNC_ACCESS_INDEX_NONE
1127 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1128 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001129 return stage_access;
1130}
1131
John Zulauf7635de32020-05-29 17:14:15 -06001132// Caller must manage returned pointer
1133static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001134 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001135 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001136 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1137 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001138 return proxy;
1139}
1140
John Zulaufb02c1eb2020-10-06 16:33:36 -06001141template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001142void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1143 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1144 const ResourceAccessState *infill_state) const {
1145 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1146 if (!attachment_gen) return;
1147
1148 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1149 const AccessAddressType address_type = view_gen.GetAddressType();
1150 for (; range_gen->non_empty(); ++range_gen) {
1151 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001152 }
John Zulauf62f10592020-04-03 12:20:02 -06001153}
1154
John Zulauf1d5f9c12022-05-13 14:51:08 -06001155template <typename ResolveOp>
1156void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1157 const ResourceAccessState *infill_state, bool recur_to_infill) {
1158 for (auto address_type : kAddressTypes) {
1159 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1160 recur_to_infill);
1161 }
1162}
1163
John Zulauf7635de32020-05-29 17:14:15 -06001164// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001165bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001166 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001167 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001168 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001169 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1170 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1171 // those affects have not been recorded yet.
1172 //
1173 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1174 // to apply and only copy then, if this proves a hot spot.
1175 std::unique_ptr<AccessContext> proxy_for_prev;
1176 TrackBack proxy_track_back;
1177
John Zulauf355e49b2020-04-24 15:11:15 -06001178 const auto &transitions = rp_state.subpass_transitions[subpass];
1179 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001180 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1181
1182 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001183 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001184 if (prev_needs_proxy) {
1185 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001186 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001187 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001188 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001189 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001190 }
1191 track_back = &proxy_track_back;
1192 }
1193 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001194 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001195 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001196 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001197 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001198 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1199 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1200 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1201 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1202 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1203 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001204 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001205 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1206 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1207 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1208 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1209 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001210 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001211 }
John Zulauf355e49b2020-04-24 15:11:15 -06001212 }
1213 }
1214 return skip;
1215}
1216
John Zulaufbb890452021-12-14 11:30:18 -07001217bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001218 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001219 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001220 bool skip = false;
1221 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001222
John Zulauf1507ee42020-05-18 11:33:09 -06001223 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1224 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001225 const auto &view_gen = attachment_views[i];
1226 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001227 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001228
1229 // Need check in the following way
1230 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1231 // vs. transition
1232 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1233 // for each aspect loaded.
1234
1235 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001236 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001237 const bool is_color = !(has_depth || has_stencil);
1238
1239 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001240 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001241
John Zulaufaff20662020-06-01 14:07:58 -06001242 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001243 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001244
John Zulaufb02c1eb2020-10-06 16:33:36 -06001245 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001246 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001247 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001248 aspect = "color";
1249 } else {
John Zulauf57261402021-08-13 11:32:06 -06001250 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001251 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1252 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001253 aspect = "depth";
1254 }
John Zulauf57261402021-08-13 11:32:06 -06001255 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001256 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1257 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001258 aspect = "stencil";
1259 checked_stencil = true;
1260 }
1261 }
1262
1263 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001264 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001265 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001266 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001267 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001268 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001269 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001270 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1271 " aspect %s during load with loadOp %s.",
1272 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1273 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001274 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001275 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001276 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001277 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001278 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001279 }
1280 }
1281 }
1282 }
1283 return skip;
1284}
1285
John Zulaufaff20662020-06-01 14:07:58 -06001286// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1287// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1288// store is part of the same Next/End operation.
1289// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001290bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001291 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001292 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001293 bool skip = false;
1294 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001295
1296 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1297 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001298 const AttachmentViewGen &view_gen = attachment_views[i];
1299 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001300 const auto &ci = attachment_ci[i];
1301
1302 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1303 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1304 // sake, we treat DONT_CARE as writing.
1305 const bool has_depth = FormatHasDepth(ci.format);
1306 const bool has_stencil = FormatHasStencil(ci.format);
1307 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001308 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001309 if (!has_stencil && !store_op_stores) continue;
1310
1311 HazardResult hazard;
1312 const char *aspect = nullptr;
1313 bool checked_stencil = false;
1314 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001315 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1316 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001317 aspect = "color";
1318 } else {
John Zulauf57261402021-08-13 11:32:06 -06001319 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001320 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001321 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1322 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001323 aspect = "depth";
1324 }
1325 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001326 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1327 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001328 aspect = "stencil";
1329 checked_stencil = true;
1330 }
1331 }
1332
1333 if (hazard.hazard) {
1334 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1335 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001336 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1337 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1338 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001339 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1340 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001341 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001342 }
1343 }
1344 }
1345 return skip;
1346}
1347
John Zulaufbb890452021-12-14 11:30:18 -07001348bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001349 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001350 CMD_TYPE cmd_type, uint32_t subpass) const {
1351 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001352 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001353 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001354}
1355
John Zulauf06f6f1e2022-04-19 15:28:11 -06001356void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1357
John Zulauf3d84f1b2020-03-09 13:33:25 -06001358class HazardDetector {
1359 SyncStageAccessIndex usage_index_;
1360
1361 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001362 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001363 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001364 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001365 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001366 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001367};
1368
John Zulauf69133422020-05-20 14:55:53 -06001369class HazardDetectorWithOrdering {
1370 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001371 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001372
1373 public:
1374 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001375 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001376 }
John Zulauf14940722021-04-12 15:19:02 -06001377 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001378 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001379 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001380 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001381};
1382
John Zulauf16adfc92020-04-08 10:28:33 -06001383HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001384 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001385 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001386 const auto base_address = ResourceBaseAddress(buffer);
1387 HazardDetector detector(usage_index);
1388 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001389}
1390
John Zulauf69133422020-05-20 14:55:53 -06001391template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001392HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1393 DetectOptions options) const {
1394 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1395 if (!attachment_gen) return HazardResult();
1396
1397 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1398 const auto address_type = view_gen.GetAddressType();
1399 for (; range_gen->non_empty(); ++range_gen) {
1400 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1401 if (hazard.hazard) return hazard;
1402 }
1403
1404 return HazardResult();
1405}
1406
1407template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001408HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1409 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001410 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001411 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001412 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001413 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001414 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001415 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001416 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001417 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001418 if (hazard.hazard) return hazard;
1419 }
1420 return HazardResult();
1421}
John Zulauf110413c2021-03-20 05:38:38 -06001422template <typename Detector>
1423HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001424 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1425 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001426 if (!SimpleBinding(image)) return HazardResult();
1427 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001428 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1429 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001430 const auto address_type = ImageAddressType(image);
1431 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001432 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1433 if (hazard.hazard) return hazard;
1434 }
1435 return HazardResult();
1436}
John Zulauf69133422020-05-20 14:55:53 -06001437
John Zulauf540266b2020-04-06 18:54:53 -06001438HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1439 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001440 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001441 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1442 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001443 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001444 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001445}
1446
1447HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001448 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001449 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001450 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001451}
1452
John Zulaufd0ec59f2021-03-13 14:25:08 -07001453HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1454 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1455 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1456 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1457}
1458
John Zulauf69133422020-05-20 14:55:53 -06001459HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001460 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001461 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001462 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001463 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001464}
1465
John Zulauf3d84f1b2020-03-09 13:33:25 -06001466class BarrierHazardDetector {
1467 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001468 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001469 SyncStageAccessFlags src_access_scope)
1470 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1471
John Zulauf5f13a792020-03-10 07:31:21 -06001472 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001473 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001474 }
John Zulauf14940722021-04-12 15:19:02 -06001475 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001476 // 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 -07001477 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001478 }
1479
1480 private:
1481 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001482 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001483 SyncStageAccessFlags src_access_scope_;
1484};
1485
John Zulauf4a6105a2020-11-17 15:11:05 -07001486class EventBarrierHazardDetector {
1487 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001488 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001489 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001490 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001491 : usage_index_(usage_index),
1492 src_exec_scope_(src_exec_scope),
1493 src_access_scope_(src_access_scope),
1494 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001495 scope_queue_id_(queue_id),
1496 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001497 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001498 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001499
John Zulaufe0757ba2022-06-10 16:51:45 -06001500 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1501 // Need to piece together coverage of pos->first range:
1502 // Copy the range as we'll be chopping it up as needed
1503 ResourceAccessRange range = pos->first;
1504 const ResourceAccessState &access = pos->second;
1505 HazardResult hazard;
1506
1507 bool in_scope = AdvanceScope(range);
1508 bool unscoped_tested = false;
1509 while (in_scope && !hazard.IsHazard()) {
1510 if (range.begin < ScopeBegin()) {
1511 if (!unscoped_tested) {
1512 unscoped_tested = true;
1513 hazard = access.DetectHazard(usage_index_);
1514 }
1515 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1516 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1517 range.begin = ScopeBegin();
1518 } else { // in_scope implied that ScopeRange and range intersect
1519 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1520 scope_tag_);
1521 if (!hazard.IsHazard()) {
1522 range.begin = ScopeEnd();
1523 in_scope = AdvanceScope(range); // contains a non_empty check
1524 }
1525 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001526 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001527 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1528 hazard = access.DetectHazard(usage_index_);
1529 }
1530 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001531 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001532
John Zulauf14940722021-04-12 15:19:02 -06001533 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001534 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1535 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1536 }
1537
1538 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001539 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1540 bool ScopeValid() const { return !ScopeInvalid(); }
1541 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1542
1543 // Hiding away the std::pair grunge...
1544 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1545 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1546 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1547 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1548
1549 bool AdvanceScope(const ResourceAccessRange &range) {
1550 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1551 if (!range.non_empty()) return false;
1552 if (ScopeInvalid()) return false;
1553
1554 if (ScopeRange().strictly_less(range)) {
1555 ScopeSeek(range);
1556 }
1557
1558 return ScopeValid() && ScopeRange().intersects(range);
1559 }
1560
John Zulauf4a6105a2020-11-17 15:11:05 -07001561 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001562 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001563 SyncStageAccessFlags src_access_scope_;
1564 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001565 QueueId scope_queue_id_;
1566 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001567 SyncEventState::ScopeMap::const_iterator scope_pos_;
1568 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001569};
1570
John Zulaufe0757ba2022-06-10 16:51:45 -06001571HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1572 VkPipelineStageFlags2KHR src_exec_scope,
1573 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1574 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001575 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1576 // first access scope map to use, and there's no easy way to plumb it in below.
1577 const auto address_type = ImageAddressType(image);
1578 const auto &event_scope = sync_event.FirstScope(address_type);
1579
1580 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001581 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001582 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001583}
1584
John Zulaufd0ec59f2021-03-13 14:25:08 -07001585HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1586 DetectOptions options) const {
1587 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1588 barrier.src_access_scope);
1589 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1590}
1591
Jeremy Gebben40a22942020-12-22 14:22:06 -07001592HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001593 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001594 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001595 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001596 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001597 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001598}
1599
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001600HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001601 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001602 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001603}
John Zulauf355e49b2020-04-24 15:11:15 -06001604
John Zulauf9cb530d2019-09-30 14:14:10 -06001605template <typename Flags, typename Map>
1606SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1607 SyncStageAccessFlags scope = 0;
1608 for (const auto &bit_scope : map) {
1609 if (flag_mask < bit_scope.first) break;
1610
1611 if (flag_mask & bit_scope.first) {
1612 scope |= bit_scope.second;
1613 }
1614 }
1615 return scope;
1616}
1617
Jeremy Gebben40a22942020-12-22 14:22:06 -07001618SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001619 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1620}
1621
Jeremy Gebben40a22942020-12-22 14:22:06 -07001622SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1623 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001624}
1625
Jeremy Gebben40a22942020-12-22 14:22:06 -07001626// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1627SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001628 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1629 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1630 // 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 -06001631 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1632}
1633
1634template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001635void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001636 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1637 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001638 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001639 auto pos = accesses->lower_bound(range);
1640 if (pos == accesses->end() || !pos->first.intersects(range)) {
1641 // The range is empty, fill it with a default value.
1642 pos = action.Infill(accesses, pos, range);
1643 } else if (range.begin < pos->first.begin) {
1644 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001645 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001646 } else if (pos->first.begin < range.begin) {
1647 // Trim the beginning if needed
1648 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1649 ++pos;
1650 }
1651
1652 const auto the_end = accesses->end();
1653 while ((pos != the_end) && pos->first.intersects(range)) {
1654 if (pos->first.end > range.end) {
1655 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1656 }
1657
1658 pos = action(accesses, pos);
1659 if (pos == the_end) break;
1660
1661 auto next = pos;
1662 ++next;
1663 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1664 // Need to infill if next is disjoint
1665 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001666 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001667 next = action.Infill(accesses, next, new_range);
1668 }
1669 pos = next;
1670 }
1671}
John Zulaufd5115702021-01-18 12:34:33 -07001672
1673// Give a comparable interface for range generators and ranges
1674template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001675void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001676 assert(range);
1677 UpdateMemoryAccessState(accesses, *range, action);
1678}
1679
John Zulauf4a6105a2020-11-17 15:11:05 -07001680template <typename Action, typename RangeGen>
1681void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1682 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001683 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 -07001684 for (; range_gen->non_empty(); ++range_gen) {
1685 UpdateMemoryAccessState(accesses, *range_gen, action);
1686 }
1687}
John Zulauf9cb530d2019-09-30 14:14:10 -06001688
John Zulaufd0ec59f2021-03-13 14:25:08 -07001689template <typename Action, typename RangeGen>
1690void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1691 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1692 for (; range_gen->non_empty(); ++range_gen) {
1693 UpdateMemoryAccessState(accesses, *range_gen, action);
1694 }
1695}
John Zulauf9cb530d2019-09-30 14:14:10 -06001696struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001697 using Iterator = ResourceAccessRangeMap::iterator;
1698 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001699 // this is only called on gaps, and never returns a gap.
1700 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001701 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001702 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001703 }
John Zulauf5f13a792020-03-10 07:31:21 -06001704
John Zulauf5c5e88d2019-12-26 11:22:02 -07001705 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001706 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001707 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001708 return pos;
1709 }
1710
John Zulauf43cc7462020-12-03 12:33:12 -07001711 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001712 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001713 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001714 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001715 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001716 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001717 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001718 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001719};
1720
John Zulauf4a6105a2020-11-17 15:11:05 -07001721// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001722struct PipelineBarrierOp {
1723 SyncBarrier barrier;
1724 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001725 ResourceAccessState::QueueScopeOps scope;
1726 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1727 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001728 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001729 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001730};
John Zulauf00119522022-05-23 19:07:42 -06001731
John Zulaufecf4ac52022-06-06 10:08:42 -06001732// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1733struct BatchBarrierOp : public PipelineBarrierOp {
1734 void operator()(ResourceAccessState *access_state) const {
1735 access_state->ApplyBarrier(scope, barrier, layout_transition);
1736 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1737 }
1738 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1739};
1740
John Zulauf4a6105a2020-11-17 15:11:05 -07001741// The barrier operation for wait events
1742struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001743 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001744 SyncBarrier barrier;
1745 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001746
1747 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001748 bool layout_transition_)
John Zulaufe0757ba2022-06-10 16:51:45 -06001749 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
John Zulaufb7578302022-05-19 13:50:18 -06001750 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001751};
John Zulauf1e331ec2020-12-04 18:29:38 -07001752
John Zulauf4a6105a2020-11-17 15:11:05 -07001753// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1754// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1755// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001756template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001757class ApplyBarrierOpsFunctor {
1758 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001759 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001760 // Only called with a gap, and pos at the lower_bound(range)
1761 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1762 if (!infill_default_) {
1763 return pos;
1764 }
1765 ResourceAccessState default_state;
1766 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1767 return inserted;
1768 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001769
John Zulauf5c628d02021-05-04 15:46:36 -06001770 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001771 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001772 for (const auto &op : barrier_ops_) {
1773 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001774 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001775
John Zulauf89311b42020-09-29 16:28:47 -06001776 if (resolve_) {
1777 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1778 // another walk
1779 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001780 }
1781 return pos;
1782 }
1783
John Zulauf89311b42020-09-29 16:28:47 -06001784 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001785 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1786 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001787 barrier_ops_.reserve(size_hint);
1788 }
John Zulauf5c628d02021-05-04 15:46:36 -06001789 void EmplaceBack(const BarrierOp &op) {
1790 barrier_ops_.emplace_back(op);
1791 infill_default_ |= op.layout_transition;
1792 }
John Zulauf89311b42020-09-29 16:28:47 -06001793
1794 private:
1795 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001796 bool infill_default_;
1797 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001798 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001799};
1800
John Zulauf4a6105a2020-11-17 15:11:05 -07001801// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1802// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1803template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001804class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1805 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1806
John Zulauf4a6105a2020-11-17 15:11:05 -07001807 public:
John Zulaufee984022022-04-13 16:39:50 -06001808 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001809};
1810
John Zulauf1e331ec2020-12-04 18:29:38 -07001811// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001812class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1813 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1814
John Zulauf1e331ec2020-12-04 18:29:38 -07001815 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001816 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001817};
1818
John Zulauf8e3c3e92021-01-06 11:19:36 -07001819void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001820 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001821 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001822 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001823}
1824
John Zulauf8e3c3e92021-01-06 11:19:36 -07001825void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001826 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001827 if (!SimpleBinding(buffer)) return;
1828 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001829 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001830}
John Zulauf355e49b2020-04-24 15:11:15 -06001831
John Zulauf8e3c3e92021-01-06 11:19:36 -07001832void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001833 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1834 if (!SimpleBinding(image)) return;
1835 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001836 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001837 const auto address_type = ImageAddressType(image);
1838 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1839 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1840}
1841void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001842 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001843 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001844 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001845 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001846 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001847 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001848 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001849 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001850 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001851}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001852
1853void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001854 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001855 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1856 if (!gen) return;
1857 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1858 const auto address_type = view_gen.GetAddressType();
1859 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1860 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001861}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001862
John Zulauf8e3c3e92021-01-06 11:19:36 -07001863void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001864 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001865 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001866 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1867 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001868 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001869}
1870
John Zulaufd0ec59f2021-03-13 14:25:08 -07001871template <typename Action, typename RangeGen>
1872void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1873 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1874 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001875}
1876
1877template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001878void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1879 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1880 if (!gen) return;
1881 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001882}
1883
John Zulaufd0ec59f2021-03-13 14:25:08 -07001884void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1885 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001886 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001887 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001888 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001889}
1890
John Zulaufd0ec59f2021-03-13 14:25:08 -07001891void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001892 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001893 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001894
1895 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1896 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001897 const auto &view_gen = attachment_views[i];
1898 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001899
1900 const auto &ci = attachment_ci[i];
1901 const bool has_depth = FormatHasDepth(ci.format);
1902 const bool has_stencil = FormatHasStencil(ci.format);
1903 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001904 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001905
1906 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001907 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1908 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001909 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001910 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001911 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1912 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001913 }
John Zulauf57261402021-08-13 11:32:06 -06001914 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001915 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001916 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1917 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001918 }
1919 }
1920 }
1921 }
1922}
1923
John Zulauf540266b2020-04-06 18:54:53 -06001924template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001925void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001926 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001927 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001928 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001929 }
1930}
1931
1932void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001933 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1934 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001935 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001936 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001937 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001938 }
1939 }
1940}
1941
John Zulauf4fa68462021-04-26 21:04:22 -06001942// Caller must ensure that lifespan of this is less than from
1943void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1944
John Zulauf355e49b2020-04-24 15:11:15 -06001945// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001946HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1947 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001948
John Zulauf355e49b2020-04-24 15:11:15 -06001949 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001950 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001951
1952 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001953 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1954 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001955 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001956 if (!hazard.hazard) {
1957 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001958 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001959 }
John Zulaufa0a98292020-09-18 09:30:10 -06001960
John Zulauf355e49b2020-04-24 15:11:15 -06001961 return hazard;
1962}
1963
John Zulaufb02c1eb2020-10-06 16:33:36 -06001964void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001965 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001966 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001967 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001968 for (const auto &transition : transitions) {
1969 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001970 const auto &view_gen = attachment_views[transition.attachment];
1971 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001972
1973 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1974 assert(trackback);
1975
1976 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001977 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001978 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001979 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001980 auto &target_map = GetAccessStateMap(address_type);
1981 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001982 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1983 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001984 }
1985
John Zulauf86356ca2020-10-19 11:46:41 -06001986 // If there were no transitions skip this global map walk
1987 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001988 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001989 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001990 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001991}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001992
sjfricke0bea06e2022-06-05 09:22:26 +09001993bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06001994 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001995 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001996 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001997 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001998 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001999 return skip;
2000 }
sjfricke0bea06e2022-06-05 09:22:26 +09002001 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002002
2003 using DescriptorClass = cvdescriptorset::DescriptorClass;
2004 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2005 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002006 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2007
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002008 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002009 const auto raster_state = pipe->RasterizationState();
2010 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002011 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002012 }
locke-lunarg61870c22020-06-09 14:51:50 -06002013 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002014 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002015 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2016 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002017 SyncStageAccessIndex sync_index =
2018 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2019
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002020 for (uint32_t index = 0; index < binding->count; index++) {
2021 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002022 switch (descriptor->GetClass()) {
2023 case DescriptorClass::ImageSampler:
2024 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002025 if (descriptor->Invalid()) {
2026 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002027 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002028
2029 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2030 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2031 const auto *img_view_state = image_descriptor->GetImageViewState();
2032 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2033
John Zulauf361fb532020-07-22 10:45:39 -06002034 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002035 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2036 // Descriptors, so we do not have to worry about depth slicing here.
2037 // See: VUID 00343
2038 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002039 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002040 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002041
2042 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2043 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2044 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002045 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002046 hazard =
2047 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2048 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002049 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002050 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2051 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002052 }
John Zulauf110413c2021-03-20 05:38:38 -06002053
John Zulauf33fc1d52020-07-17 11:01:10 -06002054 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002055 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002056 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002057 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2058 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002059 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002060 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2061 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2062 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002063 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2064 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002065 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002066 }
2067 break;
2068 }
2069 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002070 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2071 if (texel_descriptor->Invalid()) {
2072 continue;
2073 }
2074 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2075 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002076 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002077 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002078 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002079 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002080 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002081 "%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 +09002082 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002083 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2084 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2085 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002086 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002087 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002088 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002089 }
2090 break;
2091 }
2092 case DescriptorClass::GeneralBuffer: {
2093 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002094 if (buffer_descriptor->Invalid()) {
2095 continue;
2096 }
2097 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002098 const ResourceAccessRange range =
2099 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002100 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002101 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002102 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002103 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002104 "%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 +09002105 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002106 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2107 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2108 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002109 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002110 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002111 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002112 }
2113 break;
2114 }
2115 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2116 default:
2117 break;
2118 }
2119 }
2120 }
2121 }
2122 return skip;
2123}
2124
2125void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002126 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002127 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002128 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002129 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002130 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002131 return;
2132 }
2133
2134 using DescriptorClass = cvdescriptorset::DescriptorClass;
2135 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2136 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002137 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2138
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002139 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002140 const auto raster_state = pipe->RasterizationState();
2141 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002142 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002143 }
locke-lunarg61870c22020-06-09 14:51:50 -06002144 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002145 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002146 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2147 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002148 SyncStageAccessIndex sync_index =
2149 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2150
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002151 for (uint32_t i = 0; i < binding->count; i++) {
2152 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002153 switch (descriptor->GetClass()) {
2154 case DescriptorClass::ImageSampler:
2155 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002156 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2157 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2158 if (image_descriptor->Invalid()) {
2159 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002160 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002161 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002162 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2163 // Descriptors, so we do not have to worry about depth slicing here.
2164 // See: VUID 00343
2165 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002166 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002167 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002168 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2169 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2170 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2171 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002172 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002173 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2174 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002175 }
locke-lunarg61870c22020-06-09 14:51:50 -06002176 break;
2177 }
2178 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002179 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2180 if (texel_descriptor->Invalid()) {
2181 continue;
2182 }
2183 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2184 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002185 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002186 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002187 break;
2188 }
2189 case DescriptorClass::GeneralBuffer: {
2190 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002191 if (buffer_descriptor->Invalid()) {
2192 continue;
2193 }
2194 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002195 const ResourceAccessRange range =
2196 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002197 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002198 break;
2199 }
2200 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2201 default:
2202 break;
2203 }
2204 }
2205 }
2206 }
2207}
2208
sjfricke0bea06e2022-06-05 09:22:26 +09002209bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002210 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002211 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002212 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002213 return skip;
2214 }
2215
2216 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2217 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002218 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002219
2220 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002221 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002222 if (binding_description.binding < binding_buffers_size) {
2223 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002224 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002225
locke-lunarg1ae57d62020-11-18 10:49:19 -07002226 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002227 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2228 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002229 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002230 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002231 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002232 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002233 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002234 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2235 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002236 }
2237 }
2238 }
2239 return skip;
2240}
2241
John Zulauf14940722021-04-12 15:19:02 -06002242void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002243 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002244 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002245 return;
2246 }
2247 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2248 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002249 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002250
2251 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002252 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002253 if (binding_description.binding < binding_buffers_size) {
2254 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002255 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002256
locke-lunarg1ae57d62020-11-18 10:49:19 -07002257 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002258 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2259 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002260 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2261 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002262 }
2263 }
2264}
2265
sjfricke0bea06e2022-06-05 09:22:26 +09002266bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002267 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002268 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002269 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002270 }
locke-lunarg61870c22020-06-09 14:51:50 -06002271
locke-lunarg1ae57d62020-11-18 10:49:19 -07002272 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002273 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002274 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2275 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002276 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002277 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002278 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002279 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 +09002280 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2281 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002282 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002283 }
2284
2285 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2286 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002287 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002288 return skip;
2289}
2290
John Zulauf14940722021-04-12 15:19:02 -06002291void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002292 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 -06002293
locke-lunarg1ae57d62020-11-18 10:49:19 -07002294 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002295 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002296 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2297 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002298 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002299
2300 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2301 // We will detect more accurate range in the future.
2302 RecordDrawVertex(UINT32_MAX, 0, tag);
2303}
2304
sjfricke0bea06e2022-06-05 09:22:26 +09002305bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002306 bool skip = false;
2307 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002308 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002309 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002310}
2311
John Zulauf14940722021-04-12 15:19:02 -06002312void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002313 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002314 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002315 }
locke-lunarg61870c22020-06-09 14:51:50 -06002316}
2317
John Zulauf00119522022-05-23 19:07:42 -06002318QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2319
sjfricke0bea06e2022-06-05 09:22:26 +09002320ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002321 const VkRect2D &render_area,
2322 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002323 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002324 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2325 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002326 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002327 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002328 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002329 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002330 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002331}
2332
sjfricke0bea06e2022-06-05 09:22:26 +09002333ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002334 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002335 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002336
sjfricke0bea06e2022-06-05 09:22:26 +09002337 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2338 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2339 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002340
2341 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002342 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002343 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002344}
2345
sjfricke0bea06e2022-06-05 09:22:26 +09002346ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002347 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002348 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002349
sjfricke0bea06e2022-06-05 09:22:26 +09002350 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2351 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002352
2353 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002354 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002355 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002356 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002357}
2358
John Zulauf4a6105a2020-11-17 15:11:05 -07002359void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2360 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002361 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002362 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002363 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002364 }
2365}
2366
John Zulaufae842002021-04-15 18:20:55 -06002367// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002368bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002369 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002370 if (!exec_context.ValidForSyncOps()) return false;
2371
2372 const QueueId queue_id = exec_context.GetQueueId();
2373 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002374 bool skip = false;
2375 ResourceUsageRange tag_range = {0, 0};
2376 const AccessContext *recorded_context = GetCurrentAccessContext();
2377 assert(recorded_context);
2378 HazardResult hazard;
John Zulaufdab327f2022-07-08 12:02:05 -06002379 ReplayGuard replay_guard(exec_context, *this);
2380
John Zulaufbb890452021-12-14 11:30:18 -07002381 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002382 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002383 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002384 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002385 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002386 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002387 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2388 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002389 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002390 };
2391 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002392 // we update the range to any include layout transition first use writes,
2393 // as they are stored along with the source scope (as effective barrier) when recorded
2394 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002395 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002396
John Zulauf0223f142022-07-06 09:05:39 -06002397 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2398 // we need to fetch the current access context each time
John Zulaufdab327f2022-07-08 12:02:05 -06002399 hazard = exec_context.DetectFirstUseHazard(tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002400 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002401 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002402 }
2403 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002404 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002405 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002406 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002407 }
2408
2409 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002410 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002411 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002412 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002413 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002414 }
2415
2416 return skip;
2417}
2418
sjfricke0bea06e2022-06-05 09:22:26 +09002419void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002420 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2421 assert(recorded_context);
2422
2423 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2424 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002425 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002426 // we update the range to any include layout transition first use writes,
2427 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002428 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002429 }
2430
2431 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2432 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002433 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002434}
2435
John Zulauf1d5f9c12022-05-13 14:51:08 -06002436void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002437 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002438 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002439}
2440
John Zulaufdab327f2022-07-08 12:02:05 -06002441HazardResult CommandBufferAccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
2442 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, *GetCurrentAccessContext());
2443}
2444
John Zulauf3c788ef2022-02-22 12:12:30 -07002445ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002446 // The execution references ensure lifespan for the referenced child CB's...
2447 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002448 InsertRecordedAccessLogEntries(recorded_context);
2449 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002450 return tag_range;
2451}
2452
John Zulauf3c788ef2022-02-22 12:12:30 -07002453void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2454 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2455 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2456}
2457
John Zulauf41a9c7c2021-12-07 15:59:53 -07002458ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2459 ResourceUsageTag next = access_log_.size();
2460 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2461 return next;
2462}
2463
2464ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2465 command_number_++;
2466 subcommand_number_ = 0;
2467 ResourceUsageTag next = access_log_.size();
2468 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2469 return next;
2470}
2471
2472ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2473 if (index == 0) {
2474 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2475 }
2476 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2477}
2478
John Zulaufbb890452021-12-14 11:30:18 -07002479void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2480 auto tag = sync_op->Record(this);
2481 // As renderpass operations can have side effects on the command buffer access context,
2482 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002483 sync_ops_.emplace_back(tag, std::move(sync_op));
2484}
2485
John Zulaufae842002021-04-15 18:20:55 -06002486class HazardDetectFirstUse {
2487 public:
John Zulauf0223f142022-07-06 09:05:39 -06002488 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2489 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002490 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002491 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002492 }
2493 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2494 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2495 }
2496
2497 private:
2498 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002499 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002500 const ResourceUsageRange &tag_range_;
2501};
2502
2503// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2504// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002505HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002506 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002507 HazardResult hazard;
2508 for (const auto address_type : kAddressTypes) {
2509 const auto &recorded_access_map = GetAccessStateMap(address_type);
2510 for (const auto &recorded_access : recorded_access_map) {
2511 // Cull any entries not in the current tag range
2512 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002513 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002514 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2515 if (hazard.hazard) break;
2516 }
2517 }
2518
2519 return hazard;
2520}
2521
John Zulaufbb890452021-12-14 11:30:18 -07002522bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002523 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002524 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002525 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002526 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002527 if (!pipe) {
2528 return skip;
2529 }
2530
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002531 const auto raster_state = pipe->RasterizationState();
2532 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002533 return skip;
2534 }
sjfricke0bea06e2022-06-05 09:22:26 +09002535 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002536 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002537 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002538
John Zulauf1a224292020-06-30 14:52:13 -06002539 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002540 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002541 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2542 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002543 if (location >= subpass.colorAttachmentCount ||
2544 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002545 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002546 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002547 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2548 if (!view_gen.IsValid()) continue;
2549 HazardResult hazard =
2550 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2551 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002552 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002553 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002554 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002555 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002556 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002557 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002558 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2559 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002560 }
2561 }
2562 }
locke-lunarg37047832020-06-12 13:44:45 -06002563
2564 // PHASE1 TODO: Add layout based read/vs. write selection.
2565 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002566 const auto ds_state = pipe->DepthStencilState();
2567 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002568
2569 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2570 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2571 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002572 bool depth_write = false, stencil_write = false;
2573
2574 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002575 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002576 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2577 depth_write = true;
2578 }
2579 // PHASE1 TODO: It needs to check if stencil is writable.
2580 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2581 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2582 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002583 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002584 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2585 stencil_write = true;
2586 }
2587
2588 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2589 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002590 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2591 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2592 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002593 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002594 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002595 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002596 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002597 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002598 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002599 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002600 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002601 }
2602 }
2603 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002604 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2605 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2606 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002607 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002608 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002609 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002610 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002611 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002612 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002613 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002614 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002615 }
locke-lunarg61870c22020-06-09 14:51:50 -06002616 }
2617 }
2618 return skip;
2619}
2620
sjfricke0bea06e2022-06-05 09:22:26 +09002621void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2622 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002623 if (!pipe) {
2624 return;
2625 }
2626
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002627 const auto *raster_state = pipe->RasterizationState();
2628 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002629 return;
2630 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002631 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002632 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002633
John Zulauf1a224292020-06-30 14:52:13 -06002634 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002635 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002636 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2637 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002638 if (location >= subpass.colorAttachmentCount ||
2639 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002640 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002641 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002642 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2643 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2644 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2645 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002646 }
2647 }
locke-lunarg37047832020-06-12 13:44:45 -06002648
2649 // PHASE1 TODO: Add layout based read/vs. write selection.
2650 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002651 const auto *ds_state = pipe->DepthStencilState();
2652 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002653 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2654 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2655 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002656 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002657 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2658 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002659
2660 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002661 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2662 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002663 depth_write = true;
2664 }
2665 // PHASE1 TODO: It needs to check if stencil is writable.
2666 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2667 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2668 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002669 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002670 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2671 stencil_write = true;
2672 }
2673
John Zulaufd0ec59f2021-03-13 14:25:08 -07002674 if (depth_write || stencil_write) {
2675 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2676 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2677 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2678 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002679 }
locke-lunarg61870c22020-06-09 14:51:50 -06002680 }
2681}
2682
sjfricke0bea06e2022-06-05 09:22:26 +09002683bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002684 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002685 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002686 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002687 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002688 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002689 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002690
John Zulauf355e49b2020-04-24 15:11:15 -06002691 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002692 if (next_subpass >= subpass_contexts_.size()) {
2693 return skip;
2694 }
John Zulauf1507ee42020-05-18 11:33:09 -06002695 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002696 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002697 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002698 if (!skip) {
2699 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2700 // on a copy of the (empty) next context.
2701 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2702 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002703 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002704 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002705 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002706 }
John Zulauf7635de32020-05-29 17:14:15 -06002707 return skip;
2708}
sjfricke0bea06e2022-06-05 09:22:26 +09002709bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002710 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002711 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002712 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002713 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002714 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2715 cmd_type);
2716 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002717 return skip;
2718}
2719
John Zulauf64ffe552021-02-06 10:25:07 -07002720AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002721 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002722}
2723
John Zulaufbb890452021-12-14 11:30:18 -07002724bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002725 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002726 bool skip = false;
2727
John Zulauf7635de32020-05-29 17:14:15 -06002728 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2729 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2730 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2731 // to apply and only copy then, if this proves a hot spot.
2732 std::unique_ptr<AccessContext> proxy_for_current;
2733
John Zulauf355e49b2020-04-24 15:11:15 -06002734 // Validate the "finalLayout" transitions to external
2735 // Get them from where there we're hidding in the extra entry.
2736 const auto &final_transitions = rp_state_->subpass_transitions.back();
2737 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002738 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002739 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002740 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2741 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002742
2743 if (transition.prev_pass == current_subpass_) {
2744 if (!proxy_for_current) {
2745 // 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 -07002746 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002747 }
2748 context = proxy_for_current.get();
2749 }
2750
John Zulaufa0a98292020-09-18 09:30:10 -06002751 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2752 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002753 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002754 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002755 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002756 if (hazard.tag == kInvalidTag) {
2757 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002758 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002759 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2760 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2761 " final image layout transition (old_layout: %s, new_layout: %s).",
2762 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2763 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2764 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002765 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002766 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2767 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2768 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2769 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2770 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002771 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002772 }
John Zulauf355e49b2020-04-24 15:11:15 -06002773 }
2774 }
2775 return skip;
2776}
2777
John Zulauf14940722021-04-12 15:19:02 -06002778void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002779 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002780 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002781}
2782
John Zulauf14940722021-04-12 15:19:02 -06002783void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002784 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2785 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002786
2787 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2788 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002789 const AttachmentViewGen &view_gen = attachment_views_[i];
2790 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002791
2792 const auto &ci = attachment_ci[i];
2793 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002794 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002795 const bool is_color = !(has_depth || has_stencil);
2796
2797 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002798 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2799 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2800 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2801 SyncOrdering::kColorAttachment, tag);
2802 }
John Zulauf1507ee42020-05-18 11:33:09 -06002803 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002804 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002805 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2806 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2807 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2808 SyncOrdering::kDepthStencilAttachment, tag);
2809 }
John Zulauf1507ee42020-05-18 11:33:09 -06002810 }
2811 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002812 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2813 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2814 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2815 SyncOrdering::kDepthStencilAttachment, tag);
2816 }
John Zulauf1507ee42020-05-18 11:33:09 -06002817 }
2818 }
2819 }
2820 }
2821}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002822AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2823 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2824 AttachmentViewGenVector view_gens;
2825 VkExtent3D extent = CastTo3D(render_area.extent);
2826 VkOffset3D offset = CastTo3D(render_area.offset);
2827 view_gens.reserve(attachment_views.size());
2828 for (const auto *view : attachment_views) {
2829 view_gens.emplace_back(view, offset, extent);
2830 }
2831 return view_gens;
2832}
John Zulauf64ffe552021-02-06 10:25:07 -07002833RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2834 VkQueueFlags queue_flags,
2835 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2836 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002837 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulaufdab327f2022-07-08 12:02:05 -06002838 // Add this for all subpasses here so that they exist during next subpass validation
2839 InitSubpassContexts(queue_flags, rp_state, external_context, subpass_contexts_);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002840 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002841}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002842void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002843 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002844 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2845 RecordLayoutTransitions(barrier_tag);
2846 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002847}
John Zulauf1507ee42020-05-18 11:33:09 -06002848
John Zulauf41a9c7c2021-12-07 15:59:53 -07002849void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2850 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002851 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002852 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2853 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002854
ziga-lunarg31a3e772022-03-22 11:48:46 +01002855 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2856 return;
2857 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002858 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2859 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002860 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002861 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2862 RecordLayoutTransitions(barrier_tag);
2863 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002864}
2865
John Zulauf41a9c7c2021-12-07 15:59:53 -07002866void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2867 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002868 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002869 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2870 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002871
John Zulauf355e49b2020-04-24 15:11:15 -06002872 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002873 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002874
2875 // Add the "finalLayout" transitions to external
2876 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002877 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2878 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2879 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002880 const auto &final_transitions = rp_state_->subpass_transitions.back();
2881 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002882 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002883 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002884 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002885 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002886 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002887 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002888 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002889 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002890 }
2891}
2892
John Zulauf06f6f1e2022-04-19 15:28:11 -06002893SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2894 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002895 SyncExecScope result;
2896 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002897 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002898 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002899 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002900 return result;
2901}
2902
Jeremy Gebben40a22942020-12-22 14:22:06 -07002903SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002904 SyncExecScope result;
2905 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002906 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2907 result.exec_scope = sync_utils::WithLaterPipelineStages(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
John Zulaufecf4ac52022-06-06 10:08:42 -06002912SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2913 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2914
2915SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2916 : 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 -07002917
2918template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002919SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2920 : src_exec_scope(src),
2921 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2922 dst_exec_scope(dst),
2923 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002924
2925SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002926 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2927 if (barrier) {
2928 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002929 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002930 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002931
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002932 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002933 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002934 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2935
2936 } else {
2937 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.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, subpass.srcAccessMask);
2940
2941 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.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, subpass.dstAccessMask);
2944 }
2945}
2946
2947template <typename Barrier>
2948SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2949 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2950 src_exec_scope = src.exec_scope;
2951 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2952
2953 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002954 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002955 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002956}
2957
John Zulaufb02c1eb2020-10-06 16:33:36 -06002958// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2959void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002960 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002961 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002962 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002963 }
2964}
2965
John Zulauf89311b42020-09-29 16:28:47 -06002966// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2967// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2968// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002969void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002970 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002971 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002972 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002973 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002974 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002975 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002976 }
John Zulaufbb890452021-12-14 11:30:18 -07002977 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002978}
John Zulauf9cb530d2019-09-30 14:14:10 -06002979HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2980 HazardResult hazard;
2981 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002982 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002983 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002984 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002985 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002986 }
2987 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002988 // Write operation:
2989 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2990 // If reads exists -- test only against them because either:
2991 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2992 // * 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
2993 // the current write happens after the reads, so just test the write against the reades
2994 // Otherwise test against last_write
2995 //
2996 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002997 if (last_reads.size()) {
2998 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002999 if (IsReadHazard(usage_stage, read_access)) {
3000 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3001 break;
3002 }
3003 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003004 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003005 // Write-After-Write check -- if we have a previous write to test against
3006 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003007 }
3008 }
3009 return hazard;
3010}
3011
John Zulaufec943ec2022-06-29 07:52:56 -06003012HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3013 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003014 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003015 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003016}
3017
John Zulaufec943ec2022-06-29 07:52:56 -06003018HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3019 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003020 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3021 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003022 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003023 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003024 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003025 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003026 if (IsRead(usage_bit)) {
3027 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3028 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3029 if (is_raw_hazard) {
3030 // NOTE: we know last_write is non-zero
3031 // See if the ordering rules save us from the simple RAW check above
3032 // First check to see if the current usage is covered by the ordering rules
3033 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3034 const bool usage_is_ordered =
3035 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3036 if (usage_is_ordered) {
3037 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003038 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003039 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003040 }
3041 }
John Zulauf4285ee92020-09-23 10:20:52 -06003042 if (is_raw_hazard) {
3043 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3044 }
John Zulauf5c628d02021-05-04 15:46:36 -06003045 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3046 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003047 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003048 } else {
3049 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003050 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003051 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003052 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003053 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003054 if (usage_write_is_ordered) {
3055 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003056 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003057 }
3058 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3059 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003060 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003061 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3062 if (IsReadHazard(usage_stage, read_access)) {
3063 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3064 break;
3065 }
John Zulaufd14743a2020-07-03 09:42:39 -06003066 }
3067 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003068 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3069 bool ilt_ilt_hazard = false;
3070 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3071 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3072 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3073 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3074 }
3075 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003076 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003077 }
John Zulauf69133422020-05-20 14:55:53 -06003078 }
3079 }
3080 return hazard;
3081}
3082
John Zulaufec943ec2022-06-29 07:52:56 -06003083HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3084 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003085 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003086 using Size = FirstAccesses::size_type;
3087 const auto &recorded_accesses = recorded_use.first_accesses_;
3088 Size count = recorded_accesses.size();
3089 if (count) {
3090 const auto &last_access = recorded_accesses.back();
3091 bool do_write_last = IsWrite(last_access.usage_index);
3092 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003093
John Zulauf4fa68462021-04-26 21:04:22 -06003094 for (Size i = 0; i < count; ++count) {
3095 const auto &first = recorded_accesses[i];
3096 // Skip and quit logic
3097 if (first.tag < tag_range.begin) continue;
3098 if (first.tag >= tag_range.end) {
3099 do_write_last = false; // ignore last since we know it can't be in tag_range
3100 break;
3101 }
3102
John Zulaufec943ec2022-06-29 07:52:56 -06003103 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003104 if (hazard.hazard) {
3105 hazard.AddRecordedAccess(first);
3106 break;
3107 }
3108 }
3109
3110 if (do_write_last && tag_range.includes(last_access.tag)) {
3111 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3112 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3113 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3114 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3115 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3116 // the barrier that applies them
3117 barrier |= recorded_use.first_write_layout_ordering_;
3118 }
3119 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3120 // the active context
3121 if (recorded_use.first_read_stages_) {
3122 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3123 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3124 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3125 // active context.
3126 barrier.exec_scope |= recorded_use.first_read_stages_;
3127 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3128 barrier.access_scope |= FlagBit(last_access.usage_index);
3129 }
John Zulaufec943ec2022-06-29 07:52:56 -06003130 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003131 if (hazard.hazard) {
3132 hazard.AddRecordedAccess(last_access);
3133 }
3134 }
John Zulaufae842002021-04-15 18:20:55 -06003135 }
3136 return hazard;
3137}
3138
John Zulauf2f952d22020-02-10 11:34:51 -07003139// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003140HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003141 HazardResult hazard;
3142 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003143 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3144 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3145 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003146 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003147 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003148 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003149 }
3150 } else {
John Zulauf14940722021-04-12 15:19:02 -06003151 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003152 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003153 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003154 // 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 -07003155 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003156 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003157 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003158 break;
3159 }
3160 }
John Zulauf2f952d22020-02-10 11:34:51 -07003161 }
3162 }
3163 return hazard;
3164}
3165
John Zulaufae842002021-04-15 18:20:55 -06003166HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3167 ResourceUsageTag start_tag) const {
3168 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003169 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003170 // Skip and quit logic
3171 if (first.tag < tag_range.begin) continue;
3172 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003173
3174 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003175 if (hazard.hazard) {
3176 hazard.AddRecordedAccess(first);
3177 break;
3178 }
John Zulaufae842002021-04-15 18:20:55 -06003179 }
3180 return hazard;
3181}
3182
John Zulaufec943ec2022-06-29 07:52:56 -06003183HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3184 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003185 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003186 // Only supporting image layout transitions for now
3187 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3188 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003189 // only test for WAW if there no intervening read operations.
3190 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003191 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003192 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003193 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003194 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003195 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003196 break;
3197 }
3198 }
John Zulaufec943ec2022-06-29 07:52:56 -06003199 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003200 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3201 }
3202
3203 return hazard;
3204}
3205
John Zulaufe0757ba2022-06-10 16:51:45 -06003206HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3207 VkPipelineStageFlags2KHR src_exec_scope,
3208 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3209 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003210 // Only supporting image layout transitions for now
3211 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3212 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003213
John Zulaufe0757ba2022-06-10 16:51:45 -06003214 if ((write_tag >= event_tag) && last_write.any()) {
3215 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3216 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3217 } else {
3218 // only test for WAW if there no intervening read operations.
3219 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3220 if (last_reads.size()) {
3221 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3222 // first scope, or they are a hazard.
3223 const ReadStates &scope_reads = scope_state.last_reads;
3224 const ReadStates::size_type scope_read_count = scope_reads.size();
3225 // Since the hasn't been a write:
3226 // * The current read state is a superset of the scoped one
3227 // * The stage order is the same.
3228 assert(last_reads.size() >= scope_read_count);
3229 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3230 const ReadState &scope_read = scope_reads[read_idx];
3231 const ReadState &current_read = last_reads[read_idx];
3232 assert(scope_read.stage == current_read.stage);
3233 if (current_read.tag > event_tag) {
3234 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3235 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3236 } else {
3237 // The read is in the events first synchronization scope, so we use a barrier hazard check
3238 // If the read stage is not in the src sync scope
3239 // *AND* not execution chained with an existing sync barrier (that's the or)
3240 // then the barrier access is unsafe (R/W after R)
3241 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3242 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3243 break;
3244 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003245 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003246 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003247 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3248 const ReadState &current_read = last_reads[scope_read_count];
3249 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3250 }
3251 } else if (last_write.any()) {
3252 // 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 -07003253 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3254 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003255 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3256 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003257 }
John Zulauf361fb532020-07-22 10:45:39 -06003258 }
John Zulaufd14743a2020-07-03 09:42:39 -06003259 }
John Zulauf361fb532020-07-22 10:45:39 -06003260
John Zulauf0cb5be22020-01-23 12:18:22 -07003261 return hazard;
3262}
3263
John Zulauf5f13a792020-03-10 07:31:21 -06003264// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3265// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3266// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3267void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003268 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003269 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3270 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003271 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003272 } else if (other.write_tag == write_tag) {
3273 // 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 -06003274 // dependency chaining logic or any stage expansion)
3275 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003276 pending_write_barriers |= other.pending_write_barriers;
3277 pending_layout_transition |= other.pending_layout_transition;
3278 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003279 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003280
John Zulaufd14743a2020-07-03 09:42:39 -06003281 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003282 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003283 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003284 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003285 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003286 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003287 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003288 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3289 // but we should wait on profiling data for that.
3290 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003291 auto &my_read = last_reads[my_read_index];
3292 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003293 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003294 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003295 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003296 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003297 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003298 my_read.pending_dep_chain = other_read.pending_dep_chain;
3299 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3300 // May require tracking more than one access per stage.
3301 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003302 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003303 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003304 // Since I'm overwriting the fragement stage read, also update the input attachment info
3305 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003306 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003307 }
John Zulauf14940722021-04-12 15:19:02 -06003308 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003309 // The read tags match so merge the barriers
3310 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003311 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003312 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003313 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003314
John Zulauf5f13a792020-03-10 07:31:21 -06003315 break;
3316 }
3317 }
3318 } else {
3319 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003320 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003321 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003322 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003323 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003324 }
John Zulauf5f13a792020-03-10 07:31:21 -06003325 }
3326 }
John Zulauf361fb532020-07-22 10:45:39 -06003327 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003328 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3329 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003330
3331 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3332 // of the copy and other into this using the update first logic.
3333 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3334 // of the other first_accesses... )
3335 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3336 FirstAccesses firsts(std::move(first_accesses_));
3337 first_accesses_.clear();
3338 first_read_stages_ = 0U;
3339 auto a = firsts.begin();
3340 auto a_end = firsts.end();
3341 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003342 // TODO: Determine whether some tag offset will be needed for PHASE II
3343 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003344 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3345 ++a;
3346 }
3347 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3348 }
3349 for (; a != a_end; ++a) {
3350 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3351 }
3352 }
John Zulauf5f13a792020-03-10 07:31:21 -06003353}
3354
John Zulauf14940722021-04-12 15:19:02 -06003355void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003356 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3357 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003358 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003359 // Mulitple outstanding reads may be of interest and do dependency chains independently
3360 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3361 const auto usage_stage = PipelineStageBit(usage_index);
3362 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003363 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003364 for (auto &read_access : last_reads) {
3365 if (read_access.stage == usage_stage) {
3366 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003367 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003368 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003369 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003370 } else {
3371 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3372 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3373 // that sync_stages is a subset of barriers may not apply.
3374 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003375 }
3376 }
3377 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003378 for (auto &read_access : last_reads) {
3379 if (read_access.barriers & usage_stage) {
3380 read_access.sync_stages |= usage_stage;
3381 }
3382 }
John Zulaufab7756b2020-12-29 16:10:16 -07003383 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003384 last_read_stages |= usage_stage;
3385 }
John Zulauf4285ee92020-09-23 10:20:52 -06003386
3387 // 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 -07003388 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003389 // TODO Revisit re: multiple reads for a given stage
3390 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003391 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003392 } else {
3393 // Assume write
3394 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003395 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003396 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003397 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003398}
John Zulauf5f13a792020-03-10 07:31:21 -06003399
John Zulauf89311b42020-09-29 16:28:47 -06003400// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3401// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3402// We can overwrite them as *this* write is now after them.
3403//
3404// 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 -06003405void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003406 ClearRead();
3407 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003408 write_tag = tag;
3409 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003410}
3411
John Zulauf1d5f9c12022-05-13 14:51:08 -06003412void ResourceAccessState::ClearWrite() {
3413 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3414 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3415 write_barriers.reset();
3416 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3417 last_write.reset();
3418
3419 write_tag = 0;
3420 write_queue = QueueSyncState::kQueueIdInvalid;
3421}
3422
3423void ResourceAccessState::ClearRead() {
3424 last_reads.clear();
3425 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3426}
3427
John Zulauf89311b42020-09-29 16:28:47 -06003428// Apply the memory barrier without updating the existing barriers. The execution barrier
3429// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3430// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3431// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003432template <typename ScopeOps>
3433void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003434 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3435 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003436 // 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 -06003437 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003438 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3439 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003440 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003441 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003442 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003443 if (layout_transition) {
3444 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3445 }
John Zulaufa0a98292020-09-18 09:30:10 -06003446 }
John Zulauf89311b42020-09-29 16:28:47 -06003447 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3448 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003449
John Zulauf89311b42020-09-29 16:28:47 -06003450 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003451 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3452 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003453 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3454
John Zulaufab7756b2020-12-29 16:10:16 -07003455 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003456 // 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 -06003457 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003458 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3459 stages_in_scope |= read_access.stage;
3460 }
3461 }
3462
3463 for (auto &read_access : last_reads) {
3464 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3465 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3466 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3467 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003468 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003469 }
3470 }
John Zulaufa0a98292020-09-18 09:30:10 -06003471 }
John Zulaufa0a98292020-09-18 09:30:10 -06003472}
3473
John Zulauf14940722021-04-12 15:19:02 -06003474void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003475 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003476 // 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 -06003477 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003478 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003479 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3480 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003481 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003482 }
John Zulauf89311b42020-09-29 16:28:47 -06003483
3484 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003485 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003486 for (auto &read_access : last_reads) {
3487 read_access.barriers |= read_access.pending_dep_chain;
3488 read_execution_barriers |= read_access.barriers;
3489 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003490 }
3491
3492 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3493 write_dependency_chain |= pending_write_dep_chain;
3494 write_barriers |= pending_write_barriers;
3495 pending_write_dep_chain = 0;
3496 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003497}
3498
John Zulaufecf4ac52022-06-06 10:08:42 -06003499// Assumes signal queue != wait queue
3500void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3501 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3502 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3503 assert(signal.queue != wait.queue);
3504 for (auto &read_access : last_reads) {
3505 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3506 // Deflects WAR on wait queue
3507 read_access.barriers = wait.exec_scope;
3508 } else {
3509 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3510 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3511 }
3512 }
3513 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3514 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3515 read_execution_barriers = wait.exec_scope;
3516 write_barriers = wait.valid_accesses;
3517 } else {
3518 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3519 write_barriers.reset();
3520 }
3521 write_dependency_chain = read_execution_barriers;
3522}
3523
John Zulauf1d5f9c12022-05-13 14:51:08 -06003524bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3525 return (queue == usage_queue) && (tag <= usage_tag);
3526}
3527
3528bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3529
3530bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3531
3532// Return if the resulting state is "empty"
3533template <typename Pred>
3534bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3535 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3536
3537 // Use the predicate to build a mask of the read stages we are synchronizing
3538 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003539 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003540 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003541 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3542 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003543 }
3544 }
3545
John Zulauf434c4e62022-05-19 16:03:56 -06003546 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3547 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3548 uint32_t unsync_count = 0;
3549 for (auto &read_access : last_reads) {
3550 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3551 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3552 sync_reads |= read_access.stage;
3553 } else {
3554 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003555 }
3556 }
3557
3558 if (unsync_count) {
3559 if (sync_reads) {
3560 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3561 ReadStates unsync_reads;
3562 unsync_reads.reserve(unsync_count);
3563 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3564 for (auto &read_access : last_reads) {
3565 if (0 == (read_access.stage & sync_reads)) {
3566 unsync_reads.emplace_back(read_access);
3567 unsync_read_stages |= read_access.stage;
3568 }
3569 }
3570 last_read_stages = unsync_read_stages;
3571 last_reads = std::move(unsync_reads);
3572 }
3573 } else {
3574 // Nothing remains (or it was empty to begin with)
3575 ClearRead();
3576 }
3577
3578 bool all_clear = last_reads.size() == 0;
3579 if (last_write.any()) {
3580 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3581 // Clear any predicated write, or any the write from any any access with synchronized reads.
3582 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3583 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3584 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3585 ClearWrite();
3586 } else {
3587 all_clear = false;
3588 }
3589 }
3590 return all_clear;
3591}
3592
John Zulaufae842002021-04-15 18:20:55 -06003593bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3594 if (!first_accesses_.size()) return false;
3595 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3596 return tag_range.intersects(first_access_range);
3597}
3598
John Zulauf1d5f9c12022-05-13 14:51:08 -06003599void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3600 if (last_write.any()) write_tag += offset;
3601 for (auto &read_access : last_reads) {
3602 read_access.tag += offset;
3603 }
3604 for (auto &first : first_accesses_) {
3605 first.tag += offset;
3606 }
3607}
3608
3609ResourceAccessState::ResourceAccessState()
3610 : write_barriers(~SyncStageAccessFlags(0)),
3611 write_dependency_chain(0),
3612 write_tag(),
3613 write_queue(QueueSyncState::kQueueIdInvalid),
3614 last_write(0),
3615 input_attachment_read(false),
3616 last_read_stages(0),
3617 read_execution_barriers(0),
3618 pending_write_dep_chain(0),
3619 pending_layout_transition(false),
3620 pending_write_barriers(0),
3621 pending_layout_ordering_(),
3622 first_accesses_(),
3623 first_read_stages_(0U),
3624 first_write_layout_ordering_() {}
3625
John Zulauf59e25072020-07-17 10:55:21 -06003626// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003627VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3628 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003629
John Zulaufab7756b2020-12-29 16:10:16 -07003630 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003631 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003632 barriers = read_access.barriers;
3633 break;
John Zulauf59e25072020-07-17 10:55:21 -06003634 }
3635 }
John Zulauf4285ee92020-09-23 10:20:52 -06003636
John Zulauf59e25072020-07-17 10:55:21 -06003637 return barriers;
3638}
3639
John Zulauf1d5f9c12022-05-13 14:51:08 -06003640void ResourceAccessState::SetQueueId(QueueId id) {
3641 for (auto &read_access : last_reads) {
3642 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3643 read_access.queue = id;
3644 }
3645 }
3646 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3647 write_queue = id;
3648 }
3649}
3650
John Zulauf00119522022-05-23 19:07:42 -06003651bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3652 return 0 != (write_dependency_chain & src_exec_scope);
3653}
3654
3655bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3656 return (src_access_scope & last_write).any();
3657}
3658
John Zulaufec943ec2022-06-29 07:52:56 -06003659bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3660 return (write_barriers & src_access_scope).any();
3661}
3662
John Zulaufb7578302022-05-19 13:50:18 -06003663bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3664 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003665 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3666}
3667
3668bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3669 SyncStageAccessFlags src_access_scope) const {
3670 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003671}
3672
John Zulaufe0757ba2022-06-10 16:51:45 -06003673bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3674 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003675 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3676 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3677 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003678 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003679}
3680
John Zulaufec943ec2022-06-29 07:52:56 -06003681bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3682 const SyncStageAccessFlags &src_access_scope) const {
3683 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3684}
3685
John Zulaufcb7e1672022-05-04 13:46:08 -06003686bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003687 assert(IsRead(usage));
3688 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3689 // * the previous reads are not hazards, and thus last_write must be visible and available to
3690 // any reads that happen after.
3691 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3692 // 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 -07003693 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003694}
3695
John Zulaufec943ec2022-06-29 07:52:56 -06003696VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3697 // At apply queue submission order limits on the effect of ordering
3698 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3699 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3700 for (const auto &read_access : last_reads) {
3701 if (read_access.queue != queue_id) {
3702 non_qso_stages |= read_access.stage;
3703 }
3704 }
3705 }
John Zulauf4285ee92020-09-23 10:20:52 -06003706 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003707 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3708 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003709 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003710 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003711 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003712 // 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 -07003713 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003714 }
3715
3716 return ordered_stages;
3717}
3718
John Zulauf14940722021-04-12 15:19:02 -06003719void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003720 // Only record until we record a write.
3721 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003722 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003723 if (0 == (usage_stage & first_read_stages_)) {
3724 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003725 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003726 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003727 if (0 == (read_execution_barriers & usage_stage)) {
3728 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3729 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3730 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003731 }
3732 }
3733}
3734
John Zulauf4fa68462021-04-26 21:04:22 -06003735void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3736 // Only call this after recording an image layout transition
3737 assert(first_accesses_.size());
3738 if (first_accesses_.back().tag == tag) {
3739 // 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 +02003740 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003741 first_write_layout_ordering_ = layout_ordering;
3742 }
3743}
3744
John Zulauf1d5f9c12022-05-13 14:51:08 -06003745ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3746 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3747 : stage(stage_),
3748 access(access_),
3749 barriers(barriers_),
3750 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3751 tag(tag_),
3752 queue(QueueSyncState::kQueueIdInvalid),
3753 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3754
John Zulaufee984022022-04-13 16:39:50 -06003755void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3756 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3757 stage = stage_;
3758 access = access_;
3759 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003760 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003761 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003762 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 -06003763}
3764
John Zulauf00119522022-05-23 19:07:42 -06003765// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3766// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3767// that have bee applied (via semaphore) to those accesses can be chained off of.
3768bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3769 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3770 return (exec_scope & effective_stages) != 0;
3771}
3772
John Zulauf697c0e12022-04-19 16:31:12 -06003773ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3774 ResourceUsageRange reserve;
3775 reserve.begin = tag_limit_.fetch_add(tag_count);
3776 reserve.end = reserve.begin + tag_count;
3777 return reserve;
3778}
3779
John Zulaufbbda4572022-04-19 16:20:45 -06003780const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3781 return GetMappedPlainFromShared(queue_sync_states_, queue);
3782}
3783
3784QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3785
3786std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3787 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3788}
3789
3790std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3791 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3792}
3793
John Zulaufe0757ba2022-06-10 16:51:45 -06003794template <typename T>
3795struct GetBatchTraits {};
3796template <>
3797struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3798 using Batch = std::shared_ptr<QueueBatchContext>;
3799 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3800};
3801
3802template <>
3803struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3804 using Batch = std::shared_ptr<QueueBatchContext>;
3805 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3806};
3807
3808template <typename BatchSet, typename Map, typename Predicate>
3809static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003810 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003811 for (auto &entry : map) {
3812 // Intentional copy
3813 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003814 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003815 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003816 return snapshot;
3817}
3818
3819template <typename Predicate>
3820QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003821 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003822}
3823
3824template <typename Predicate>
3825QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003826 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3827}
3828
3829QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3830 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3831 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3832 if (batch && !layer_data::Contains(snapshot, batch)) {
3833 snapshot.emplace(batch);
3834 }
3835 return false;
3836 };
3837 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3838 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003839}
3840
John Zulaufcb7e1672022-05-04 13:46:08 -06003841bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3842 const std::shared_ptr<QueueBatchContext> &batch,
3843 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003844 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003845 const SyncExecScope exec_scope =
3846 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3847 const VkSemaphore sem = sem_state->semaphore();
3848 auto signal_it = signaled_.find(sem);
3849 std::shared_ptr<Signal> insert_signal;
3850 if (signal_it == signaled_.end()) {
3851 if (prev_) {
3852 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3853 if (prev_sig) {
3854 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3855 insert_signal = std::make_shared<Signal>(*prev_sig);
3856 }
3857 }
3858 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3859 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003860 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003861
3862 bool success = false;
3863 if (!signal_it->second) {
3864 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3865 success = true;
3866 }
3867
3868 return success;
3869}
3870
John Zulaufecf4ac52022-06-06 10:08:42 -06003871std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3872 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003873 const auto found_it = signaled_.find(sem);
3874 if (found_it != signaled_.end()) {
3875 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3876 // a bit.
3877 unsignaled = std::move(found_it->second);
3878 if (!prev_) {
3879 // No parent, not need to keep the entry
3880 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3881 signaled_.erase(found_it);
3882 }
3883 } else if (prev_) {
3884 // We can't unsignal prev_ because it's const * by design.
3885 // We put in an empty placeholder
3886 signaled_.emplace(sem, std::shared_ptr<Signal>());
3887 unsignaled = GetPrev(sem);
3888 }
3889 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3890 // but CoreChecks should have reported it
3891
3892 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003893 return unsignaled;
3894}
3895
John Zulaufcb7e1672022-05-04 13:46:08 -06003896void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3897 // Overwrite the s tate with the last state from this
3898 if (from) {
3899 assert(sem == from->sem_state->semaphore());
3900 signaled_[sem] = std::move(from);
3901 } else {
3902 signaled_.erase(sem);
3903 }
3904}
3905
3906void SignaledSemaphores::Reset() {
3907 signaled_.clear();
3908 prev_ = nullptr;
3909}
3910
John Zulaufea943c52022-02-22 11:05:17 -07003911std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3912 // If we don't have one, make it.
3913 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3914 assert(cb_state.get());
3915 auto queue_flags = cb_state->GetQueueFlags();
3916 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3917}
3918
John Zulaufcb7e1672022-05-04 13:46:08 -06003919std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003920 return GetMappedInsert(cb_access_state, command_buffer,
3921 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3922}
3923
3924std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3925 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3926}
3927
3928const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3929 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3930}
3931
3932CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3933 return GetAccessContextShared(command_buffer).get();
3934}
3935
3936CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3937 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3938}
3939
John Zulaufd1f85d42020-04-15 12:23:15 -06003940void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003941 auto *access_context = GetAccessContextNoInsert(command_buffer);
3942 if (access_context) {
3943 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003944 }
3945}
3946
John Zulaufd1f85d42020-04-15 12:23:15 -06003947void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3948 auto access_found = cb_access_state.find(command_buffer);
3949 if (access_found != cb_access_state.end()) {
3950 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003951 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003952 cb_access_state.erase(access_found);
3953 }
3954}
3955
John Zulauf9cb530d2019-09-30 14:14:10 -06003956bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3957 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3958 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003959 const auto *cb_context = GetAccessContext(commandBuffer);
3960 assert(cb_context);
3961 if (!cb_context) return skip;
3962 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003963
John Zulauf3d84f1b2020-03-09 13:33:25 -06003964 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003965 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3966 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003967
3968 for (uint32_t region = 0; region < regionCount; region++) {
3969 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003970 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003971 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003972 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003973 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003974 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003975 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003976 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003977 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003978 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003979 }
John Zulauf16adfc92020-04-08 10:28:33 -06003980 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003981 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003982 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003983 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003984 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003985 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003986 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003987 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003988 }
3989 }
3990 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003991 }
3992 return skip;
3993}
3994
3995void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3996 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003997 auto *cb_context = GetAccessContext(commandBuffer);
3998 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003999 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004000 auto *context = cb_context->GetCurrentAccessContext();
4001
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004002 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4003 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004004
4005 for (uint32_t region = 0; region < regionCount; region++) {
4006 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004007 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004008 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004009 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004010 }
John Zulauf16adfc92020-04-08 10:28:33 -06004011 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004012 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004013 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004014 }
4015 }
4016}
4017
John Zulauf4a6105a2020-11-17 15:11:05 -07004018void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4019 // Clear out events from the command buffer contexts
4020 for (auto &cb_context : cb_access_state) {
4021 cb_context.second->RecordDestroyEvent(event);
4022 }
4023}
4024
Tony-LunarGef035472021-11-02 10:23:33 -06004025bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4026 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004027 bool skip = false;
4028 const auto *cb_context = GetAccessContext(commandBuffer);
4029 assert(cb_context);
4030 if (!cb_context) return skip;
4031 const auto *context = cb_context->GetCurrentAccessContext();
4032
4033 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004034 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4035 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004036
4037 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4038 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4039 if (src_buffer) {
4040 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004041 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004042 if (hazard.hazard) {
4043 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004044 skip |=
4045 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4046 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4047 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4048 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004049 }
4050 }
4051 if (dst_buffer && !skip) {
4052 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004053 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004054 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004055 skip |=
4056 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4057 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4058 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4059 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004060 }
4061 }
4062 if (skip) break;
4063 }
4064 return skip;
4065}
4066
Tony-LunarGef035472021-11-02 10:23:33 -06004067bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4068 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4069 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4070}
4071
4072bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4073 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4074}
4075
4076void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004077 auto *cb_context = GetAccessContext(commandBuffer);
4078 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004079 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004080 auto *context = cb_context->GetCurrentAccessContext();
4081
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004082 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4083 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004084
4085 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4086 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4087 if (src_buffer) {
4088 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004089 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004090 }
4091 if (dst_buffer) {
4092 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004093 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004094 }
4095 }
4096}
4097
Tony-LunarGef035472021-11-02 10:23:33 -06004098void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4099 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4100}
4101
4102void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4103 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4104}
4105
John Zulauf5c5e88d2019-12-26 11:22:02 -07004106bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4107 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4108 const VkImageCopy *pRegions) const {
4109 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004110 const auto *cb_access_context = GetAccessContext(commandBuffer);
4111 assert(cb_access_context);
4112 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004113
John Zulauf3d84f1b2020-03-09 13:33:25 -06004114 const auto *context = cb_access_context->GetCurrentAccessContext();
4115 assert(context);
4116 if (!context) return skip;
4117
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004118 auto src_image = Get<IMAGE_STATE>(srcImage);
4119 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004120 for (uint32_t region = 0; region < regionCount; region++) {
4121 const auto &copy_region = pRegions[region];
4122 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004123 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004124 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004125 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004126 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004127 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004128 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004129 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004130 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004131 }
4132
4133 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004134 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004135 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004136 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004137 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004138 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004139 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004140 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004141 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004142 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004143 }
4144 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004145
John Zulauf5c5e88d2019-12-26 11:22:02 -07004146 return skip;
4147}
4148
4149void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4150 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4151 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004152 auto *cb_access_context = GetAccessContext(commandBuffer);
4153 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004154 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004155 auto *context = cb_access_context->GetCurrentAccessContext();
4156 assert(context);
4157
Jeremy Gebben9f537102021-10-05 16:37:12 -06004158 auto src_image = Get<IMAGE_STATE>(srcImage);
4159 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004160
4161 for (uint32_t region = 0; region < regionCount; region++) {
4162 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004163 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004164 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004165 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004166 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004167 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004168 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004169 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004170 }
4171 }
4172}
4173
Tony-LunarGb61514a2021-11-02 12:36:51 -06004174bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4175 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004176 bool skip = false;
4177 const auto *cb_access_context = GetAccessContext(commandBuffer);
4178 assert(cb_access_context);
4179 if (!cb_access_context) return skip;
4180
4181 const auto *context = cb_access_context->GetCurrentAccessContext();
4182 assert(context);
4183 if (!context) return skip;
4184
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004185 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4186 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004187
Jeff Leger178b1e52020-10-05 12:22:23 -04004188 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4189 const auto &copy_region = pCopyImageInfo->pRegions[region];
4190 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004191 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004192 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004193 if (hazard.hazard) {
4194 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004195 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004196 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004197 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004198 }
4199 }
4200
4201 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004202 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004203 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004204 if (hazard.hazard) {
4205 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004206 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004207 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004208 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004209 }
4210 if (skip) break;
4211 }
4212 }
4213
4214 return skip;
4215}
4216
Tony-LunarGb61514a2021-11-02 12:36:51 -06004217bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4218 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4219 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4220}
4221
4222bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4223 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4224}
4225
4226void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004227 auto *cb_access_context = GetAccessContext(commandBuffer);
4228 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004229 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004230 auto *context = cb_access_context->GetCurrentAccessContext();
4231 assert(context);
4232
Jeremy Gebben9f537102021-10-05 16:37:12 -06004233 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4234 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004235
4236 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4237 const auto &copy_region = pCopyImageInfo->pRegions[region];
4238 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004239 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004240 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004241 }
4242 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004243 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004244 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004245 }
4246 }
4247}
4248
Tony-LunarGb61514a2021-11-02 12:36:51 -06004249void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4250 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4251}
4252
4253void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4254 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4255}
4256
John Zulauf9cb530d2019-09-30 14:14:10 -06004257bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4258 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4259 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4260 uint32_t bufferMemoryBarrierCount,
4261 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4262 uint32_t imageMemoryBarrierCount,
4263 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4264 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004265 const auto *cb_access_context = GetAccessContext(commandBuffer);
4266 assert(cb_access_context);
4267 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004268
John Zulauf36ef9282021-02-02 11:47:24 -07004269 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4270 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4271 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4272 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004273 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004274 return skip;
4275}
4276
4277void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4278 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4279 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4280 uint32_t bufferMemoryBarrierCount,
4281 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4282 uint32_t imageMemoryBarrierCount,
4283 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004284 auto *cb_access_context = GetAccessContext(commandBuffer);
4285 assert(cb_access_context);
4286 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004287
John Zulauf1bf30522021-09-03 15:39:06 -06004288 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4289 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4290 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4291 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004292}
4293
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004294bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4295 const VkDependencyInfoKHR *pDependencyInfo) const {
4296 bool skip = false;
4297 const auto *cb_access_context = GetAccessContext(commandBuffer);
4298 assert(cb_access_context);
4299 if (!cb_access_context) return skip;
4300
4301 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4302 skip = pipeline_barrier.Validate(*cb_access_context);
4303 return skip;
4304}
4305
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004306bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4307 const VkDependencyInfo *pDependencyInfo) const {
4308 bool skip = false;
4309 const auto *cb_access_context = GetAccessContext(commandBuffer);
4310 assert(cb_access_context);
4311 if (!cb_access_context) return skip;
4312
4313 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4314 skip = pipeline_barrier.Validate(*cb_access_context);
4315 return skip;
4316}
4317
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004318void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4319 auto *cb_access_context = GetAccessContext(commandBuffer);
4320 assert(cb_access_context);
4321 if (!cb_access_context) return;
4322
John Zulauf1bf30522021-09-03 15:39:06 -06004323 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4324 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004325}
4326
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004327void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4328 auto *cb_access_context = GetAccessContext(commandBuffer);
4329 assert(cb_access_context);
4330 if (!cb_access_context) return;
4331
4332 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4333 *pDependencyInfo);
4334}
4335
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004336void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004337 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004338 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004339
John Zulauf5f13a792020-03-10 07:31:21 -06004340 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4341 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004342 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004343 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4344 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004345
John Zulauf1d5f9c12022-05-13 14:51:08 -06004346 QueueId queue_id = QueueSyncState::kQueueIdBase;
4347 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004348 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004349 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004350 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4351 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004352}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004353
John Zulauf355e49b2020-04-24 15:11:15 -06004354bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004355 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004356 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004357 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004358 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004359 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004360 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004361 }
John Zulauf355e49b2020-04-24 15:11:15 -06004362 return skip;
4363}
4364
4365bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4366 VkSubpassContents contents) const {
4367 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004368 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004369 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004370 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004371 return skip;
4372}
4373
4374bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004375 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004376 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004377 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004378 return skip;
4379}
4380
4381bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4382 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004383 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004384 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004385 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004386 return skip;
4387}
4388
John Zulauf3d84f1b2020-03-09 13:33:25 -06004389void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4390 VkResult result) {
4391 // The state tracker sets up the command buffer state
4392 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4393
4394 // Create/initialize the structure that trackers accesses at the command buffer scope.
4395 auto cb_access_context = GetAccessContext(commandBuffer);
4396 assert(cb_access_context);
4397 cb_access_context->Reset();
4398}
4399
4400void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004401 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004402 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004403 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004404 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004405 }
4406}
4407
4408void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4409 VkSubpassContents contents) {
4410 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004411 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004412 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004413 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004414}
4415
4416void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4417 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4418 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004419 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004420}
4421
4422void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4423 const VkRenderPassBeginInfo *pRenderPassBegin,
4424 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4425 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004426 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004427}
4428
Mike Schuchardt2df08912020-12-15 16:28:09 -08004429bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004430 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004431 bool skip = false;
4432
4433 auto cb_context = GetAccessContext(commandBuffer);
4434 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004435 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004436 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004437 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004438}
4439
4440bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4441 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004442 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004443 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004444 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004445 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4446 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004447 return skip;
4448}
4449
Mike Schuchardt2df08912020-12-15 16:28:09 -08004450bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4451 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004452 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004453 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004454 return skip;
4455}
4456
4457bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4458 const VkSubpassEndInfo *pSubpassEndInfo) const {
4459 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004460 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004461 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004462}
4463
4464void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004465 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004466 auto cb_context = GetAccessContext(commandBuffer);
4467 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004468 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004469
sjfricke0bea06e2022-06-05 09:22:26 +09004470 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004471}
4472
4473void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4474 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004475 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004476 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004477 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004478}
4479
4480void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4481 const VkSubpassEndInfo *pSubpassEndInfo) {
4482 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004483 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004484}
4485
4486void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4487 const VkSubpassEndInfo *pSubpassEndInfo) {
4488 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004489 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004490}
4491
sfricke-samsung85584a72021-09-30 21:43:38 -07004492bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004493 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004494 bool skip = false;
4495
4496 auto cb_context = GetAccessContext(commandBuffer);
4497 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004498 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004499
sjfricke0bea06e2022-06-05 09:22:26 +09004500 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004501 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004502 return skip;
4503}
4504
4505bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4506 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004507 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004508 return skip;
4509}
4510
Mike Schuchardt2df08912020-12-15 16:28:09 -08004511bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004512 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004513 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004514 return skip;
4515}
4516
4517bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004518 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004519 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004520 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004521 return skip;
4522}
4523
sjfricke0bea06e2022-06-05 09:22:26 +09004524void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4525 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004526 // Resolve the all subpass contexts to the command buffer contexts
4527 auto cb_context = GetAccessContext(commandBuffer);
4528 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004529 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004530
sjfricke0bea06e2022-06-05 09:22:26 +09004531 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004532}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004533
John Zulauf33fc1d52020-07-17 11:01:10 -06004534// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4535// updates to a resource which do not conflict at the byte level.
4536// TODO: Revisit this rule to see if it needs to be tighter or looser
4537// TODO: Add programatic control over suppression heuristics
4538bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4539 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4540}
4541
John Zulauf3d84f1b2020-03-09 13:33:25 -06004542void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004543 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004544 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004545}
4546
4547void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004548 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004549 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004550}
4551
4552void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004553 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004554 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004555}
locke-lunarga19c71d2020-03-02 18:17:04 -07004556
sfricke-samsung71f04e32022-03-16 01:21:21 -05004557template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004558bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004559 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4560 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004561 bool skip = false;
4562 const auto *cb_access_context = GetAccessContext(commandBuffer);
4563 assert(cb_access_context);
4564 if (!cb_access_context) return skip;
4565
4566 const auto *context = cb_access_context->GetCurrentAccessContext();
4567 assert(context);
4568 if (!context) return skip;
4569
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004570 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4571 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004572
4573 for (uint32_t region = 0; region < regionCount; region++) {
4574 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004575 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004576 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004577 if (src_buffer) {
4578 ResourceAccessRange src_range =
4579 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004580 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004581 if (hazard.hazard) {
4582 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004583 skip |=
4584 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4585 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4586 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4587 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004588 }
4589 }
4590
Jeremy Gebben40a22942020-12-22 14:22:06 -07004591 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004592 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004593 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004594 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004595 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004596 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004597 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004598 }
4599 if (skip) break;
4600 }
4601 if (skip) break;
4602 }
4603 return skip;
4604}
4605
Jeff Leger178b1e52020-10-05 12:22:23 -04004606bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4607 VkImageLayout dstImageLayout, uint32_t regionCount,
4608 const VkBufferImageCopy *pRegions) const {
4609 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004610 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004611}
4612
4613bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4614 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4615 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4616 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004617 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4618}
4619
4620bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4621 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4622 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4623 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4624 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004625}
4626
sfricke-samsung71f04e32022-03-16 01:21:21 -05004627template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004628void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004629 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4630 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004631 auto *cb_access_context = GetAccessContext(commandBuffer);
4632 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004633
Jeff Leger178b1e52020-10-05 12:22:23 -04004634 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004635 auto *context = cb_access_context->GetCurrentAccessContext();
4636 assert(context);
4637
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004638 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4639 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004640
4641 for (uint32_t region = 0; region < regionCount; region++) {
4642 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004643 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004644 if (src_buffer) {
4645 ResourceAccessRange src_range =
4646 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004647 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004648 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004649 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004650 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004651 }
4652 }
4653}
4654
Jeff Leger178b1e52020-10-05 12:22:23 -04004655void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4656 VkImageLayout dstImageLayout, uint32_t regionCount,
4657 const VkBufferImageCopy *pRegions) {
4658 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004659 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004660}
4661
4662void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4663 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4664 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4665 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4666 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004667 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4668}
4669
4670void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4671 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4672 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4673 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4674 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4675 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004676}
4677
sfricke-samsung71f04e32022-03-16 01:21:21 -05004678template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004679bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004680 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4681 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004682 bool skip = false;
4683 const auto *cb_access_context = GetAccessContext(commandBuffer);
4684 assert(cb_access_context);
4685 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004686
locke-lunarga19c71d2020-03-02 18:17:04 -07004687 const auto *context = cb_access_context->GetCurrentAccessContext();
4688 assert(context);
4689 if (!context) return skip;
4690
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004691 auto src_image = Get<IMAGE_STATE>(srcImage);
4692 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004693 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004694 for (uint32_t region = 0; region < regionCount; region++) {
4695 const auto &copy_region = pRegions[region];
4696 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004697 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004698 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004699 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004700 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004701 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004702 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004703 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004704 }
John Zulauf477700e2021-01-06 11:41:49 -07004705 if (dst_mem) {
4706 ResourceAccessRange dst_range =
4707 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004708 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004709 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004710 skip |=
4711 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4712 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4713 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4714 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004715 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004716 }
4717 }
4718 if (skip) break;
4719 }
4720 return skip;
4721}
4722
Jeff Leger178b1e52020-10-05 12:22:23 -04004723bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4724 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4725 const VkBufferImageCopy *pRegions) const {
4726 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004727 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004728}
4729
4730bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4731 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4732 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4733 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004734 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4735}
4736
4737bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4738 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4739 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4740 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4741 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004742}
4743
sfricke-samsung71f04e32022-03-16 01:21:21 -05004744template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004745void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004746 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004747 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004748 auto *cb_access_context = GetAccessContext(commandBuffer);
4749 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004750
Jeff Leger178b1e52020-10-05 12:22:23 -04004751 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004752 auto *context = cb_access_context->GetCurrentAccessContext();
4753 assert(context);
4754
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004755 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004756 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004757 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004758 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004759
4760 for (uint32_t region = 0; region < regionCount; region++) {
4761 const auto &copy_region = pRegions[region];
4762 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004763 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004764 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004765 if (dst_buffer) {
4766 ResourceAccessRange dst_range =
4767 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004768 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004769 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004770 }
4771 }
4772}
4773
Jeff Leger178b1e52020-10-05 12:22:23 -04004774void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4775 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4776 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004777 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004778}
4779
4780void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4781 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4782 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4783 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4784 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004785 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4786}
4787
4788void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4789 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4790 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4791 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4792 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4793 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004794}
4795
4796template <typename RegionType>
4797bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4798 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004799 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004800 bool skip = false;
4801 const auto *cb_access_context = GetAccessContext(commandBuffer);
4802 assert(cb_access_context);
4803 if (!cb_access_context) return skip;
4804
4805 const auto *context = cb_access_context->GetCurrentAccessContext();
4806 assert(context);
4807 if (!context) return skip;
4808
sjfricke0bea06e2022-06-05 09:22:26 +09004809 const char *caller_name = CommandTypeString(cmd_type);
4810
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004811 auto src_image = Get<IMAGE_STATE>(srcImage);
4812 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004813
4814 for (uint32_t region = 0; region < regionCount; region++) {
4815 const auto &blit_region = pRegions[region];
4816 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004817 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4818 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4819 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4820 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4821 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4822 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004823 auto hazard =
4824 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004825 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004826 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004827 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004828 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004829 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004830 }
4831 }
4832
4833 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004834 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4835 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4836 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4837 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4838 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4839 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004840 auto hazard =
4841 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004842 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004843 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004844 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004845 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004846 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004847 }
4848 if (skip) break;
4849 }
4850 }
4851
4852 return skip;
4853}
4854
Jeff Leger178b1e52020-10-05 12:22:23 -04004855bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4856 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4857 const VkImageBlit *pRegions, VkFilter filter) const {
4858 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004859 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004860}
4861
4862bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4863 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4864 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4865 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004866 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004867}
4868
Tony-LunarG542ae912021-11-04 16:06:44 -06004869bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4870 const VkBlitImageInfo2 *pBlitImageInfo) const {
4871 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004872 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4873 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004874}
4875
Jeff Leger178b1e52020-10-05 12:22:23 -04004876template <typename RegionType>
4877void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4878 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4879 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004880 auto *cb_access_context = GetAccessContext(commandBuffer);
4881 assert(cb_access_context);
4882 auto *context = cb_access_context->GetCurrentAccessContext();
4883 assert(context);
4884
Jeremy Gebben9f537102021-10-05 16:37:12 -06004885 auto src_image = Get<IMAGE_STATE>(srcImage);
4886 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004887
4888 for (uint32_t region = 0; region < regionCount; region++) {
4889 const auto &blit_region = pRegions[region];
4890 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004891 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4892 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4893 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4894 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4895 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4896 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004897 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004898 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004899 }
4900 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004901 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4902 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4903 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4904 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4905 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4906 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004907 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004908 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004909 }
4910 }
4911}
locke-lunarg36ba2592020-04-03 09:42:04 -06004912
Jeff Leger178b1e52020-10-05 12:22:23 -04004913void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4914 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4915 const VkImageBlit *pRegions, VkFilter filter) {
4916 auto *cb_access_context = GetAccessContext(commandBuffer);
4917 assert(cb_access_context);
4918 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4919 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4920 pRegions, filter);
4921 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4922}
4923
4924void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4925 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4926 auto *cb_access_context = GetAccessContext(commandBuffer);
4927 assert(cb_access_context);
4928 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4929 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4930 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4931 pBlitImageInfo->filter, tag);
4932}
4933
Tony-LunarG542ae912021-11-04 16:06:44 -06004934void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4935 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4936 auto *cb_access_context = GetAccessContext(commandBuffer);
4937 assert(cb_access_context);
4938 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4939 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4940 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4941 pBlitImageInfo->filter, tag);
4942}
4943
John Zulauffaea0ee2021-01-14 14:01:32 -07004944bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4945 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4946 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004947 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004948 bool skip = false;
4949 if (drawCount == 0) return skip;
4950
sjfricke0bea06e2022-06-05 09:22:26 +09004951 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004952 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004953 VkDeviceSize size = struct_size;
4954 if (drawCount == 1 || stride == size) {
4955 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004956 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004957 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4958 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004959 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004960 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004961 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004962 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004963 }
4964 } else {
4965 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004966 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004967 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4968 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004969 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004970 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
4971 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4972 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004973 break;
4974 }
4975 }
4976 }
4977 return skip;
4978}
4979
John Zulauf14940722021-04-12 15:19:02 -06004980void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004981 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4982 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004983 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004984 VkDeviceSize size = struct_size;
4985 if (drawCount == 1 || stride == size) {
4986 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004987 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004988 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004989 } else {
4990 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004991 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004992 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4993 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004994 }
4995 }
4996}
4997
John Zulauffaea0ee2021-01-14 14:01:32 -07004998bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4999 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005000 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005001 bool skip = false;
5002
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005003 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005004 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005005 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5006 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005007 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005008 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5009 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5010 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005011 }
5012 return skip;
5013}
5014
John Zulauf14940722021-04-12 15:19:02 -06005015void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005016 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005017 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005018 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005019}
5020
locke-lunarg36ba2592020-04-03 09:42:04 -06005021bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005022 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005023 const auto *cb_access_context = GetAccessContext(commandBuffer);
5024 assert(cb_access_context);
5025 if (!cb_access_context) return skip;
5026
sjfricke0bea06e2022-06-05 09:22:26 +09005027 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005028 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005029}
5030
5031void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005032 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005033 auto *cb_access_context = GetAccessContext(commandBuffer);
5034 assert(cb_access_context);
5035 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005036
locke-lunarg61870c22020-06-09 14:51:50 -06005037 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005038}
locke-lunarge1a67022020-04-29 00:15:36 -06005039
5040bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005041 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005042 const auto *cb_access_context = GetAccessContext(commandBuffer);
5043 assert(cb_access_context);
5044 if (!cb_access_context) return skip;
5045
5046 const auto *context = cb_access_context->GetCurrentAccessContext();
5047 assert(context);
5048 if (!context) return skip;
5049
sjfricke0bea06e2022-06-05 09:22:26 +09005050 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005051 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005052 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005053 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005054}
5055
5056void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005057 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005058 auto *cb_access_context = GetAccessContext(commandBuffer);
5059 assert(cb_access_context);
5060 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5061 auto *context = cb_access_context->GetCurrentAccessContext();
5062 assert(context);
5063
locke-lunarg61870c22020-06-09 14:51:50 -06005064 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5065 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005066}
5067
5068bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5069 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005070 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005071 const auto *cb_access_context = GetAccessContext(commandBuffer);
5072 assert(cb_access_context);
5073 if (!cb_access_context) return skip;
5074
sjfricke0bea06e2022-06-05 09:22:26 +09005075 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5076 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5077 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005078 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005079}
5080
5081void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5082 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005083 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005084 auto *cb_access_context = GetAccessContext(commandBuffer);
5085 assert(cb_access_context);
5086 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005087
locke-lunarg61870c22020-06-09 14:51:50 -06005088 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5089 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5090 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005091}
5092
5093bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5094 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005095 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005096 const auto *cb_access_context = GetAccessContext(commandBuffer);
5097 assert(cb_access_context);
5098 if (!cb_access_context) return skip;
5099
sjfricke0bea06e2022-06-05 09:22:26 +09005100 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5101 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5102 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005103 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005104}
5105
5106void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5107 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005108 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005109 auto *cb_access_context = GetAccessContext(commandBuffer);
5110 assert(cb_access_context);
5111 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005112
locke-lunarg61870c22020-06-09 14:51:50 -06005113 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5114 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5115 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005116}
5117
5118bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5119 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005120 bool skip = false;
5121 if (drawCount == 0) return skip;
5122
locke-lunargff255f92020-05-13 18:53:52 -06005123 const auto *cb_access_context = GetAccessContext(commandBuffer);
5124 assert(cb_access_context);
5125 if (!cb_access_context) return skip;
5126
5127 const auto *context = cb_access_context->GetCurrentAccessContext();
5128 assert(context);
5129 if (!context) return skip;
5130
sjfricke0bea06e2022-06-05 09:22:26 +09005131 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5132 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005133 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005134 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005135
5136 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5137 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5138 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005139 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005140 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005141}
5142
5143void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5144 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005145 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005146 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005147 auto *cb_access_context = GetAccessContext(commandBuffer);
5148 assert(cb_access_context);
5149 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5150 auto *context = cb_access_context->GetCurrentAccessContext();
5151 assert(context);
5152
locke-lunarg61870c22020-06-09 14:51:50 -06005153 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5154 cb_access_context->RecordDrawSubpassAttachment(tag);
5155 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005156
5157 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5158 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5159 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005160 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005161}
5162
5163bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5164 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005165 bool skip = false;
5166 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005167 const auto *cb_access_context = GetAccessContext(commandBuffer);
5168 assert(cb_access_context);
5169 if (!cb_access_context) return skip;
5170
5171 const auto *context = cb_access_context->GetCurrentAccessContext();
5172 assert(context);
5173 if (!context) return skip;
5174
sjfricke0bea06e2022-06-05 09:22:26 +09005175 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5176 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005177 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005178 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005179
5180 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5181 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5182 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005183 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005184 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005185}
5186
5187void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5188 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005189 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005190 auto *cb_access_context = GetAccessContext(commandBuffer);
5191 assert(cb_access_context);
5192 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5193 auto *context = cb_access_context->GetCurrentAccessContext();
5194 assert(context);
5195
locke-lunarg61870c22020-06-09 14:51:50 -06005196 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5197 cb_access_context->RecordDrawSubpassAttachment(tag);
5198 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005199
5200 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5201 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5202 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005203 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005204}
5205
5206bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5207 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005208 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005209 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005210 const auto *cb_access_context = GetAccessContext(commandBuffer);
5211 assert(cb_access_context);
5212 if (!cb_access_context) return skip;
5213
5214 const auto *context = cb_access_context->GetCurrentAccessContext();
5215 assert(context);
5216 if (!context) return skip;
5217
sjfricke0bea06e2022-06-05 09:22:26 +09005218 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5219 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005220 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005221 maxDrawCount, stride, cmd_type);
5222 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005223
5224 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5225 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5226 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005227 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005228 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005229}
5230
5231bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5232 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5233 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005234 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005235 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005236}
5237
sfricke-samsung85584a72021-09-30 21:43:38 -07005238void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5239 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5240 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005241 auto *cb_access_context = GetAccessContext(commandBuffer);
5242 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005243 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005244 auto *context = cb_access_context->GetCurrentAccessContext();
5245 assert(context);
5246
locke-lunarg61870c22020-06-09 14:51:50 -06005247 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5248 cb_access_context->RecordDrawSubpassAttachment(tag);
5249 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5250 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005251
5252 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5253 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5254 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005255 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005256}
5257
sfricke-samsung85584a72021-09-30 21:43:38 -07005258void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5259 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5260 uint32_t stride) {
5261 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5262 stride);
5263 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5264 CMD_DRAWINDIRECTCOUNT);
5265}
locke-lunarge1a67022020-04-29 00:15:36 -06005266bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5267 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5268 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005269 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005270 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005271}
5272
5273void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5274 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5275 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005276 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5277 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005278 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5279 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005280}
5281
5282bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5283 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5284 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005285 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005286 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005287}
5288
5289void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5290 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5291 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005292 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5293 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005294 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5295 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005296}
5297
5298bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5299 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005300 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005301 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005302 const auto *cb_access_context = GetAccessContext(commandBuffer);
5303 assert(cb_access_context);
5304 if (!cb_access_context) return skip;
5305
5306 const auto *context = cb_access_context->GetCurrentAccessContext();
5307 assert(context);
5308 if (!context) return skip;
5309
sjfricke0bea06e2022-06-05 09:22:26 +09005310 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5311 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005312 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005313 offset, maxDrawCount, stride, cmd_type);
5314 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005315
5316 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5317 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5318 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005319 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005320 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005321}
5322
5323bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5324 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5325 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005326 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005327 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005328}
5329
sfricke-samsung85584a72021-09-30 21:43:38 -07005330void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5331 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5332 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005333 auto *cb_access_context = GetAccessContext(commandBuffer);
5334 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005335 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005336 auto *context = cb_access_context->GetCurrentAccessContext();
5337 assert(context);
5338
locke-lunarg61870c22020-06-09 14:51:50 -06005339 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5340 cb_access_context->RecordDrawSubpassAttachment(tag);
5341 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5342 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005343
5344 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5345 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005346 // We will update the index and vertex buffer in SubmitQueue in the future.
5347 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005348}
5349
sfricke-samsung85584a72021-09-30 21:43:38 -07005350void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5351 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5352 uint32_t maxDrawCount, uint32_t stride) {
5353 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5354 maxDrawCount, stride);
5355 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5356 CMD_DRAWINDEXEDINDIRECTCOUNT);
5357}
5358
locke-lunarge1a67022020-04-29 00:15:36 -06005359bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5360 VkDeviceSize offset, VkBuffer countBuffer,
5361 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5362 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005363 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005364 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005365}
5366
5367void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5368 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5369 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005370 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5371 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005372 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5373 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005374}
5375
5376bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5377 VkDeviceSize offset, VkBuffer countBuffer,
5378 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5379 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005380 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005381 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005382}
5383
5384void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5385 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5386 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005387 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5388 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005389 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5390 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005391}
5392
5393bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5394 const VkClearColorValue *pColor, uint32_t rangeCount,
5395 const VkImageSubresourceRange *pRanges) const {
5396 bool skip = false;
5397 const auto *cb_access_context = GetAccessContext(commandBuffer);
5398 assert(cb_access_context);
5399 if (!cb_access_context) return skip;
5400
5401 const auto *context = cb_access_context->GetCurrentAccessContext();
5402 assert(context);
5403 if (!context) return skip;
5404
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005405 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005406
5407 for (uint32_t index = 0; index < rangeCount; index++) {
5408 const auto &range = pRanges[index];
5409 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005410 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005411 if (hazard.hazard) {
5412 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005413 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005414 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005415 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005416 }
5417 }
5418 }
5419 return skip;
5420}
5421
5422void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5423 const VkClearColorValue *pColor, uint32_t rangeCount,
5424 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005425 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005426 auto *cb_access_context = GetAccessContext(commandBuffer);
5427 assert(cb_access_context);
5428 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5429 auto *context = cb_access_context->GetCurrentAccessContext();
5430 assert(context);
5431
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005432 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005433
5434 for (uint32_t index = 0; index < rangeCount; index++) {
5435 const auto &range = pRanges[index];
5436 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005437 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005438 }
5439 }
5440}
5441
5442bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5443 VkImageLayout imageLayout,
5444 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5445 const VkImageSubresourceRange *pRanges) const {
5446 bool skip = false;
5447 const auto *cb_access_context = GetAccessContext(commandBuffer);
5448 assert(cb_access_context);
5449 if (!cb_access_context) return skip;
5450
5451 const auto *context = cb_access_context->GetCurrentAccessContext();
5452 assert(context);
5453 if (!context) return skip;
5454
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005455 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005456
5457 for (uint32_t index = 0; index < rangeCount; index++) {
5458 const auto &range = pRanges[index];
5459 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005460 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005461 if (hazard.hazard) {
5462 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005463 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005464 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005465 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005466 }
5467 }
5468 }
5469 return skip;
5470}
5471
5472void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5473 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5474 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005475 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005476 auto *cb_access_context = GetAccessContext(commandBuffer);
5477 assert(cb_access_context);
5478 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5479 auto *context = cb_access_context->GetCurrentAccessContext();
5480 assert(context);
5481
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005482 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005483
5484 for (uint32_t index = 0; index < rangeCount; index++) {
5485 const auto &range = pRanges[index];
5486 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005487 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005488 }
5489 }
5490}
5491
5492bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5493 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5494 VkDeviceSize dstOffset, VkDeviceSize stride,
5495 VkQueryResultFlags flags) const {
5496 bool skip = false;
5497 const auto *cb_access_context = GetAccessContext(commandBuffer);
5498 assert(cb_access_context);
5499 if (!cb_access_context) return skip;
5500
5501 const auto *context = cb_access_context->GetCurrentAccessContext();
5502 assert(context);
5503 if (!context) return skip;
5504
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005505 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005506
5507 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005508 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005509 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005510 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005511 skip |=
5512 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5513 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005514 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005515 }
5516 }
locke-lunargff255f92020-05-13 18:53:52 -06005517
5518 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005519 return skip;
5520}
5521
5522void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5523 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5524 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005525 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5526 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005527 auto *cb_access_context = GetAccessContext(commandBuffer);
5528 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005529 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005530 auto *context = cb_access_context->GetCurrentAccessContext();
5531 assert(context);
5532
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005533 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005534
5535 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005536 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005537 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005538 }
locke-lunargff255f92020-05-13 18:53:52 -06005539
5540 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005541}
5542
5543bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5544 VkDeviceSize size, uint32_t data) const {
5545 bool skip = false;
5546 const auto *cb_access_context = GetAccessContext(commandBuffer);
5547 assert(cb_access_context);
5548 if (!cb_access_context) return skip;
5549
5550 const auto *context = cb_access_context->GetCurrentAccessContext();
5551 assert(context);
5552 if (!context) return skip;
5553
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005554 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005555
5556 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005557 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005558 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005559 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005560 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005561 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005562 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005563 }
5564 }
5565 return skip;
5566}
5567
5568void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5569 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005570 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005571 auto *cb_access_context = GetAccessContext(commandBuffer);
5572 assert(cb_access_context);
5573 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5574 auto *context = cb_access_context->GetCurrentAccessContext();
5575 assert(context);
5576
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005577 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005578
5579 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005580 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005581 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005582 }
5583}
5584
5585bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5586 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5587 const VkImageResolve *pRegions) const {
5588 bool skip = false;
5589 const auto *cb_access_context = GetAccessContext(commandBuffer);
5590 assert(cb_access_context);
5591 if (!cb_access_context) return skip;
5592
5593 const auto *context = cb_access_context->GetCurrentAccessContext();
5594 assert(context);
5595 if (!context) return skip;
5596
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005597 auto src_image = Get<IMAGE_STATE>(srcImage);
5598 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005599
5600 for (uint32_t region = 0; region < regionCount; region++) {
5601 const auto &resolve_region = pRegions[region];
5602 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005603 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005604 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005605 if (hazard.hazard) {
5606 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005607 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005608 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005609 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005610 }
5611 }
5612
5613 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005614 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005615 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005616 if (hazard.hazard) {
5617 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005618 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005619 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005620 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005621 }
5622 if (skip) break;
5623 }
5624 }
5625
5626 return skip;
5627}
5628
5629void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5630 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5631 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005632 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5633 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005634 auto *cb_access_context = GetAccessContext(commandBuffer);
5635 assert(cb_access_context);
5636 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5637 auto *context = cb_access_context->GetCurrentAccessContext();
5638 assert(context);
5639
Jeremy Gebben9f537102021-10-05 16:37:12 -06005640 auto src_image = Get<IMAGE_STATE>(srcImage);
5641 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005642
5643 for (uint32_t region = 0; region < regionCount; region++) {
5644 const auto &resolve_region = pRegions[region];
5645 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005646 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005647 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005648 }
5649 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005650 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005651 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005652 }
5653 }
5654}
5655
Tony-LunarG562fc102021-11-12 13:58:35 -07005656bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5657 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005658 bool skip = false;
5659 const auto *cb_access_context = GetAccessContext(commandBuffer);
5660 assert(cb_access_context);
5661 if (!cb_access_context) return skip;
5662
5663 const auto *context = cb_access_context->GetCurrentAccessContext();
5664 assert(context);
5665 if (!context) return skip;
5666
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005667 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5668 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005669
5670 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5671 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5672 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005673 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005674 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005675 if (hazard.hazard) {
5676 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005677 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005678 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005679 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005680 }
5681 }
5682
5683 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005684 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005685 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005686 if (hazard.hazard) {
5687 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005688 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005689 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005690 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005691 }
5692 if (skip) break;
5693 }
5694 }
5695
5696 return skip;
5697}
5698
Tony-LunarG562fc102021-11-12 13:58:35 -07005699bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5700 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5701 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5702}
5703
5704bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5705 const VkResolveImageInfo2 *pResolveImageInfo) const {
5706 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5707}
5708
5709void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5710 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005711 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5712 auto *cb_access_context = GetAccessContext(commandBuffer);
5713 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005714 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005715 auto *context = cb_access_context->GetCurrentAccessContext();
5716 assert(context);
5717
Jeremy Gebben9f537102021-10-05 16:37:12 -06005718 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5719 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005720
5721 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5722 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5723 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005724 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005725 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005726 }
5727 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005728 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005729 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005730 }
5731 }
5732}
5733
Tony-LunarG562fc102021-11-12 13:58:35 -07005734void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5735 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5736 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5737}
5738
5739void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5740 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5741}
5742
locke-lunarge1a67022020-04-29 00:15:36 -06005743bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5744 VkDeviceSize dataSize, const void *pData) const {
5745 bool skip = false;
5746 const auto *cb_access_context = GetAccessContext(commandBuffer);
5747 assert(cb_access_context);
5748 if (!cb_access_context) return skip;
5749
5750 const auto *context = cb_access_context->GetCurrentAccessContext();
5751 assert(context);
5752 if (!context) return skip;
5753
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005754 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005755
5756 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005757 // VK_WHOLE_SIZE not allowed
5758 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005759 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005760 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005761 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005762 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005763 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005764 }
5765 }
5766 return skip;
5767}
5768
5769void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5770 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005771 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005772 auto *cb_access_context = GetAccessContext(commandBuffer);
5773 assert(cb_access_context);
5774 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5775 auto *context = cb_access_context->GetCurrentAccessContext();
5776 assert(context);
5777
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005778 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005779
5780 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005781 // VK_WHOLE_SIZE not allowed
5782 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005783 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005784 }
5785}
locke-lunargff255f92020-05-13 18:53:52 -06005786
5787bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5788 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5789 bool skip = false;
5790 const auto *cb_access_context = GetAccessContext(commandBuffer);
5791 assert(cb_access_context);
5792 if (!cb_access_context) return skip;
5793
5794 const auto *context = cb_access_context->GetCurrentAccessContext();
5795 assert(context);
5796 if (!context) return skip;
5797
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005798 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005799
5800 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005801 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005802 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005803 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005804 skip |=
5805 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5806 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005807 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005808 }
5809 }
5810 return skip;
5811}
5812
5813void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5814 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005815 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005816 auto *cb_access_context = GetAccessContext(commandBuffer);
5817 assert(cb_access_context);
5818 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5819 auto *context = cb_access_context->GetCurrentAccessContext();
5820 assert(context);
5821
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005822 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005823
5824 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005825 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005826 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005827 }
5828}
John Zulauf49beb112020-11-04 16:06:31 -07005829
5830bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5831 bool skip = false;
5832 const auto *cb_context = GetAccessContext(commandBuffer);
5833 assert(cb_context);
5834 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005835 const auto *access_context = cb_context->GetCurrentAccessContext();
5836 assert(access_context);
5837 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005838
John Zulaufe0757ba2022-06-10 16:51:45 -06005839 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005840 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005841}
5842
5843void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5844 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5845 auto *cb_context = GetAccessContext(commandBuffer);
5846 assert(cb_context);
5847 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005848
5849 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5850 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005851}
5852
John Zulauf4edde622021-02-15 08:54:50 -07005853bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5854 const VkDependencyInfoKHR *pDependencyInfo) const {
5855 bool skip = false;
5856 const auto *cb_context = GetAccessContext(commandBuffer);
5857 assert(cb_context);
5858 if (!cb_context || !pDependencyInfo) return skip;
5859
John Zulaufe0757ba2022-06-10 16:51:45 -06005860 const auto *access_context = cb_context->GetCurrentAccessContext();
5861 assert(access_context);
5862 if (!access_context) return skip;
5863
5864 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005865 return set_event_op.Validate(*cb_context);
5866}
5867
Tony-LunarGc43525f2021-11-15 16:12:38 -07005868bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5869 const VkDependencyInfo *pDependencyInfo) const {
5870 bool skip = false;
5871 const auto *cb_context = GetAccessContext(commandBuffer);
5872 assert(cb_context);
5873 if (!cb_context || !pDependencyInfo) return skip;
5874
John Zulaufe0757ba2022-06-10 16:51:45 -06005875 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005876 return set_event_op.Validate(*cb_context);
5877}
5878
John Zulauf4edde622021-02-15 08:54:50 -07005879void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5880 const VkDependencyInfoKHR *pDependencyInfo) {
5881 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5882 auto *cb_context = GetAccessContext(commandBuffer);
5883 assert(cb_context);
5884 if (!cb_context || !pDependencyInfo) return;
5885
John Zulaufe0757ba2022-06-10 16:51:45 -06005886 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5887 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005888}
5889
Tony-LunarGc43525f2021-11-15 16:12:38 -07005890void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5891 const VkDependencyInfo *pDependencyInfo) {
5892 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5893 auto *cb_context = GetAccessContext(commandBuffer);
5894 assert(cb_context);
5895 if (!cb_context || !pDependencyInfo) return;
5896
John Zulaufe0757ba2022-06-10 16:51:45 -06005897 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5898 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005899}
5900
John Zulauf49beb112020-11-04 16:06:31 -07005901bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5902 VkPipelineStageFlags stageMask) const {
5903 bool skip = false;
5904 const auto *cb_context = GetAccessContext(commandBuffer);
5905 assert(cb_context);
5906 if (!cb_context) return skip;
5907
John Zulauf36ef9282021-02-02 11:47:24 -07005908 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005909 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005910}
5911
5912void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5913 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5914 auto *cb_context = GetAccessContext(commandBuffer);
5915 assert(cb_context);
5916 if (!cb_context) return;
5917
John Zulauf1bf30522021-09-03 15:39:06 -06005918 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005919}
5920
John Zulauf4edde622021-02-15 08:54:50 -07005921bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5922 VkPipelineStageFlags2KHR stageMask) const {
5923 bool skip = false;
5924 const auto *cb_context = GetAccessContext(commandBuffer);
5925 assert(cb_context);
5926 if (!cb_context) return skip;
5927
5928 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5929 return reset_event_op.Validate(*cb_context);
5930}
5931
Tony-LunarGa2662db2021-11-16 07:26:24 -07005932bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5933 VkPipelineStageFlags2 stageMask) const {
5934 bool skip = false;
5935 const auto *cb_context = GetAccessContext(commandBuffer);
5936 assert(cb_context);
5937 if (!cb_context) return skip;
5938
5939 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5940 return reset_event_op.Validate(*cb_context);
5941}
5942
John Zulauf4edde622021-02-15 08:54:50 -07005943void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5944 VkPipelineStageFlags2KHR stageMask) {
5945 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5946 auto *cb_context = GetAccessContext(commandBuffer);
5947 assert(cb_context);
5948 if (!cb_context) return;
5949
John Zulauf1bf30522021-09-03 15:39:06 -06005950 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005951}
5952
Tony-LunarGa2662db2021-11-16 07:26:24 -07005953void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5954 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5955 auto *cb_context = GetAccessContext(commandBuffer);
5956 assert(cb_context);
5957 if (!cb_context) return;
5958
5959 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5960}
5961
John Zulauf49beb112020-11-04 16:06:31 -07005962bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5963 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5964 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5965 uint32_t bufferMemoryBarrierCount,
5966 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5967 uint32_t imageMemoryBarrierCount,
5968 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5969 bool skip = false;
5970 const auto *cb_context = GetAccessContext(commandBuffer);
5971 assert(cb_context);
5972 if (!cb_context) return skip;
5973
John Zulauf36ef9282021-02-02 11:47:24 -07005974 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5975 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5976 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005977 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005978}
5979
5980void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5981 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5982 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5983 uint32_t bufferMemoryBarrierCount,
5984 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5985 uint32_t imageMemoryBarrierCount,
5986 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5987 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5988 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5989 imageMemoryBarrierCount, pImageMemoryBarriers);
5990
5991 auto *cb_context = GetAccessContext(commandBuffer);
5992 assert(cb_context);
5993 if (!cb_context) return;
5994
John Zulauf1bf30522021-09-03 15:39:06 -06005995 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005996 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005997 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005998}
5999
John Zulauf4edde622021-02-15 08:54:50 -07006000bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6001 const VkDependencyInfoKHR *pDependencyInfos) const {
6002 bool skip = false;
6003 const auto *cb_context = GetAccessContext(commandBuffer);
6004 assert(cb_context);
6005 if (!cb_context) return skip;
6006
6007 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6008 skip |= wait_events_op.Validate(*cb_context);
6009 return skip;
6010}
6011
6012void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6013 const VkDependencyInfoKHR *pDependencyInfos) {
6014 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6015
6016 auto *cb_context = GetAccessContext(commandBuffer);
6017 assert(cb_context);
6018 if (!cb_context) return;
6019
John Zulauf1bf30522021-09-03 15:39:06 -06006020 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6021 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006022}
6023
Tony-LunarG1364cf52021-11-17 16:10:11 -07006024bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6025 const VkDependencyInfo *pDependencyInfos) const {
6026 bool skip = false;
6027 const auto *cb_context = GetAccessContext(commandBuffer);
6028 assert(cb_context);
6029 if (!cb_context) return skip;
6030
6031 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6032 skip |= wait_events_op.Validate(*cb_context);
6033 return skip;
6034}
6035
6036void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6037 const VkDependencyInfo *pDependencyInfos) {
6038 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6039
6040 auto *cb_context = GetAccessContext(commandBuffer);
6041 assert(cb_context);
6042 if (!cb_context) return;
6043
6044 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6045 pDependencyInfos);
6046}
6047
John Zulauf4a6105a2020-11-17 15:11:05 -07006048void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006049 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006050 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006051 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006052}
6053
6054// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006055SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006056 IgnoreReason reason = NotIgnored;
6057
sjfricke0bea06e2022-06-05 09:22:26 +09006058 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006059 reason = SetVsWait2;
6060 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6061 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006062 } else if (unsynchronized_set) {
6063 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006064 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006065 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006066 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006067 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006068 } else {
6069 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006070 }
6071
6072 return reason;
6073}
6074
Jeremy Gebben40a22942020-12-22 14:22:06 -07006075bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006076 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6077 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6078 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006079}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006080
sjfricke0bea06e2022-06-05 09:22:26 +09006081SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006082 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6083 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006084 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6085 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6086 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006087 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006088 auto &barrier_set = barriers_[0];
6089 barrier_set.dependency_flags = dependencyFlags;
6090 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6091 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006092 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006093 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6094 pMemoryBarriers);
6095 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6096 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6097 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6098 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006099}
6100
sjfricke0bea06e2022-06-05 09:22:26 +09006101SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006102 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006103 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006104 for (uint32_t i = 0; i < event_count; i++) {
6105 const auto &dep_info = dep_infos[i];
6106 auto &barrier_set = barriers_[i];
6107 barrier_set.dependency_flags = dep_info.dependencyFlags;
6108 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6109 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6110 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6111 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6112 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6113 dep_info.pMemoryBarriers);
6114 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6115 dep_info.pBufferMemoryBarriers);
6116 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6117 dep_info.pImageMemoryBarriers);
6118 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006119}
6120
sjfricke0bea06e2022-06-05 09:22:26 +09006121SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006122 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6123 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6124 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6125 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6126 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006127 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6128 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6129 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006130
sjfricke0bea06e2022-06-05 09:22:26 +09006131SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006132 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006133 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006134
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006135bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6136 bool skip = false;
6137 const auto *context = cb_context.GetCurrentAccessContext();
6138 assert(context);
6139 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006140 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6141
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006142 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006143 const auto &barrier_set = barriers_[0];
6144 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6145 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6146 const auto *image_state = image_barrier.image.get();
6147 if (!image_state) continue;
6148 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6149 if (hazard.hazard) {
6150 // PHASE1 TODO -- add tag information to log msg when useful.
6151 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006152 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006153 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6154 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6155 string_SyncHazard(hazard.hazard), image_barrier.index,
6156 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006157 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006158 }
6159 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006160 return skip;
6161}
6162
John Zulaufd5115702021-01-18 12:34:33 -07006163struct SyncOpPipelineBarrierFunctorFactory {
6164 using BarrierOpFunctor = PipelineBarrierOp;
6165 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6166 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6167 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6168 using BufferRange = ResourceAccessRange;
6169 using ImageRange = subresource_adapter::ImageRangeGenerator;
6170 using GlobalRange = ResourceAccessRange;
6171
John Zulauf00119522022-05-23 19:07:42 -06006172 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6173 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006174 }
John Zulauf14940722021-04-12 15:19:02 -06006175 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006176 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6177 }
John Zulauf00119522022-05-23 19:07:42 -06006178 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6179 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006180 }
6181
6182 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6183 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6184 const auto base_address = ResourceBaseAddress(buffer);
6185 return (range + base_address);
6186 }
John Zulauf110413c2021-03-20 05:38:38 -06006187 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006188 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006189
6190 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006191 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006192 return range_gen;
6193 }
6194 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6195};
6196
6197template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006198void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6199 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006200 for (const auto &barrier : barriers) {
6201 const auto *state = barrier.GetState();
6202 if (state) {
6203 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006204 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006205 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6206 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6207 }
6208 }
6209}
6210
6211template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006212void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6213 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006214 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6215 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006216 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006217 }
6218 for (const auto address_type : kAddressTypes) {
6219 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6220 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6221 }
6222}
6223
John Zulaufdab327f2022-07-08 12:02:05 -06006224ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006225 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006226 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006227 return tag;
6228}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006229
John Zulauf0223f142022-07-06 09:05:39 -06006230void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006231 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006232 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6233 assert(barriers_.size() == 1);
6234 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006235 if (!exec_context.ValidForSyncOps()) return;
6236
6237 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6238 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6239 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006240 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6241 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6242 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006243 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006244 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006245 } else {
6246 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006247 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006248 }
6249 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006250}
6251
John Zulauf8eda1562021-04-13 17:06:41 -06006252bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006253 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006254 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6255 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006256 return false;
6257}
6258
John Zulauf4edde622021-02-15 08:54:50 -07006259void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6260 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6261 const VkMemoryBarrier *barriers) {
6262 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006263 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006264 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006265 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006266 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006267 }
6268 if (0 == memory_barrier_count) {
6269 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006270 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006271 }
John Zulauf4edde622021-02-15 08:54:50 -07006272 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006273}
6274
John Zulauf4edde622021-02-15 08:54:50 -07006275void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6276 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6277 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6278 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006279 for (uint32_t index = 0; index < barrier_count; index++) {
6280 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006281 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006282 if (buffer) {
6283 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6284 const auto range = MakeRange(barrier.offset, barrier_size);
6285 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006286 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006287 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006288 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006289 }
6290 }
6291}
6292
John Zulauf4edde622021-02-15 08:54:50 -07006293void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006294 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006295 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006296 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006297 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006298 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6299 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6300 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006301 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006302 }
John Zulauf4edde622021-02-15 08:54:50 -07006303 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006304}
6305
John Zulauf4edde622021-02-15 08:54:50 -07006306void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6307 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006308 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006309 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006310 for (uint32_t index = 0; index < barrier_count; index++) {
6311 const auto &barrier = barriers[index];
6312 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6313 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006314 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006315 if (buffer) {
6316 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6317 const auto range = MakeRange(barrier.offset, barrier_size);
6318 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006319 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006320 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006321 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006322 }
6323 }
6324}
6325
John Zulauf4edde622021-02-15 08:54:50 -07006326void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6327 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6328 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6329 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006330 for (uint32_t index = 0; index < barrier_count; index++) {
6331 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006332 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006333 if (image) {
6334 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6335 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006336 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006337 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006338 image_memory_barriers.emplace_back();
6339 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006340 }
6341 }
6342}
John Zulaufd5115702021-01-18 12:34:33 -07006343
John Zulauf4edde622021-02-15 08:54:50 -07006344void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6345 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006346 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006347 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006348 for (uint32_t index = 0; index < barrier_count; index++) {
6349 const auto &barrier = barriers[index];
6350 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6351 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006352 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006353 if (image) {
6354 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6355 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006356 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006357 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006358 image_memory_barriers.emplace_back();
6359 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006360 }
6361 }
6362}
6363
sjfricke0bea06e2022-06-05 09:22:26 +09006364SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6365 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6366 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6367 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6368 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6369 const VkImageMemoryBarrier *pImageMemoryBarriers)
6370 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006371 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6372 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006373 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006374}
6375
sjfricke0bea06e2022-06-05 09:22:26 +09006376SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6377 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6378 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006379 MakeEventsList(sync_state, eventCount, pEvents);
6380 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6381}
6382
John Zulauf610e28c2021-08-03 17:46:23 -06006383const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6384
John Zulaufd5115702021-01-18 12:34:33 -07006385bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006386 bool skip = false;
6387 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006388 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006389
John Zulauf610e28c2021-08-03 17:46:23 -06006390 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006391 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6392 const auto &barrier_set = barriers_[barrier_set_index];
6393 if (barrier_set.single_exec_scope) {
6394 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6395 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6396 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6397 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6398 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6399 } else {
6400 const auto &barriers = barrier_set.memory_barriers;
6401 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6402 const auto &barrier = barriers[barrier_index];
6403 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6404 const std::string vuid =
6405 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6406 skip =
6407 sync_state.LogInfo(command_buffer_handle, vuid,
6408 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6409 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6410 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6411 }
6412 }
6413 }
6414 }
John Zulaufd5115702021-01-18 12:34:33 -07006415 }
6416
John Zulauf610e28c2021-08-03 17:46:23 -06006417 // The rest is common to record time and replay time.
6418 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6419 return skip;
6420}
6421
John Zulaufbb890452021-12-14 11:30:18 -07006422bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006423 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006424 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006425 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006426
Jeremy Gebben40a22942020-12-22 14:22:06 -07006427 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006428 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006429 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006430 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006431 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006432 size_t barrier_set_index = 0;
6433 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006434 for (const auto &event : events_) {
6435 const auto *sync_event = events_context->Get(event.get());
6436 const auto &barrier_set = barriers_[barrier_set_index];
6437 if (!sync_event) {
6438 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6439 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6440 // new validation error... wait without previously submitted set event...
6441 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 -07006442 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006443 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006444 }
John Zulauf610e28c2021-08-03 17:46:23 -06006445
6446 // For replay calls, don't revalidate "same command buffer" events
6447 if (sync_event->last_command_tag > base_tag) continue;
6448
John Zulauf78394fc2021-07-12 15:41:40 -06006449 const auto event_handle = sync_event->event->event();
6450 // TODO add "destroyed" checks
6451
John Zulaufe0757ba2022-06-10 16:51:45 -06006452 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006453 // Only accumulate barrier and event stages if there is a pending set in the current context
6454 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6455 event_stage_masks |= sync_event->scope.mask_param;
6456 }
6457
John Zulauf78394fc2021-07-12 15:41:40 -06006458 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006459
sjfricke0bea06e2022-06-05 09:22:26 +09006460 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006461 if (ignore_reason) {
6462 switch (ignore_reason) {
6463 case SyncEventState::ResetWaitRace:
6464 case SyncEventState::Reset2WaitRace: {
6465 // Four permuations of Reset and Wait calls...
6466 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006467 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006468 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006469 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6470 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006471 }
6472 const char *const message =
6473 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6474 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6475 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006476 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006477 break;
6478 }
6479 case SyncEventState::SetRace: {
6480 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6481 // this event
6482 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6483 const char *const message =
6484 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6485 const char *const reason = "First synchronization scope is undefined.";
6486 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6487 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006488 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006489 break;
6490 }
6491 case SyncEventState::MissingStageBits: {
6492 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6493 // Issue error message that event waited for is not in wait events scope
6494 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6495 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6496 ". Bits missing from srcStageMask %s. %s";
6497 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6498 sync_state.report_data->FormatHandle(event_handle).c_str(),
6499 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006500 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006501 break;
6502 }
6503 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006504 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006505 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6506 sync_state.report_data->FormatHandle(event_handle).c_str(),
6507 CommandTypeString(sync_event->last_command));
6508 break;
6509 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006510 case SyncEventState::MissingSetEvent: {
6511 // TODO: There are conditions at queue submit time where we can definitively say that
6512 // a missing set event is an error. Add those if not captured in CoreChecks
6513 break;
6514 }
John Zulauf78394fc2021-07-12 15:41:40 -06006515 default:
6516 assert(ignore_reason == SyncEventState::NotIgnored);
6517 }
6518 } else if (barrier_set.image_memory_barriers.size()) {
6519 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006520 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006521 assert(context);
6522 for (const auto &image_memory_barrier : image_memory_barriers) {
6523 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6524 const auto *image_state = image_memory_barrier.image.get();
6525 if (!image_state) continue;
6526 const auto &subresource_range = image_memory_barrier.range;
6527 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006528 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6529 src_access_scope, queue_id, *sync_event,
6530 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006531 if (hazard.hazard) {
6532 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6533 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6534 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6535 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006536 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006537 break;
6538 }
6539 }
6540 }
6541 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6542 // 03839
6543 barrier_set_index += barrier_set_incr;
6544 }
John Zulaufd5115702021-01-18 12:34:33 -07006545
6546 // 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 -07006547 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 -07006548 if (extra_stage_bits) {
6549 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006550 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6551 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006552 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006553 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006554 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006555 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006556 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006557 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006558 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006559 " vkCmdSetEvent may be in previously submitted command buffer.");
6560 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006561 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006562 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006563 }
6564 }
6565 return skip;
6566}
6567
6568struct SyncOpWaitEventsFunctorFactory {
6569 using BarrierOpFunctor = WaitEventBarrierOp;
6570 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6571 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6572 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6573 using BufferRange = EventSimpleRangeGenerator;
6574 using ImageRange = EventImageRangeGenerator;
6575 using GlobalRange = EventSimpleRangeGenerator;
6576
6577 // Need to restrict to only valid exec and access scope for this event
6578 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6579 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006580 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006581 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6582 return barrier;
6583 }
John Zulauf00119522022-05-23 19:07:42 -06006584 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006585 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006586 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006587 }
John Zulauf14940722021-04-12 15:19:02 -06006588 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006589 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6590 }
John Zulauf00119522022-05-23 19:07:42 -06006591 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006592 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006593 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006594 }
6595
6596 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6597 const AccessAddressType address_type = GetAccessAddressType(buffer);
6598 const auto base_address = ResourceBaseAddress(buffer);
6599 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6600 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6601 return filtered_range_gen;
6602 }
John Zulauf110413c2021-03-20 05:38:38 -06006603 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006604 if (!SimpleBinding(image)) return ImageRange();
6605 const auto address_type = GetAccessAddressType(image);
6606 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006607 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6608 false);
John Zulaufd5115702021-01-18 12:34:33 -07006609 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6610
6611 return filtered_range_gen;
6612 }
6613 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6614 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6615 }
6616 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6617 SyncEventState *sync_event;
6618};
6619
John Zulaufdab327f2022-07-08 12:02:05 -06006620ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006621 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006622
John Zulauf0223f142022-07-06 09:05:39 -06006623 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006624 return tag;
6625}
6626
John Zulauf0223f142022-07-06 09:05:39 -06006627void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006628 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6629 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6630 // 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 -06006631 if (!exec_context.ValidForSyncOps()) return;
6632 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6633 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6634 const QueueId queue_id = exec_context.GetQueueId();
6635
John Zulaufd5115702021-01-18 12:34:33 -07006636 access_context->ResolvePreviousAccesses();
6637
John Zulauf4edde622021-02-15 08:54:50 -07006638 size_t barrier_set_index = 0;
6639 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6640 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006641 for (auto &event_shared : events_) {
6642 if (!event_shared.get()) continue;
6643 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006644
sjfricke0bea06e2022-06-05 09:22:26 +09006645 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006646 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006647
John Zulauf4edde622021-02-15 08:54:50 -07006648 const auto &barrier_set = barriers_[barrier_set_index];
6649 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006650 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006651 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6652 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6653 // of the barriers is maintained.
6654 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006655 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6656 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6657 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006658
6659 // Apply the global barrier to the event itself (for race condition tracking)
6660 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6661 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6662 sync_event->barriers |= dst.exec_scope;
6663 } else {
6664 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6665 sync_event->barriers = 0U;
6666 }
John Zulauf4edde622021-02-15 08:54:50 -07006667 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006668 }
6669
6670 // Apply the pending barriers
6671 ResolvePendingBarrierFunctor apply_pending_action(tag);
6672 access_context->ApplyToContext(apply_pending_action);
6673}
6674
John Zulauf8eda1562021-04-13 17:06:41 -06006675bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006676 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6677 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006678}
6679
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006680bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6681 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6682 bool skip = false;
6683 const auto *cb_access_context = GetAccessContext(commandBuffer);
6684 assert(cb_access_context);
6685 if (!cb_access_context) return skip;
6686
6687 const auto *context = cb_access_context->GetCurrentAccessContext();
6688 assert(context);
6689 if (!context) return skip;
6690
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006691 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006692
6693 if (dst_buffer) {
6694 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6695 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6696 if (hazard.hazard) {
6697 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6698 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6699 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006700 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006701 }
6702 }
6703 return skip;
6704}
6705
John Zulauf669dfd52021-01-27 17:15:28 -07006706void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006707 events_.reserve(event_count);
6708 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006709 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006710 }
6711}
John Zulauf6ce24372021-01-30 05:56:25 -07006712
sjfricke0bea06e2022-06-05 09:22:26 +09006713SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006714 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006715 : SyncOpBase(cmd_type),
6716 event_(sync_state.Get<EVENT_STATE>(event)),
6717 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006718
John Zulauf1bf30522021-09-03 15:39:06 -06006719bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6720 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6721}
6722
John Zulaufbb890452021-12-14 11:30:18 -07006723bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6724 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006725 assert(events_context);
6726 bool skip = false;
6727 if (!events_context) return skip;
6728
John Zulaufbb890452021-12-14 11:30:18 -07006729 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006730 const auto *sync_event = events_context->Get(event_);
6731 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6732
John Zulauf1bf30522021-09-03 15:39:06 -06006733 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6734
John Zulauf6ce24372021-01-30 05:56:25 -07006735 const char *const set_wait =
6736 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6737 "hazards.";
6738 const char *message = set_wait; // Only one message this call.
6739 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6740 const char *vuid = nullptr;
6741 switch (sync_event->last_command) {
6742 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006743 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006744 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006745 // Needs a barrier between set and reset
6746 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6747 break;
John Zulauf4edde622021-02-15 08:54:50 -07006748 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006749 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006750 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006751 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6752 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6753 break;
6754 }
6755 default:
6756 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006757 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6758 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006759 break;
6760 }
6761 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006762 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6763 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006764 CommandTypeString(sync_event->last_command));
6765 }
6766 }
6767 return skip;
6768}
6769
John Zulaufdab327f2022-07-08 12:02:05 -06006770ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006771 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006772 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006773 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006774}
6775
John Zulauf8eda1562021-04-13 17:06:41 -06006776bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006777 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6778 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006779}
6780
John Zulauf0223f142022-07-06 09:05:39 -06006781void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6782 if (!exec_context.ValidForSyncOps()) return;
6783 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6784
John Zulaufe0757ba2022-06-10 16:51:45 -06006785 auto *sync_event = events_context->GetFromShared(event_);
6786 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6787
6788 // Update the event state
6789 sync_event->last_command = cmd_type_;
6790 sync_event->last_command_tag = tag;
6791 sync_event->unsynchronized_set = CMD_NONE;
6792 sync_event->ResetFirstScope();
6793 sync_event->barriers = 0U;
6794}
John Zulauf8eda1562021-04-13 17:06:41 -06006795
sjfricke0bea06e2022-06-05 09:22:26 +09006796SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006797 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006798 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006799 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006800 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006801 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006802 dep_info_() {
6803 // Snapshot the current access_context for later inspection at wait time.
6804 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6805 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6806 // or Submit time reference.
6807 if (access_context) {
6808 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6809 }
6810}
John Zulauf4edde622021-02-15 08:54:50 -07006811
sjfricke0bea06e2022-06-05 09:22:26 +09006812SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006813 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006814 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006815 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006816 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006817 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006818 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6819 if (access_context) {
6820 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6821 }
6822}
John Zulauf6ce24372021-01-30 05:56:25 -07006823
6824bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006825 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6826}
6827bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006828 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6829 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006830}
6831
John Zulaufbb890452021-12-14 11:30:18 -07006832bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006833 bool skip = false;
6834
John Zulaufbb890452021-12-14 11:30:18 -07006835 const auto &sync_state = exec_context.GetSyncState();
6836 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006837 assert(events_context);
6838 if (!events_context) return skip;
6839
6840 const auto *sync_event = events_context->Get(event_);
6841 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6842
John Zulauf610e28c2021-08-03 17:46:23 -06006843 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6844
John Zulauf6ce24372021-01-30 05:56:25 -07006845 const char *const reset_set =
6846 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6847 "hazards.";
6848 const char *const wait =
6849 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6850
6851 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006852 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006853 const char *message = nullptr;
6854 switch (sync_event->last_command) {
6855 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006856 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006857 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006858 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006859 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006860 message = reset_set;
6861 break;
6862 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006863 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006864 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006865 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006866 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006867 message = reset_set;
6868 break;
6869 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006870 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006871 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006872 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006873 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006874 message = wait;
6875 break;
6876 default:
6877 // The only other valid last command that wasn't one.
6878 assert(sync_event->last_command == CMD_NONE);
6879 break;
6880 }
John Zulauf4edde622021-02-15 08:54:50 -07006881 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006882 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006883 std::string vuid("SYNC-");
6884 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006885 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6886 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006887 CommandTypeString(sync_event->last_command));
6888 }
6889 }
6890
6891 return skip;
6892}
6893
John Zulaufdab327f2022-07-08 12:02:05 -06006894ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006895 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006896 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006897 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006898 assert(recorded_context_);
6899 if (recorded_context_ && events_context) {
6900 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006901 }
6902 return tag;
6903}
John Zulauf6ce24372021-01-30 05:56:25 -07006904
John Zulauf0223f142022-07-06 09:05:39 -06006905void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006906 // Create a copy of the current context, and merge in the state snapshot at record set event time
6907 // 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 -06006908 if (!exec_context.ValidForSyncOps()) return;
6909 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6910 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6911 const QueueId queue_id = exec_context.GetQueueId();
6912
John Zulaufe0757ba2022-06-10 16:51:45 -06006913 auto merged_context = std::make_shared<AccessContext>(*access_context);
6914 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6915 DoRecord(queue_id, tag, merged_context, events_context);
6916}
6917
6918void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6919 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006920 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006921 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006922
6923 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6924 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6925 // any issues caused by naive scope setting here.
6926
6927 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6928 // Given:
6929 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6930 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6931
6932 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6933 sync_event->unsynchronized_set = sync_event->last_command;
6934 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006935 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006936 // We only set the scope if there isn't one
6937 sync_event->scope = src_exec_scope_;
6938
John Zulaufe0757ba2022-06-10 16:51:45 -06006939 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6940 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006941 sync_event->unsynchronized_set = CMD_NONE;
6942 sync_event->first_scope_tag = tag;
6943 }
John Zulauf4edde622021-02-15 08:54:50 -07006944 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006945 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006946 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006947 sync_event->barriers = 0U;
6948}
John Zulauf64ffe552021-02-06 10:25:07 -07006949
sjfricke0bea06e2022-06-05 09:22:26 +09006950SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006951 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006952 const VkSubpassBeginInfo *pSubpassBeginInfo)
John Zulaufdab327f2022-07-08 12:02:05 -06006953 : SyncOpBase(cmd_type), rp_context_(nullptr) {
John Zulauf64ffe552021-02-06 10:25:07 -07006954 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006955 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006956 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006957 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006958 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006959 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006960 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6961 // Note that this a safe to presist as long as shared_attachments is not cleared
6962 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006963 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006964 attachments_.emplace_back(attachment.get());
6965 }
6966 }
6967 if (pSubpassBeginInfo) {
6968 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6969 }
6970 }
6971}
6972
6973bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6974 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6975 bool skip = false;
6976
6977 assert(rp_state_.get());
6978 if (nullptr == rp_state_.get()) return skip;
6979 auto &rp_state = *rp_state_.get();
6980
6981 const uint32_t subpass = 0;
6982
6983 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6984 // hasn't happened yet)
6985 const std::vector<AccessContext> empty_context_vector;
6986 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6987 cb_context.GetCurrentAccessContext());
6988
6989 // Validate attachment operations
6990 if (attachments_.size() == 0) return skip;
6991 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07006992
6993 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
6994 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
6995 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
6996 // operations (though it's currently a messy approach)
6997 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09006998 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006999
7000 // Validate load operations if there were no layout transition hazards
7001 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007002 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007003 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007004 }
7005
7006 return skip;
7007}
7008
John Zulaufdab327f2022-07-08 12:02:05 -06007009ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) {
John Zulauf64ffe552021-02-06 10:25:07 -07007010 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007011 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
John Zulaufdab327f2022-07-08 12:02:05 -06007012 const ResourceUsageTag begin_tag =
7013 cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
7014
7015 // Note: this state update must be after RecordBeginRenderPass as there is no current render pass until that function runs
7016 rp_context_ = cb_context->GetCurrentRenderPassContext();
7017
7018 return begin_tag;
John Zulauf64ffe552021-02-06 10:25:07 -07007019}
7020
John Zulauf8eda1562021-04-13 17:06:41 -06007021bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007022 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007023 return false;
7024}
7025
John Zulaufdab327f2022-07-08 12:02:05 -06007026void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7027 // Need to update the exec_contexts state (which for RenderPass operations *must* be a QueueBatchContext, as
7028 // render pass operations are not allowed in secondary command buffers.
7029 const QueueId queue_id = exec_context.GetQueueId();
7030 assert(queue_id != QueueSyncState::kQueueIdInvalid); // Renderpass replay only valid at submit (not exec) time
7031 if (queue_id == QueueSyncState::kQueueIdInvalid) return;
7032
7033 exec_context.BeginRenderPassReplay(*this, tag);
7034}
John Zulauf8eda1562021-04-13 17:06:41 -06007035
sjfricke0bea06e2022-06-05 09:22:26 +09007036SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7037 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7038 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007039 if (pSubpassBeginInfo) {
7040 subpass_begin_info_.initialize(pSubpassBeginInfo);
7041 }
7042 if (pSubpassEndInfo) {
7043 subpass_end_info_.initialize(pSubpassEndInfo);
7044 }
7045}
7046
7047bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7048 bool skip = false;
7049 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7050 if (!renderpass_context) return skip;
7051
sjfricke0bea06e2022-06-05 09:22:26 +09007052 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007053 return skip;
7054}
7055
John Zulaufdab327f2022-07-08 12:02:05 -06007056ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007057 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007058}
7059
7060bool SyncOpNextSubpass::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;
John Zulauf64ffe552021-02-06 10:25:07 -07007063}
7064
sjfricke0bea06e2022-06-05 09:22:26 +09007065SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7066 const VkSubpassEndInfo *pSubpassEndInfo)
7067 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007068 if (pSubpassEndInfo) {
7069 subpass_end_info_.initialize(pSubpassEndInfo);
7070 }
7071}
7072
John Zulaufdab327f2022-07-08 12:02:05 -06007073void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7074 exec_context.NextSubpassReplay();
7075}
John Zulauf8eda1562021-04-13 17:06:41 -06007076
John Zulauf64ffe552021-02-06 10:25:07 -07007077bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7078 bool skip = false;
7079 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7080
7081 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007082 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007083 return skip;
7084}
7085
John Zulaufdab327f2022-07-08 12:02:05 -06007086ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007087 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007088}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007089
John Zulauf8eda1562021-04-13 17:06:41 -06007090bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007091 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007092 return false;
7093}
7094
John Zulaufdab327f2022-07-08 12:02:05 -06007095void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7096 exec_context.EndRenderPassReplay();
7097}
John Zulauf8eda1562021-04-13 17:06:41 -06007098
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007099void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7100 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7101 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7102 auto *cb_access_context = GetAccessContext(commandBuffer);
7103 assert(cb_access_context);
7104 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7105 auto *context = cb_access_context->GetCurrentAccessContext();
7106 assert(context);
7107
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007108 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007109
7110 if (dst_buffer) {
7111 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7112 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7113 }
7114}
John Zulaufd05c5842021-03-26 11:32:16 -06007115
John Zulaufae842002021-04-15 18:20:55 -06007116bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7117 const VkCommandBuffer *pCommandBuffers) const {
7118 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007119 const auto *cb_context = GetAccessContext(commandBuffer);
7120 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007121
7122 // Heavyweight, but we need a proxy copy of the active command buffer access context
7123 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007124
7125 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007126 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007127 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7128
John Zulaufae842002021-04-15 18:20:55 -06007129 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7130 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007131
7132 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7133 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007134 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007135
7136 // The barriers have already been applied in ValidatFirstUse
7137 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007138 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007139 }
7140
John Zulaufae842002021-04-15 18:20:55 -06007141 return skip;
7142}
7143
7144void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7145 const VkCommandBuffer *pCommandBuffers) {
7146 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007147 auto *cb_context = GetAccessContext(commandBuffer);
7148 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007149 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007150 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007151 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7152 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007153 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007154 }
John Zulaufae842002021-04-15 18:20:55 -06007155}
7156
John Zulauf1d5f9c12022-05-13 14:51:08 -06007157void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7158 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7159 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7160
7161 const auto queue_state = GetQueueSyncStateShared(queue);
7162 if (!queue_state) return; // Invalid queue
7163 QueueId waited_queue = queue_state->GetQueueId();
7164
7165 // We need to go through every queue batch context and clear all accesses this wait synchronizes
7166 // As usual -- two groups, the "last batch" and the signaled semaphores
7167 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
7168 // QueueBatchContext, track which we've done to avoid duplicate traversals
John Zulaufe0757ba2022-06-10 16:51:45 -06007169 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7170 for (auto &batch : queue_batch_contexts) {
7171 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007172 }
7173
John Zulaufe0757ba2022-06-10 16:51:45 -06007174 // TODO: Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007175}
7176
7177void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7178 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007179
7180 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7181 for (auto &batch : queue_batch_contexts) {
7182 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007183 }
7184
John Zulaufe0757ba2022-06-10 16:51:45 -06007185 // TODO: Update Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007186}
7187
John Zulauf697c0e12022-04-19 16:31:12 -06007188struct QueueSubmitCmdState {
7189 std::shared_ptr<const QueueSyncState> queue;
7190 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007191 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007192 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007193 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7194 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007195};
7196
7197template <>
7198thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7199
John Zulaufbbda4572022-04-19 16:20:45 -06007200bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7201 VkFence fence) const {
7202 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007203
7204 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007205 if (!enabled[sync_validation_queue_submit]) return skip;
7206
John Zulauf00119522022-05-23 19:07:42 -06007207 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007208 const auto fence_state = Get<FENCE_STATE>(fence);
7209 cmd_state->queue = GetQueueSyncStateShared(queue);
7210 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007211
John Zulauf697c0e12022-04-19 16:31:12 -06007212 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7213 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7214
7215 // verify each submit batch
7216 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7217 // most recently created batch
7218 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7219 std::shared_ptr<QueueBatchContext> batch;
7220 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7221 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007222 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7223 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007224
John Zulaufe0757ba2022-06-10 16:51:45 -06007225 // Skip import and validation of empty batches
7226 if (batch->GetTagRange().size()) {
7227 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007228
John Zulaufe0757ba2022-06-10 16:51:45 -06007229 // For each submit in the batch...
7230 for (const auto &cb : *batch) {
7231 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
John Zulauf0223f142022-07-06 09:05:39 -06007232 skip |= cb.cb->ValidateFirstUse(*batch.get(), "vkQueueSubmit", cb.index);
John Zulaufe0757ba2022-06-10 16:51:45 -06007233
7234 // The barriers have already been applied in ValidatFirstUse
7235 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7236 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7237 }
John Zulauf697c0e12022-04-19 16:31:12 -06007238 }
7239
John Zulaufe0757ba2022-06-10 16:51:45 -06007240 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007241 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7242 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007243 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007244 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007245 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7246 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7247 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007248 }
7249 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7250 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7251 last_batch = batch;
7252 }
7253 // The most recently created batch will become the queue's "last batch" in the record phase
7254 if (batch) {
7255 cmd_state->last_batch = std::move(batch);
7256 }
7257
7258 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007259 return skip;
7260}
7261
7262void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7263 VkResult result) {
7264 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007265
John Zulaufcb7e1672022-05-04 13:46:08 -06007266 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007267 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7268
John Zulaufcb7e1672022-05-04 13:46:08 -06007269 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7270 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007271 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007272
7273 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007274 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7275
John Zulauf697c0e12022-04-19 16:31:12 -06007276 // Don't need to look up the queue state again, but we need a non-const version
7277 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007278
John Zulaufcb7e1672022-05-04 13:46:08 -06007279 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7280 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7281 // QBC's are those referenced by unwaited signals and the last batch.
7282 for (auto &sig_sem : cmd_state->signaled) {
7283 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007284 auto &sig_batch = sig_sem.second->batch;
7285 sig_batch->ResetAccessLog();
7286 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7287 if (sig_batch != cmd_state->last_batch) {
7288 sig_batch->ResetEventsContext();
7289 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007290 }
7291 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007292 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007293 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007294
John Zulaufcb7e1672022-05-04 13:46:08 -06007295 // Update the queue to point to the last batch from the submit
7296 if (cmd_state->last_batch) {
7297 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007298
7299 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7300 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7301 auto last_batch = queue_state->LastBatch();
7302 if (last_batch) {
7303 last_batch->ResetEventsContext();
7304 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007305 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007306 }
7307
7308 // Update the global access log from the one built during validation
7309 global_access_log_.MergeMove(std::move(cmd_state->logger));
7310
John Zulauf697c0e12022-04-19 16:31:12 -06007311
7312 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007313}
7314
7315bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7316 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007317 bool skip = false;
7318 if (!enabled[sync_validation_queue_submit]) return skip;
7319
John Zulauf697c0e12022-04-19 16:31:12 -06007320 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007321 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007322}
7323
7324void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7325 VkFence fence, VkResult result) {
7326 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007327 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7328
7329 if (!enabled[sync_validation_queue_submit]) return;
7330
John Zulauf697c0e12022-04-19 16:31:12 -06007331 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007332}
7333
John Zulaufd0ec59f2021-03-13 14:25:08 -07007334AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7335 : view_(view), view_mask_(), gen_store_() {
7336 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7337 const IMAGE_STATE &image_state = *view_->image_state.get();
7338 const auto base_address = ResourceBaseAddress(image_state);
7339 const auto *encoder = image_state.fragment_encoder.get();
7340 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007341 // Get offset and extent for the view, accounting for possible depth slicing
7342 const VkOffset3D zero_offset = view->GetOffset();
7343 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007344 // Intentional copy
7345 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7346 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007347 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7348 view->IsDepthSliced());
7349 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007350
7351 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7352 if (depth && (depth != view_mask_)) {
7353 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007354 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007355 }
7356 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7357 if (stencil && (stencil != view_mask_)) {
7358 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007359 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7360 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007361 }
7362}
7363
7364const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7365 const ImageRangeGen *got = nullptr;
7366 switch (gen_type) {
7367 case kViewSubresource:
7368 got = &gen_store_[kViewSubresource];
7369 break;
7370 case kRenderArea:
7371 got = &gen_store_[kRenderArea];
7372 break;
7373 case kDepthOnlyRenderArea:
7374 got =
7375 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7376 break;
7377 case kStencilOnlyRenderArea:
7378 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7379 : &gen_store_[Gen::kStencilOnlyRenderArea];
7380 break;
7381 default:
7382 assert(got);
7383 }
7384 return got;
7385}
7386
7387AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7388 assert(IsValid());
7389 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7390 if (depth_op) {
7391 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7392 if (stencil_op) {
7393 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7394 return kRenderArea;
7395 }
7396 return kDepthOnlyRenderArea;
7397 }
7398 if (stencil_op) {
7399 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7400 return kStencilOnlyRenderArea;
7401 }
7402
7403 assert(depth_op || stencil_op);
7404 return kRenderArea;
7405}
7406
7407AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007408
John Zulaufe0757ba2022-06-10 16:51:45 -06007409void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007410 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7411 for (auto &event_pair : map_) {
7412 assert(event_pair.second); // Shouldn't be storing empty
7413 auto &sync_event = *event_pair.second;
7414 // 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 -06007415 // But only if occuring before the tag
7416 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007417 sync_event.barriers |= dst.exec_scope;
7418 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7419 }
7420 }
7421}
John Zulaufbb890452021-12-14 11:30:18 -07007422
John Zulaufe0757ba2022-06-10 16:51:45 -06007423void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7424 const SyncExecScope src_scope =
7425 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7426 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7427 ApplyBarrier(src_scope, dst_scope, tag);
7428}
7429
7430SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7431 // We need a deep copy of the const context to update during validation phase
7432 for (const auto &event : from.map_) {
7433 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7434 }
7435 return *this;
7436}
7437
John Zulaufcb7e1672022-05-04 13:46:08 -06007438QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
John Zulaufdab327f2022-07-08 12:02:05 -06007439 : CommandExecutionContext(&sync_state),
7440 queue_state_(&queue_state),
7441 tag_range_(0, 0),
7442 current_access_context_(&access_context_),
7443 batch_log_(nullptr) {}
John Zulaufcb7e1672022-05-04 13:46:08 -06007444
John Zulauf697c0e12022-04-19 16:31:12 -06007445template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007446void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7447 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007448 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007449 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007450}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007451void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007452 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007453}
John Zulauf697c0e12022-04-19 16:31:12 -06007454
7455VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7456
John Zulauf1d5f9c12022-05-13 14:51:08 -06007457void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7458 QueueWaitWorm wait_worm(queue_id);
7459 access_context_.ForAll(wait_worm);
7460 if (wait_worm.erase_all) {
7461 access_context_.Reset();
7462 } else {
7463 // TODO: Profiling will tell us if we need a more efficient clean up.
7464 for (const auto &address : wait_worm.erase_list) {
7465 access_context_.DeleteAccess(address);
7466 }
7467 }
John Zulaufe0757ba2022-06-10 16:51:45 -06007468
7469 if (queue_id == GetQueueId()) {
7470 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7471 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007472}
7473
7474// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007475void QueueBatchContext::ApplyDeviceWait() {
7476 access_context_.Reset();
7477 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7478}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007479
John Zulaufdab327f2022-07-08 12:02:05 -06007480HazardResult QueueBatchContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
7481 // Queue batch handling requires dealing with renderpass state and picking the correct access context
7482 if (rp_replay_) {
7483 return rp_replay_.replay_context->DetectFirstUseHazard(GetQueueId(), tag_range, *current_access_context_);
7484 }
7485 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, access_context_);
7486}
7487
7488void QueueBatchContext::BeginRenderPassReplay(const SyncOpBeginRenderPass &begin_op, const ResourceUsageTag tag) {
7489 current_access_context_ = rp_replay_.Begin(GetQueueFlags(), begin_op, access_context_);
7490 current_access_context_->ResolvePreviousAccesses();
7491}
7492
7493void QueueBatchContext::NextSubpassReplay() {
7494 current_access_context_ = rp_replay_.Next();
7495 current_access_context_->ResolvePreviousAccesses();
7496}
7497
7498void QueueBatchContext::EndRenderPassReplay() {
7499 rp_replay_.End(access_context_);
7500 current_access_context_ = &access_context_;
7501}
7502
7503AccessContext *QueueBatchContext::RenderPassReplayState::Begin(VkQueueFlags queue_flags, const SyncOpBeginRenderPass &begin_op_,
7504 const AccessContext &external_context) {
7505 Reset();
7506
7507 begin_op = &begin_op_;
7508 subpass = 0;
7509
7510 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7511 assert(rp_context);
7512 replay_context = &rp_context->GetContexts()[0];
7513
7514 InitSubpassContexts(queue_flags, *rp_context->GetRenderPassState(), &external_context, subpass_contexts);
7515 return &subpass_contexts[0];
7516}
7517
7518AccessContext *QueueBatchContext::RenderPassReplayState::Next() {
7519 subpass++;
7520
7521 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7522
7523 replay_context = &rp_context->GetContexts()[subpass];
7524 return &subpass_contexts[subpass];
7525}
7526
7527void QueueBatchContext::RenderPassReplayState::End(AccessContext &external_context) {
7528 external_context.ResolveChildContexts(subpass_contexts);
7529 Reset();
7530}
7531
John Zulaufecf4ac52022-06-06 10:08:42 -06007532class ApplySemaphoreBarrierAction {
7533 public:
7534 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7535 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7536
7537 private:
7538 const SemaphoreScope &signal_;
7539 const SemaphoreScope wait_;
7540};
7541
7542std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7543 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007544 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007545 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007546
John Zulaufcb7e1672022-05-04 13:46:08 -06007547 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7548 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007549 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007550
John Zulaufecf4ac52022-06-06 10:08:42 -06007551 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007552
John Zulaufecf4ac52022-06-06 10:08:42 -06007553 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007554 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007555 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7556 if (signal_scope.queue == wait_scope.queue) {
7557 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7558 // valid accesses for the sync scope.
7559 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7560 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7561 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007562 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007563 } else {
7564 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7565 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007566 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007567 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7568 // enforce deep constness.
7569 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007570}
7571
7572// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7573template <>
7574class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7575 public:
7576 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7577 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7578 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7579 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7580 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7581 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7582
7583 private:
7584 const VkSubmitInfo &info_;
7585};
7586template <typename BatchInfo, typename Fn>
7587void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7588 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7589 Accessor batch(batch_info);
7590 const uint32_t wait_count = batch.WaitSemaphoreCount();
7591 for (uint32_t i = 0; i < wait_count; ++i) {
7592 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7593 }
7594}
7595
7596template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007597void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7598 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007599 // Copy in the event state from the previous batch (on this queue)
7600 if (prev) {
7601 events_context_.DeepCopy(prev->events_context_);
7602 }
7603
John Zulaufecf4ac52022-06-06 10:08:42 -06007604 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7605 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7606 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7607 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7608 if (resolved) {
7609 batches_resolved.emplace(std::move(resolved));
7610 }
John Zulauf697c0e12022-04-19 16:31:12 -06007611 });
7612
John Zulaufecf4ac52022-06-06 10:08:42 -06007613 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7614 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7615 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007616 }
7617
John Zulauf697c0e12022-04-19 16:31:12 -06007618 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007619 async_batches_ =
7620 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7621 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007622 });
7623 for (const auto &async_batch : async_batches_) {
7624 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7625 }
7626}
7627
7628template <typename BatchInfo>
7629void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7630 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7631 Accessor batch(batch_info);
7632
7633 // Create the list of command buffers to submit
7634 const uint32_t cb_count = batch.CommandBufferCount();
7635 command_buffers_.reserve(cb_count);
7636 for (uint32_t index = 0; index < cb_count; ++index) {
7637 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7638 if (cb_context) {
7639 tag_range_.end += cb_context->GetTagLimit();
7640 command_buffers_.emplace_back(index, std::move(cb_context));
7641 }
7642 }
7643}
7644
7645// Look up the usage informaiton from the local or global logger
7646std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7647 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7648 std::stringstream out;
7649 AccessLogger::AccessRecord access = use_logger[tag];
7650 if (access.IsValid()) {
7651 const AccessLogger::BatchRecord &batch = *access.batch;
7652 const ResourceUsageRecord &record = *access.record;
7653 // Queue and Batch information
7654 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7655 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7656
7657 // Commandbuffer Usages Information
7658 out << record;
7659 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7660 out << ", reset_no: " << std::to_string(record.reset_count);
7661 }
7662 return out.str();
7663}
7664
7665VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7666
John Zulauf00119522022-05-23 19:07:42 -06007667QueueId QueueBatchContext::GetQueueId() const {
7668 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7669 return id;
7670}
7671
John Zulauf697c0e12022-04-19 16:31:12 -06007672void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7673 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7674 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7675 SetTagBias(global_tags.begin);
7676 // Add an access log for the batches range and point the batch at it.
7677 logger_ = &logger;
7678 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7679}
7680
7681void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7682 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7683 batch_log_->Append(submitted_cb.GetAccessLog());
7684}
7685
7686void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7687 const auto size = tag_range_.size();
7688 tag_range_.begin = bias;
7689 tag_range_.end = bias + size;
7690 access_context_.SetStartTag(bias);
7691}
7692
John Zulauf1d5f9c12022-05-13 14:51:08 -06007693QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7694
7695void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7696 bool erased = access.second.ApplyQueueTagWait(predicate);
7697 if (erased) {
7698 erase_list.emplace_back(address_type, access.first);
7699 } else {
7700 erase_all = false;
7701 }
7702}
7703
John Zulauf697c0e12022-04-19 16:31:12 -06007704AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7705 const ResourceUsageRange &range) {
7706 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7707 assert(inserted.second);
7708 return &inserted.first->second;
7709}
7710
7711void AccessLogger::MergeMove(AccessLogger &&child) {
7712 for (auto &range : child.access_log_map_) {
7713 BatchLog &child_batch = range.second;
7714 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7715 insert_pair.first->second = std::move(child_batch);
7716 assert(insert_pair.second);
7717 }
7718 child.Reset();
7719}
7720
7721void AccessLogger::Reset() {
7722 prev_ = nullptr;
7723 access_log_map_.clear();
7724}
7725
7726// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7727// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7728// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7729// the contexts Resolve all history from previous all contexts when created
7730void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7731 last_batch_ = std::move(last);
7732 last_batch_->ResetAccessLog();
7733}
7734
7735// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7736// scope state.
7737// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7738// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7739uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7740
7741void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7742 log_.insert(log_.end(), other.cbegin(), other.cend());
7743 for (const auto &record : other) {
7744 assert(record.cb_state);
7745 cbs_referenced_.insert(record.cb_state->shared_from_this());
7746 }
7747}
7748
7749AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7750 assert(index < log_.size());
7751 return AccessRecord{&batch_, &log_[index]};
7752}
7753
7754AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7755 AccessRecord access_record = {nullptr, nullptr};
7756
7757 auto found_range = access_log_map_.find(tag);
7758 if (found_range != access_log_map_.cend()) {
7759 const ResourceUsageTag bias = found_range->first.begin;
7760 assert(tag >= bias);
7761 access_record = found_range->second[tag - bias];
7762 } else if (prev_) {
7763 access_record = (*prev_)[tag];
7764 }
7765
7766 return access_record;
7767}
John Zulaufcb7e1672022-05-04 13:46:08 -06007768
John Zulaufecf4ac52022-06-06 10:08:42 -06007769// This is a const method, force the returned value to be const
7770std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007771 std::shared_ptr<Signal> prev_state;
7772 if (prev_) {
7773 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7774 }
7775 return prev_state;
7776}
John Zulaufecf4ac52022-06-06 10:08:42 -06007777
7778SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7779 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7780 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7781 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7782 assert(batch);
7783 assert(sem_state);
7784}