blob: e9b29ab14fc8815e53f31257e5d67b997a1890a2 [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:
John Zulauf451e8c22022-09-01 14:14:00 -060091 return "SYNC-HAZARD-READ-AFTER-WRITE";
John Zulauf9cb530d2019-09-30 14:14:10 -060092 break;
93 case SyncHazard::WRITE_AFTER_READ:
John Zulauf451e8c22022-09-01 14:14:00 -060094 return "SYNC-HAZARD-WRITE-AFTER-READ";
John Zulauf9cb530d2019-09-30 14:14:10 -060095 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
John Zulauf451e8c22022-09-01 14:14:00 -060097 return "SYNC-HAZARD-WRITE-AFTER-WRITE";
John Zulauf9cb530d2019-09-30 14:14:10 -060098 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) {
John Zulauf3298da92022-09-01 13:58:39 -0600235 out << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
John Zulauf397e68b2022-04-19 11:44:07 -0600236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
John Zulauf3298da92022-09-01 13:58:39 -0600240 out << formater.label << ": null handle";
John Zulauf397e68b2022-04-19 11:44:07 -0600241 }
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) {
John Zulauf3298da92022-09-01 13:58:39 -0600320 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 Zulauff26fca92022-08-15 11:53:34 -0600863template <typename Action>
864void AccessContext::ConstForAll(Action &&action) const {
865 for (const auto address_type : kAddressTypes) {
866 auto &accesses = GetAccessStateMap(address_type);
867 for (auto &access : accesses) {
868 action(address_type, access);
869 }
870 }
871}
872
John Zulauf3da08bb2022-08-01 17:56:56 -0600873template <typename Predicate>
874void AccessContext::EraseIf(Predicate &&pred) {
875 for (const auto address_type : kAddressTypes) {
876 auto &accesses = GetAccessStateMap(address_type);
877 // Note: Don't forward, we don't want r-values moved, since we're going to make multiple calls.
878 layer_data::EraseIf(accesses, pred);
879 }
880}
881
John Zulauf3d84f1b2020-03-09 13:33:25 -0600882// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
883// the DAG of the contexts (for example subpasses)
884template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600885HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600886 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600887 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600888
John Zulauf1a224292020-06-30 14:52:13 -0600889 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600890 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
891 // so we'll check these first
892 for (const auto &async_context : async_) {
893 hazard = async_context->DetectAsyncHazard(type, detector, range);
894 if (hazard.hazard) return hazard;
895 }
John Zulauf5f13a792020-03-10 07:31:21 -0600896 }
897
John Zulauf1a224292020-06-30 14:52:13 -0600898 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600899
John Zulauf69133422020-05-20 14:55:53 -0600900 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600901 const auto the_end = accesses.cend(); // End is not invalidated
902 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600903 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600904
John Zulauf3cafbf72021-03-26 16:55:19 -0600905 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600906 // Cover any leading gap, or gap between entries
907 if (detect_prev) {
908 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
909 // Cover any leading gap, or gap between entries
910 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600911 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600912 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600913 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600914 if (hazard.hazard) return hazard;
915 }
John Zulauf69133422020-05-20 14:55:53 -0600916 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
917 gap.begin = pos->first.end;
918 }
919
920 hazard = detector.Detect(pos);
921 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600922 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600923 }
924
925 if (detect_prev) {
926 // Detect in the trailing empty as needed
927 gap.end = range.end;
928 if (gap.non_empty()) {
929 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600930 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600931 }
932
933 return hazard;
934}
935
936// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
937template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700938HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
939 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600940 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600941 auto pos = accesses.lower_bound(range);
942 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600943
John Zulauf3d84f1b2020-03-09 13:33:25 -0600944 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600945 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700946 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600947 if (hazard.hazard) break;
948 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600949 }
John Zulauf16adfc92020-04-08 10:28:33 -0600950
John Zulauf3d84f1b2020-03-09 13:33:25 -0600951 return hazard;
952}
953
John Zulaufb02c1eb2020-10-06 16:33:36 -0600954struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700955 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600956 void operator()(ResourceAccessState *access) const {
957 assert(access);
958 access->ApplyBarriers(barriers, true);
959 }
960 const std::vector<SyncBarrier> &barriers;
961};
962
John Zulaufe0757ba2022-06-10 16:51:45 -0600963struct QueueTagOffsetBarrierAction {
964 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
965 void operator()(ResourceAccessState *access) const {
966 access->OffsetTag(tag_offset);
967 access->SetQueueId(queue_id);
968 };
969 QueueId queue_id;
970 ResourceUsageTag tag_offset;
971};
972
John Zulauf22aefed2021-03-11 18:14:35 -0700973struct ApplyTrackbackStackAction {
974 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
975 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
976 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977 void operator()(ResourceAccessState *access) const {
978 assert(access);
979 assert(!access->HasPendingState());
980 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600981 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
982 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700983 if (previous_barrier) {
984 assert(bool(*previous_barrier));
985 (*previous_barrier)(access);
986 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600987 }
988 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700989 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600990};
991
992// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
993// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
994// *different* map from dest.
995// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
996// range [first, last)
997template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600998static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
999 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -06001000 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -06001001 auto at = entry;
1002 for (auto pos = first; pos != last; ++pos) {
1003 // Every member of the input iterator range must fit within the remaining portion of entry
1004 assert(at->first.includes(pos->first));
1005 assert(at != dest->end());
1006 // Trim up at to the same size as the entry to resolve
1007 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001008 auto access = pos->second; // intentional copy
1009 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -06001010 at->second.Resolve(access);
1011 ++at; // Go to the remaining unused section of entry
1012 }
1013}
1014
John Zulaufa0a98292020-09-18 09:30:10 -06001015static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
1016 SyncBarrier merged = {};
1017 for (const auto &barrier : barriers) {
1018 merged.Merge(barrier);
1019 }
1020 return merged;
1021}
John Zulaufb02c1eb2020-10-06 16:33:36 -06001022template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -07001023void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -06001024 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
1025 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001026 if (!range.non_empty()) return;
1027
John Zulauf355e49b2020-04-24 15:11:15 -06001028 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
1029 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001030 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001031 if (current->pos_B->valid) {
1032 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001033 auto access = src_pos->second; // intentional copy
1034 barrier_action(&access);
John Zulauf16adfc92020-04-08 10:28:33 -06001035 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001036 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1037 trimmed->second.Resolve(access);
1038 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001039 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001040 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001041 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001042 }
John Zulauf16adfc92020-04-08 10:28:33 -06001043 } else {
1044 // we have to descend to fill this gap
1045 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001046 ResourceAccessRange recurrence_range = current_range;
1047 // The current context is empty for the current range, so recur to fill the gap.
1048 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1049 // is not valid, to minimize that recurrence
1050 if (current->pos_B.at_end()) {
1051 // Do the remainder here....
1052 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001053 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001054 // Recur only over the range until B becomes valid (within the limits of range).
1055 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001056 }
John Zulauf22aefed2021-03-11 18:14:35 -07001057 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1058
John Zulauf355e49b2020-04-24 15:11:15 -06001059 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1060 // iterator of the outer while.
1061
1062 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1063 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1064 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001065 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 -06001066 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001067 current.seek(seek_to);
1068 } else if (!current->pos_A->valid && infill_state) {
1069 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1070 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1071 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001072 }
John Zulauf5f13a792020-03-10 07:31:21 -06001073 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001074 if (current->range.non_empty()) {
1075 ++current;
1076 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001077 }
John Zulauf1a224292020-06-30 14:52:13 -06001078
1079 // Infill if range goes passed both the current and resolve map prior contents
1080 if (recur_to_infill && (current->range.end < range.end)) {
1081 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001082 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001083 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001084}
1085
John Zulauf22aefed2021-03-11 18:14:35 -07001086template <typename BarrierAction>
1087void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1088 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1089 const BarrierAction &previous_barrier) const {
1090 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1091 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1092}
1093
John Zulauf43cc7462020-12-03 12:33:12 -07001094void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001095 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1096 const ResourceAccessStateFunction *previous_barrier) const {
1097 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001098 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001099 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1100 ResourceAccessState state_copy;
1101 if (previous_barrier) {
1102 assert(bool(*previous_barrier));
1103 state_copy = *infill_state;
1104 (*previous_barrier)(&state_copy);
1105 infill_state = &state_copy;
1106 }
1107 sparse_container::update_range_value(*descent_map, range, *infill_state,
1108 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001109 }
1110 } else {
1111 // Look for something to fill the gap further along.
1112 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001113 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001114 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001115 }
John Zulauf5f13a792020-03-10 07:31:21 -06001116 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001117}
1118
John Zulauf4a6105a2020-11-17 15:11:05 -07001119// Non-lazy import of all accesses, WaitEvents needs this.
1120void AccessContext::ResolvePreviousAccesses() {
1121 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001122 if (!prev_.size()) return; // If no previous contexts, nothing to do
1123
John Zulauf4a6105a2020-11-17 15:11:05 -07001124 for (const auto address_type : kAddressTypes) {
1125 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1126 }
1127}
1128
John Zulauf43cc7462020-12-03 12:33:12 -07001129AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1130 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001131}
1132
John Zulauf1507ee42020-05-18 11:33:09 -06001133static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001134 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1135 ? SYNC_ACCESS_INDEX_NONE
1136 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1137 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001138 return stage_access;
1139}
1140static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001141 const auto stage_access =
1142 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1143 ? SYNC_ACCESS_INDEX_NONE
1144 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1145 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001146 return stage_access;
1147}
1148
John Zulauf7635de32020-05-29 17:14:15 -06001149// Caller must manage returned pointer
1150static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001151 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001152 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001153 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1154 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001155 return proxy;
1156}
1157
John Zulaufb02c1eb2020-10-06 16:33:36 -06001158template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001159void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1160 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1161 const ResourceAccessState *infill_state) const {
1162 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1163 if (!attachment_gen) return;
1164
1165 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1166 const AccessAddressType address_type = view_gen.GetAddressType();
1167 for (; range_gen->non_empty(); ++range_gen) {
1168 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001169 }
John Zulauf62f10592020-04-03 12:20:02 -06001170}
1171
John Zulauf1d5f9c12022-05-13 14:51:08 -06001172template <typename ResolveOp>
1173void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1174 const ResourceAccessState *infill_state, bool recur_to_infill) {
1175 for (auto address_type : kAddressTypes) {
1176 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1177 recur_to_infill);
1178 }
1179}
1180
John Zulauf7635de32020-05-29 17:14:15 -06001181// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001182bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001183 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001184 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001185 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001186 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1187 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1188 // those affects have not been recorded yet.
1189 //
1190 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1191 // to apply and only copy then, if this proves a hot spot.
1192 std::unique_ptr<AccessContext> proxy_for_prev;
1193 TrackBack proxy_track_back;
1194
John Zulauf355e49b2020-04-24 15:11:15 -06001195 const auto &transitions = rp_state.subpass_transitions[subpass];
1196 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001197 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1198
1199 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001200 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001201 if (prev_needs_proxy) {
1202 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001203 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001204 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001205 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001206 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001207 }
1208 track_back = &proxy_track_back;
1209 }
1210 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001211 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001212 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001213 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001214 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001215 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1216 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1217 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1218 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1219 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1220 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001221 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001222 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1223 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1224 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1225 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1226 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001227 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001228 }
John Zulauf355e49b2020-04-24 15:11:15 -06001229 }
1230 }
1231 return skip;
1232}
1233
John Zulaufbb890452021-12-14 11:30:18 -07001234bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001235 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001236 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001237 bool skip = false;
1238 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001239
John Zulauf1507ee42020-05-18 11:33:09 -06001240 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1241 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001242 const auto &view_gen = attachment_views[i];
1243 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001244 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001245
1246 // Need check in the following way
1247 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1248 // vs. transition
1249 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1250 // for each aspect loaded.
1251
1252 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001253 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001254 const bool is_color = !(has_depth || has_stencil);
1255
1256 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001257 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001258
John Zulaufaff20662020-06-01 14:07:58 -06001259 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001260 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001261
John Zulaufb02c1eb2020-10-06 16:33:36 -06001262 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001263 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001264 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001265 aspect = "color";
1266 } else {
John Zulauf57261402021-08-13 11:32:06 -06001267 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001268 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1269 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001270 aspect = "depth";
1271 }
John Zulauf57261402021-08-13 11:32:06 -06001272 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001273 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1274 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001275 aspect = "stencil";
1276 checked_stencil = true;
1277 }
1278 }
1279
1280 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001281 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001282 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001283 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001284 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001285 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001286 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001287 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1288 " aspect %s during load with loadOp %s.",
1289 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1290 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001291 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001292 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001293 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001294 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001295 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001296 }
1297 }
1298 }
1299 }
1300 return skip;
1301}
1302
John Zulaufaff20662020-06-01 14:07:58 -06001303// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1304// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1305// store is part of the same Next/End operation.
1306// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001307bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001308 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001309 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001310 bool skip = false;
1311 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001312
1313 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1314 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001315 const AttachmentViewGen &view_gen = attachment_views[i];
1316 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001317 const auto &ci = attachment_ci[i];
1318
1319 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1320 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1321 // sake, we treat DONT_CARE as writing.
1322 const bool has_depth = FormatHasDepth(ci.format);
1323 const bool has_stencil = FormatHasStencil(ci.format);
1324 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001325 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001326 if (!has_stencil && !store_op_stores) continue;
1327
1328 HazardResult hazard;
1329 const char *aspect = nullptr;
1330 bool checked_stencil = false;
1331 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001332 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1333 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001334 aspect = "color";
1335 } else {
John Zulauf57261402021-08-13 11:32:06 -06001336 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001337 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001338 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1339 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001340 aspect = "depth";
1341 }
1342 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001343 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1344 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001345 aspect = "stencil";
1346 checked_stencil = true;
1347 }
1348 }
1349
1350 if (hazard.hazard) {
1351 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1352 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001353 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1354 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1355 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001356 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1357 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001358 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001359 }
1360 }
1361 }
1362 return skip;
1363}
1364
John Zulaufbb890452021-12-14 11:30:18 -07001365bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001366 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001367 CMD_TYPE cmd_type, uint32_t subpass) const {
1368 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001369 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001370 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001371}
1372
John Zulauf06f6f1e2022-04-19 15:28:11 -06001373void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1374
John Zulauf3d84f1b2020-03-09 13:33:25 -06001375class HazardDetector {
1376 SyncStageAccessIndex usage_index_;
1377
1378 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001379 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001380 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001381 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001382 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001383 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001384};
1385
John Zulauf69133422020-05-20 14:55:53 -06001386class HazardDetectorWithOrdering {
1387 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001388 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001389
1390 public:
1391 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001392 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001393 }
John Zulauf14940722021-04-12 15:19:02 -06001394 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001395 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001396 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001397 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001398};
1399
John Zulauf16adfc92020-04-08 10:28:33 -06001400HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001401 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001402 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001403 const auto base_address = ResourceBaseAddress(buffer);
1404 HazardDetector detector(usage_index);
1405 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001406}
1407
John Zulauf69133422020-05-20 14:55:53 -06001408template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001409HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1410 DetectOptions options) const {
1411 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1412 if (!attachment_gen) return HazardResult();
1413
1414 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1415 const auto address_type = view_gen.GetAddressType();
1416 for (; range_gen->non_empty(); ++range_gen) {
1417 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1418 if (hazard.hazard) return hazard;
1419 }
1420
1421 return HazardResult();
1422}
1423
1424template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001425HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1426 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001427 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001428 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001429 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001430 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001431 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001432 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001433 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001434 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001435 if (hazard.hazard) return hazard;
1436 }
1437 return HazardResult();
1438}
John Zulauf110413c2021-03-20 05:38:38 -06001439template <typename Detector>
1440HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001441 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1442 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001443 if (!SimpleBinding(image)) return HazardResult();
1444 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001445 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1446 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001447 const auto address_type = ImageAddressType(image);
1448 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001449 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1450 if (hazard.hazard) return hazard;
1451 }
1452 return HazardResult();
1453}
John Zulauf69133422020-05-20 14:55:53 -06001454
John Zulauf540266b2020-04-06 18:54:53 -06001455HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1456 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001457 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001458 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1459 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001460 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001461 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001462}
1463
1464HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001465 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001466 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001467 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001468}
1469
John Zulaufd0ec59f2021-03-13 14:25:08 -07001470HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1471 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1472 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1473 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1474}
1475
John Zulauf69133422020-05-20 14:55:53 -06001476HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001477 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001478 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001479 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001480 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001481}
1482
John Zulauf3d84f1b2020-03-09 13:33:25 -06001483class BarrierHazardDetector {
1484 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001485 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001486 SyncStageAccessFlags src_access_scope)
1487 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1488
John Zulauf5f13a792020-03-10 07:31:21 -06001489 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001490 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001491 }
John Zulauf14940722021-04-12 15:19:02 -06001492 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001493 // 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 -07001494 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001495 }
1496
1497 private:
1498 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001499 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001500 SyncStageAccessFlags src_access_scope_;
1501};
1502
John Zulauf4a6105a2020-11-17 15:11:05 -07001503class EventBarrierHazardDetector {
1504 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001505 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001506 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001507 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001508 : usage_index_(usage_index),
1509 src_exec_scope_(src_exec_scope),
1510 src_access_scope_(src_access_scope),
1511 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001512 scope_queue_id_(queue_id),
1513 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001514 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001515 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001516
John Zulaufe0757ba2022-06-10 16:51:45 -06001517 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1518 // Need to piece together coverage of pos->first range:
1519 // Copy the range as we'll be chopping it up as needed
1520 ResourceAccessRange range = pos->first;
1521 const ResourceAccessState &access = pos->second;
1522 HazardResult hazard;
1523
1524 bool in_scope = AdvanceScope(range);
1525 bool unscoped_tested = false;
1526 while (in_scope && !hazard.IsHazard()) {
1527 if (range.begin < ScopeBegin()) {
1528 if (!unscoped_tested) {
1529 unscoped_tested = true;
1530 hazard = access.DetectHazard(usage_index_);
1531 }
1532 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1533 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1534 range.begin = ScopeBegin();
1535 } else { // in_scope implied that ScopeRange and range intersect
1536 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1537 scope_tag_);
1538 if (!hazard.IsHazard()) {
1539 range.begin = ScopeEnd();
1540 in_scope = AdvanceScope(range); // contains a non_empty check
1541 }
1542 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001543 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001544 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1545 hazard = access.DetectHazard(usage_index_);
1546 }
1547 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001548 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001549
John Zulauf14940722021-04-12 15:19:02 -06001550 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001551 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1552 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1553 }
1554
1555 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001556 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1557 bool ScopeValid() const { return !ScopeInvalid(); }
1558 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1559
1560 // Hiding away the std::pair grunge...
1561 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1562 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1563 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1564 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1565
1566 bool AdvanceScope(const ResourceAccessRange &range) {
1567 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1568 if (!range.non_empty()) return false;
1569 if (ScopeInvalid()) return false;
1570
1571 if (ScopeRange().strictly_less(range)) {
1572 ScopeSeek(range);
1573 }
1574
1575 return ScopeValid() && ScopeRange().intersects(range);
1576 }
1577
John Zulauf4a6105a2020-11-17 15:11:05 -07001578 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001579 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001580 SyncStageAccessFlags src_access_scope_;
1581 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001582 QueueId scope_queue_id_;
1583 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001584 SyncEventState::ScopeMap::const_iterator scope_pos_;
1585 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001586};
1587
John Zulaufe0757ba2022-06-10 16:51:45 -06001588HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1589 VkPipelineStageFlags2KHR src_exec_scope,
1590 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1591 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001592 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1593 // first access scope map to use, and there's no easy way to plumb it in below.
1594 const auto address_type = ImageAddressType(image);
1595 const auto &event_scope = sync_event.FirstScope(address_type);
1596
1597 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001598 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001599 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001600}
1601
John Zulaufd0ec59f2021-03-13 14:25:08 -07001602HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1603 DetectOptions options) const {
1604 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1605 barrier.src_access_scope);
1606 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1607}
1608
Jeremy Gebben40a22942020-12-22 14:22:06 -07001609HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001610 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001611 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001612 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001613 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001614 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001615}
1616
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001617HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001618 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001619 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001620}
John Zulauf355e49b2020-04-24 15:11:15 -06001621
John Zulauf9cb530d2019-09-30 14:14:10 -06001622template <typename Flags, typename Map>
1623SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1624 SyncStageAccessFlags scope = 0;
1625 for (const auto &bit_scope : map) {
1626 if (flag_mask < bit_scope.first) break;
1627
1628 if (flag_mask & bit_scope.first) {
1629 scope |= bit_scope.second;
1630 }
1631 }
1632 return scope;
1633}
1634
Jeremy Gebben40a22942020-12-22 14:22:06 -07001635SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001636 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1637}
1638
Jeremy Gebben40a22942020-12-22 14:22:06 -07001639SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1640 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001641}
1642
Jeremy Gebben40a22942020-12-22 14:22:06 -07001643// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1644SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001645 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1646 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1647 // 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 -06001648 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1649}
1650
1651template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001652void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001653 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1654 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001655 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001656 auto pos = accesses->lower_bound(range);
1657 if (pos == accesses->end() || !pos->first.intersects(range)) {
1658 // The range is empty, fill it with a default value.
1659 pos = action.Infill(accesses, pos, range);
1660 } else if (range.begin < pos->first.begin) {
1661 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001662 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001663 } else if (pos->first.begin < range.begin) {
1664 // Trim the beginning if needed
1665 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1666 ++pos;
1667 }
1668
1669 const auto the_end = accesses->end();
1670 while ((pos != the_end) && pos->first.intersects(range)) {
1671 if (pos->first.end > range.end) {
1672 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1673 }
1674
1675 pos = action(accesses, pos);
1676 if (pos == the_end) break;
1677
1678 auto next = pos;
1679 ++next;
1680 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1681 // Need to infill if next is disjoint
1682 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001683 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001684 next = action.Infill(accesses, next, new_range);
1685 }
1686 pos = next;
1687 }
1688}
John Zulaufd5115702021-01-18 12:34:33 -07001689
1690// Give a comparable interface for range generators and ranges
1691template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001692void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001693 assert(range);
1694 UpdateMemoryAccessState(accesses, *range, action);
1695}
1696
John Zulauf4a6105a2020-11-17 15:11:05 -07001697template <typename Action, typename RangeGen>
1698void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1699 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001700 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 -07001701 for (; range_gen->non_empty(); ++range_gen) {
1702 UpdateMemoryAccessState(accesses, *range_gen, action);
1703 }
1704}
John Zulauf9cb530d2019-09-30 14:14:10 -06001705
John Zulaufd0ec59f2021-03-13 14:25:08 -07001706template <typename Action, typename RangeGen>
1707void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1708 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1709 for (; range_gen->non_empty(); ++range_gen) {
1710 UpdateMemoryAccessState(accesses, *range_gen, action);
1711 }
1712}
John Zulauf9cb530d2019-09-30 14:14:10 -06001713struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001714 using Iterator = ResourceAccessRangeMap::iterator;
1715 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001716 // this is only called on gaps, and never returns a gap.
1717 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001718 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001719 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001720 }
John Zulauf5f13a792020-03-10 07:31:21 -06001721
John Zulauf5c5e88d2019-12-26 11:22:02 -07001722 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001723 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001724 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001725 return pos;
1726 }
1727
John Zulauf43cc7462020-12-03 12:33:12 -07001728 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001729 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001730 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001731 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001732 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001733 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001734 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001735 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001736};
1737
John Zulauf4a6105a2020-11-17 15:11:05 -07001738// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001739struct PipelineBarrierOp {
1740 SyncBarrier barrier;
1741 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001742 ResourceAccessState::QueueScopeOps scope;
1743 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
John Zulauff26fca92022-08-15 11:53:34 -06001744 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {
1745 if (queue_id != QueueSyncState::kQueueIdInvalid) {
1746 // This is a submit time application... supress layout transitions to not taint the QueueBatchContext write state
1747 layout_transition = false;
1748 }
1749 }
John Zulaufd5115702021-01-18 12:34:33 -07001750 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001751 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001752};
John Zulauf00119522022-05-23 19:07:42 -06001753
John Zulaufecf4ac52022-06-06 10:08:42 -06001754// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1755struct BatchBarrierOp : public PipelineBarrierOp {
1756 void operator()(ResourceAccessState *access_state) const {
1757 access_state->ApplyBarrier(scope, barrier, layout_transition);
1758 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1759 }
1760 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1761};
1762
John Zulauf4a6105a2020-11-17 15:11:05 -07001763// The barrier operation for wait events
1764struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001765 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001766 SyncBarrier barrier;
1767 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001768
1769 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001770 bool layout_transition_)
John Zulauff26fca92022-08-15 11:53:34 -06001771 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {
1772 if (scope_queue_ != QueueSyncState::kQueueIdInvalid) {
1773 // This is a submit time application... supress layout transitions to not taint the QueueBatchContext write state
1774 layout_transition = false;
1775 }
1776 }
John Zulaufb7578302022-05-19 13:50:18 -06001777 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001778};
John Zulauf1e331ec2020-12-04 18:29:38 -07001779
John Zulauf4a6105a2020-11-17 15:11:05 -07001780// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1781// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1782// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001783template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001784class ApplyBarrierOpsFunctor {
1785 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001786 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001787 // Only called with a gap, and pos at the lower_bound(range)
1788 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1789 if (!infill_default_) {
1790 return pos;
1791 }
1792 ResourceAccessState default_state;
1793 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1794 return inserted;
1795 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001796
John Zulauf5c628d02021-05-04 15:46:36 -06001797 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001798 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001799 for (const auto &op : barrier_ops_) {
1800 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001801 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001802
John Zulauf89311b42020-09-29 16:28:47 -06001803 if (resolve_) {
1804 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1805 // another walk
1806 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001807 }
1808 return pos;
1809 }
1810
John Zulauf89311b42020-09-29 16:28:47 -06001811 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001812 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1813 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001814 barrier_ops_.reserve(size_hint);
1815 }
John Zulauf5c628d02021-05-04 15:46:36 -06001816 void EmplaceBack(const BarrierOp &op) {
1817 barrier_ops_.emplace_back(op);
1818 infill_default_ |= op.layout_transition;
1819 }
John Zulauf89311b42020-09-29 16:28:47 -06001820
1821 private:
1822 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001823 bool infill_default_;
1824 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001825 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001826};
1827
John Zulauf4a6105a2020-11-17 15:11:05 -07001828// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1829// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1830template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001831class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1832 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1833
John Zulauf4a6105a2020-11-17 15:11:05 -07001834 public:
John Zulaufee984022022-04-13 16:39:50 -06001835 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001836};
1837
John Zulauf1e331ec2020-12-04 18:29:38 -07001838// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001839class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1840 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1841
John Zulauf1e331ec2020-12-04 18:29:38 -07001842 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001843 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001844};
1845
John Zulauf8e3c3e92021-01-06 11:19:36 -07001846void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001847 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001848 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001849 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001850}
1851
John Zulauf8e3c3e92021-01-06 11:19:36 -07001852void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001853 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001854 if (!SimpleBinding(buffer)) return;
1855 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001856 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001857}
John Zulauf355e49b2020-04-24 15:11:15 -06001858
John Zulauf8e3c3e92021-01-06 11:19:36 -07001859void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001860 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1861 if (!SimpleBinding(image)) return;
1862 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001863 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001864 const auto address_type = ImageAddressType(image);
1865 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1866 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1867}
1868void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001869 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001870 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001871 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001872 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001873 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001874 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001875 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001876 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001877 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001878}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001879
1880void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001881 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001882 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1883 if (!gen) return;
1884 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1885 const auto address_type = view_gen.GetAddressType();
1886 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1887 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001888}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001889
John Zulauf8e3c3e92021-01-06 11:19:36 -07001890void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001891 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001892 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001893 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1894 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001895 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001896}
1897
John Zulaufd0ec59f2021-03-13 14:25:08 -07001898template <typename Action, typename RangeGen>
1899void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1900 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1901 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001902}
1903
1904template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001905void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1906 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1907 if (!gen) return;
1908 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001909}
1910
John Zulaufd0ec59f2021-03-13 14:25:08 -07001911void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1912 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001913 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001914 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001915 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001916}
1917
John Zulaufd0ec59f2021-03-13 14:25:08 -07001918void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001919 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001920 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001921
1922 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1923 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001924 const auto &view_gen = attachment_views[i];
1925 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001926
1927 const auto &ci = attachment_ci[i];
1928 const bool has_depth = FormatHasDepth(ci.format);
1929 const bool has_stencil = FormatHasStencil(ci.format);
1930 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001931 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001932
1933 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001934 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1935 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001936 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001937 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001938 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1939 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001940 }
John Zulauf57261402021-08-13 11:32:06 -06001941 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001942 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001943 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1944 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001945 }
1946 }
1947 }
1948 }
1949}
1950
John Zulauf540266b2020-04-06 18:54:53 -06001951template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001952void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001953 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001954 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001955 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001956 }
1957}
1958
1959void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001960 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1961 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001962 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001963 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001964 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001965 }
1966 }
1967}
1968
John Zulauf4fa68462021-04-26 21:04:22 -06001969// Caller must ensure that lifespan of this is less than from
1970void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1971
John Zulauf355e49b2020-04-24 15:11:15 -06001972// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001973HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1974 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001975
John Zulauf355e49b2020-04-24 15:11:15 -06001976 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001977 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001978
1979 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001980 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1981 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001982 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001983 if (!hazard.hazard) {
1984 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001985 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001986 }
John Zulaufa0a98292020-09-18 09:30:10 -06001987
John Zulauf355e49b2020-04-24 15:11:15 -06001988 return hazard;
1989}
1990
John Zulaufb02c1eb2020-10-06 16:33:36 -06001991void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001992 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001993 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001994 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001995 for (const auto &transition : transitions) {
1996 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001997 const auto &view_gen = attachment_views[transition.attachment];
1998 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001999
2000 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
2001 assert(trackback);
2002
2003 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07002004 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002005 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002006 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06002007 auto &target_map = GetAccessStateMap(address_type);
2008 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002009 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
2010 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002011 }
2012
John Zulauf86356ca2020-10-19 11:46:41 -06002013 // If there were no transitions skip this global map walk
2014 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07002015 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07002016 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06002017 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002018}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002019
sjfricke0bea06e2022-06-05 09:22:26 +09002020bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002021 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002022 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002023 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002024 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002025 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002026 return skip;
2027 }
sjfricke0bea06e2022-06-05 09:22:26 +09002028 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002029
2030 using DescriptorClass = cvdescriptorset::DescriptorClass;
2031 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2032 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002033 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2034
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002035 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002036 const auto raster_state = pipe->RasterizationState();
2037 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002038 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002039 }
locke-lunarg61870c22020-06-09 14:51:50 -06002040 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002041 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002042 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2043 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002044 SyncStageAccessIndex sync_index =
2045 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2046
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002047 for (uint32_t index = 0; index < binding->count; index++) {
2048 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002049 switch (descriptor->GetClass()) {
2050 case DescriptorClass::ImageSampler:
2051 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002052 if (descriptor->Invalid()) {
2053 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002054 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002055
2056 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2057 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2058 const auto *img_view_state = image_descriptor->GetImageViewState();
2059 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2060
John Zulauf361fb532020-07-22 10:45:39 -06002061 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002062 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2063 // Descriptors, so we do not have to worry about depth slicing here.
2064 // See: VUID 00343
2065 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002066 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002067 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002068
2069 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2070 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2071 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002072 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002073 hazard =
2074 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2075 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002076 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002077 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2078 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002079 }
John Zulauf110413c2021-03-20 05:38:38 -06002080
John Zulauf33fc1d52020-07-17 11:01:10 -06002081 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002082 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002083 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002084 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2085 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002086 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002087 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2088 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2089 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002090 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2091 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002092 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002093 }
2094 break;
2095 }
2096 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002097 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2098 if (texel_descriptor->Invalid()) {
2099 continue;
2100 }
2101 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2102 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002103 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002104 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002105 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002106 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002107 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002108 "%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 +09002109 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002110 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2111 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2112 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002113 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002114 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002115 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002116 }
2117 break;
2118 }
2119 case DescriptorClass::GeneralBuffer: {
2120 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002121 if (buffer_descriptor->Invalid()) {
2122 continue;
2123 }
2124 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002125 const ResourceAccessRange range =
2126 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002127 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002128 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002129 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002130 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002131 "%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 +09002132 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002133 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2134 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2135 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002136 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002137 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002138 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002139 }
2140 break;
2141 }
2142 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2143 default:
2144 break;
2145 }
2146 }
2147 }
2148 }
2149 return skip;
2150}
2151
2152void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002153 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002154 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002155 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002156 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002157 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002158 return;
2159 }
2160
2161 using DescriptorClass = cvdescriptorset::DescriptorClass;
2162 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2163 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002164 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2165
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002166 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002167 const auto raster_state = pipe->RasterizationState();
2168 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002169 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002170 }
locke-lunarg61870c22020-06-09 14:51:50 -06002171 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002172 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002173 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2174 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002175 SyncStageAccessIndex sync_index =
2176 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2177
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002178 for (uint32_t i = 0; i < binding->count; i++) {
2179 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002180 switch (descriptor->GetClass()) {
2181 case DescriptorClass::ImageSampler:
2182 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002183 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2184 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2185 if (image_descriptor->Invalid()) {
2186 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002187 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002188 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002189 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2190 // Descriptors, so we do not have to worry about depth slicing here.
2191 // See: VUID 00343
2192 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002193 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002194 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002195 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2196 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2197 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2198 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002199 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002200 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2201 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002202 }
locke-lunarg61870c22020-06-09 14:51:50 -06002203 break;
2204 }
2205 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002206 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2207 if (texel_descriptor->Invalid()) {
2208 continue;
2209 }
2210 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2211 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002212 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002213 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002214 break;
2215 }
2216 case DescriptorClass::GeneralBuffer: {
2217 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002218 if (buffer_descriptor->Invalid()) {
2219 continue;
2220 }
2221 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002222 const ResourceAccessRange range =
2223 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002224 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002225 break;
2226 }
2227 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2228 default:
2229 break;
2230 }
2231 }
2232 }
2233 }
2234}
2235
sjfricke0bea06e2022-06-05 09:22:26 +09002236bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002237 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002238 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002239 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002240 return skip;
2241 }
2242
2243 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2244 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002245 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002246
2247 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002248 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002249 if (binding_description.binding < binding_buffers_size) {
2250 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002251 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002252
locke-lunarg1ae57d62020-11-18 10:49:19 -07002253 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002254 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2255 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002256 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002257 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002258 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002259 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002260 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002261 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2262 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002263 }
2264 }
2265 }
2266 return skip;
2267}
2268
John Zulauf14940722021-04-12 15:19:02 -06002269void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002270 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002271 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002272 return;
2273 }
2274 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2275 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002276 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002277
2278 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002279 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002280 if (binding_description.binding < binding_buffers_size) {
2281 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002282 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002283
locke-lunarg1ae57d62020-11-18 10:49:19 -07002284 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002285 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2286 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002287 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2288 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002289 }
2290 }
2291}
2292
sjfricke0bea06e2022-06-05 09:22:26 +09002293bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002294 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002295 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002296 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002297 }
locke-lunarg61870c22020-06-09 14:51:50 -06002298
locke-lunarg1ae57d62020-11-18 10:49:19 -07002299 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002300 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002301 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2302 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002303 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002304 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002305 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002306 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 +09002307 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2308 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002309 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002310 }
2311
2312 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2313 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002314 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002315 return skip;
2316}
2317
John Zulauf14940722021-04-12 15:19:02 -06002318void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002319 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 -06002320
locke-lunarg1ae57d62020-11-18 10:49:19 -07002321 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002322 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002323 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2324 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002325 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002326
2327 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2328 // We will detect more accurate range in the future.
2329 RecordDrawVertex(UINT32_MAX, 0, tag);
2330}
2331
sjfricke0bea06e2022-06-05 09:22:26 +09002332bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002333 bool skip = false;
2334 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002335 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002336 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002337}
2338
John Zulauf14940722021-04-12 15:19:02 -06002339void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002340 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002341 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002342 }
locke-lunarg61870c22020-06-09 14:51:50 -06002343}
2344
John Zulauf00119522022-05-23 19:07:42 -06002345QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2346
sjfricke0bea06e2022-06-05 09:22:26 +09002347ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002348 const VkRect2D &render_area,
2349 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002350 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002351 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2352 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulaufab84f242022-08-04 18:38:40 -06002353 render_pass_contexts_.emplace_back(layer_data::make_unique<RenderPassAccessContext>(rp_state, render_area, GetQueueFlags(),
2354 attachment_views, &cb_access_context_));
2355 current_renderpass_context_ = render_pass_contexts_.back().get();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002356 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002357 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002358 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002359}
2360
sjfricke0bea06e2022-06-05 09:22:26 +09002361ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002362 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002363 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002364
sjfricke0bea06e2022-06-05 09:22:26 +09002365 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2366 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2367 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002368
2369 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002370 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002371 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002372}
2373
sjfricke0bea06e2022-06-05 09:22:26 +09002374ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002375 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002376 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002377
sjfricke0bea06e2022-06-05 09:22:26 +09002378 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2379 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002380
2381 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002382 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002383 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002384 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002385}
2386
John Zulauf4a6105a2020-11-17 15:11:05 -07002387void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2388 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002389 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002390 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002391 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002392 }
2393}
2394
John Zulaufae842002021-04-15 18:20:55 -06002395// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002396bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002397 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002398 if (!exec_context.ValidForSyncOps()) return false;
2399
2400 const QueueId queue_id = exec_context.GetQueueId();
2401 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002402 bool skip = false;
2403 ResourceUsageRange tag_range = {0, 0};
2404 const AccessContext *recorded_context = GetCurrentAccessContext();
2405 assert(recorded_context);
2406 HazardResult hazard;
John Zulaufdab327f2022-07-08 12:02:05 -06002407 ReplayGuard replay_guard(exec_context, *this);
2408
John Zulaufbb890452021-12-14 11:30:18 -07002409 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002410 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002411 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002412 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002413 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002414 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002415 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2416 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002417 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002418 };
2419 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002420 // we update the range to any include layout transition first use writes,
2421 // as they are stored along with the source scope (as effective barrier) when recorded
2422 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002423 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002424
John Zulauf0223f142022-07-06 09:05:39 -06002425 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2426 // we need to fetch the current access context each time
John Zulaufdab327f2022-07-08 12:02:05 -06002427 hazard = exec_context.DetectFirstUseHazard(tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002428 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002429 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002430 }
2431 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002432 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002433 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002434 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002435 }
2436
2437 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002438 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002439 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002440 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002441 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002442 }
2443
2444 return skip;
2445}
2446
sjfricke0bea06e2022-06-05 09:22:26 +09002447void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002448 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2449 assert(recorded_context);
2450
2451 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2452 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002453 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002454 // we update the range to any include layout transition first use writes,
2455 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002456 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002457 }
2458
2459 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2460 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002461 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002462}
2463
John Zulauf1d5f9c12022-05-13 14:51:08 -06002464void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002465 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002466 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002467}
2468
John Zulaufdab327f2022-07-08 12:02:05 -06002469HazardResult CommandBufferAccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
2470 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, *GetCurrentAccessContext());
2471}
2472
John Zulauf3c788ef2022-02-22 12:12:30 -07002473ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002474 // The execution references ensure lifespan for the referenced child CB's...
2475 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002476 InsertRecordedAccessLogEntries(recorded_context);
2477 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002478 return tag_range;
2479}
2480
John Zulauf3c788ef2022-02-22 12:12:30 -07002481void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2482 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2483 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2484}
2485
John Zulauf41a9c7c2021-12-07 15:59:53 -07002486ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2487 ResourceUsageTag next = access_log_.size();
2488 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2489 return next;
2490}
2491
2492ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2493 command_number_++;
2494 subcommand_number_ = 0;
2495 ResourceUsageTag next = access_log_.size();
2496 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2497 return next;
2498}
2499
2500ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2501 if (index == 0) {
2502 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2503 }
2504 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2505}
2506
John Zulaufbb890452021-12-14 11:30:18 -07002507void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2508 auto tag = sync_op->Record(this);
2509 // As renderpass operations can have side effects on the command buffer access context,
2510 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002511 sync_ops_.emplace_back(tag, std::move(sync_op));
2512}
2513
John Zulaufae842002021-04-15 18:20:55 -06002514class HazardDetectFirstUse {
2515 public:
John Zulauf0223f142022-07-06 09:05:39 -06002516 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2517 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002518 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002519 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002520 }
2521 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2522 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2523 }
2524
2525 private:
2526 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002527 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002528 const ResourceUsageRange &tag_range_;
2529};
2530
2531// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2532// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002533HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002534 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002535 HazardResult hazard;
2536 for (const auto address_type : kAddressTypes) {
2537 const auto &recorded_access_map = GetAccessStateMap(address_type);
2538 for (const auto &recorded_access : recorded_access_map) {
2539 // Cull any entries not in the current tag range
2540 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002541 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002542 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2543 if (hazard.hazard) break;
2544 }
2545 }
2546
2547 return hazard;
2548}
2549
John Zulaufbb890452021-12-14 11:30:18 -07002550bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002551 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002552 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002553 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002554 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002555 if (!pipe) {
2556 return skip;
2557 }
2558
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002559 const auto raster_state = pipe->RasterizationState();
2560 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002561 return skip;
2562 }
sjfricke0bea06e2022-06-05 09:22:26 +09002563 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002564 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002565 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002566
John Zulauf1a224292020-06-30 14:52:13 -06002567 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002568 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002569 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2570 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002571 if (location >= subpass.colorAttachmentCount ||
2572 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002573 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002574 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002575 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2576 if (!view_gen.IsValid()) continue;
2577 HazardResult hazard =
2578 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2579 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002580 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002581 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002582 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002583 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002584 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002585 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002586 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2587 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002588 }
2589 }
2590 }
locke-lunarg37047832020-06-12 13:44:45 -06002591
2592 // PHASE1 TODO: Add layout based read/vs. write selection.
2593 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002594 const auto ds_state = pipe->DepthStencilState();
2595 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002596
2597 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2598 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2599 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002600 bool depth_write = false, stencil_write = false;
2601
2602 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002603 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002604 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2605 depth_write = true;
2606 }
2607 // PHASE1 TODO: It needs to check if stencil is writable.
2608 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2609 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2610 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002611 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002612 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2613 stencil_write = true;
2614 }
2615
2616 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2617 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002618 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2619 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2620 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002621 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002622 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002623 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002624 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002625 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002626 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002627 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002628 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002629 }
2630 }
2631 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002632 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2633 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2634 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002635 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002636 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002637 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002638 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002639 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002640 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002641 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002642 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002643 }
locke-lunarg61870c22020-06-09 14:51:50 -06002644 }
2645 }
2646 return skip;
2647}
2648
sjfricke0bea06e2022-06-05 09:22:26 +09002649void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2650 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002651 if (!pipe) {
2652 return;
2653 }
2654
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002655 const auto *raster_state = pipe->RasterizationState();
2656 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002657 return;
2658 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002659 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002660 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002661
John Zulauf1a224292020-06-30 14:52:13 -06002662 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002663 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002664 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2665 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002666 if (location >= subpass.colorAttachmentCount ||
2667 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002668 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002669 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002670 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2671 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2672 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2673 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002674 }
2675 }
locke-lunarg37047832020-06-12 13:44:45 -06002676
2677 // PHASE1 TODO: Add layout based read/vs. write selection.
2678 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002679 const auto *ds_state = pipe->DepthStencilState();
2680 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002681 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2682 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2683 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002684 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002685 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2686 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002687
2688 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002689 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2690 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002691 depth_write = true;
2692 }
2693 // PHASE1 TODO: It needs to check if stencil is writable.
2694 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2695 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2696 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002697 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002698 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2699 stencil_write = true;
2700 }
2701
John Zulaufd0ec59f2021-03-13 14:25:08 -07002702 if (depth_write || stencil_write) {
2703 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2704 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2705 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2706 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002707 }
locke-lunarg61870c22020-06-09 14:51:50 -06002708 }
2709}
2710
sjfricke0bea06e2022-06-05 09:22:26 +09002711bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002712 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002713 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002714 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002715 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002716 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002717 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002718
John Zulauf355e49b2020-04-24 15:11:15 -06002719 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002720 if (next_subpass >= subpass_contexts_.size()) {
2721 return skip;
2722 }
John Zulauf1507ee42020-05-18 11:33:09 -06002723 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002724 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002725 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002726 if (!skip) {
2727 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2728 // on a copy of the (empty) next context.
2729 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2730 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002731 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002732 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002733 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002734 }
John Zulauf7635de32020-05-29 17:14:15 -06002735 return skip;
2736}
sjfricke0bea06e2022-06-05 09:22:26 +09002737bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002738 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002739 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002740 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002741 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002742 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2743 cmd_type);
2744 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002745 return skip;
2746}
2747
John Zulauf64ffe552021-02-06 10:25:07 -07002748AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002749 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002750}
2751
John Zulaufbb890452021-12-14 11:30:18 -07002752bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002753 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002754 bool skip = false;
2755
John Zulauf7635de32020-05-29 17:14:15 -06002756 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2757 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2758 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2759 // to apply and only copy then, if this proves a hot spot.
2760 std::unique_ptr<AccessContext> proxy_for_current;
2761
John Zulauf355e49b2020-04-24 15:11:15 -06002762 // Validate the "finalLayout" transitions to external
2763 // Get them from where there we're hidding in the extra entry.
2764 const auto &final_transitions = rp_state_->subpass_transitions.back();
2765 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002766 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002767 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002768 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2769 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002770
2771 if (transition.prev_pass == current_subpass_) {
2772 if (!proxy_for_current) {
2773 // 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 -07002774 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002775 }
2776 context = proxy_for_current.get();
2777 }
2778
John Zulaufa0a98292020-09-18 09:30:10 -06002779 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2780 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002781 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002782 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002783 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002784 if (hazard.tag == kInvalidTag) {
2785 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002786 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002787 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2788 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2789 " final image layout transition (old_layout: %s, new_layout: %s).",
2790 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2791 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2792 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002793 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002794 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2795 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2796 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2797 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2798 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002799 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002800 }
John Zulauf355e49b2020-04-24 15:11:15 -06002801 }
2802 }
2803 return skip;
2804}
2805
John Zulauf14940722021-04-12 15:19:02 -06002806void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002807 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002808 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002809}
2810
John Zulauf14940722021-04-12 15:19:02 -06002811void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002812 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2813 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002814
2815 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2816 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002817 const AttachmentViewGen &view_gen = attachment_views_[i];
2818 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002819
2820 const auto &ci = attachment_ci[i];
2821 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002822 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002823 const bool is_color = !(has_depth || has_stencil);
2824
2825 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002826 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2827 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2828 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2829 SyncOrdering::kColorAttachment, tag);
2830 }
John Zulauf1507ee42020-05-18 11:33:09 -06002831 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002832 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002833 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2834 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2835 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2836 SyncOrdering::kDepthStencilAttachment, tag);
2837 }
John Zulauf1507ee42020-05-18 11:33:09 -06002838 }
2839 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002840 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2841 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2842 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2843 SyncOrdering::kDepthStencilAttachment, tag);
2844 }
John Zulauf1507ee42020-05-18 11:33:09 -06002845 }
2846 }
2847 }
2848 }
2849}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002850AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2851 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2852 AttachmentViewGenVector view_gens;
2853 VkExtent3D extent = CastTo3D(render_area.extent);
2854 VkOffset3D offset = CastTo3D(render_area.offset);
2855 view_gens.reserve(attachment_views.size());
2856 for (const auto *view : attachment_views) {
2857 view_gens.emplace_back(view, offset, extent);
2858 }
2859 return view_gens;
2860}
John Zulauf64ffe552021-02-06 10:25:07 -07002861RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2862 VkQueueFlags queue_flags,
2863 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2864 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002865 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulaufdab327f2022-07-08 12:02:05 -06002866 // Add this for all subpasses here so that they exist during next subpass validation
2867 InitSubpassContexts(queue_flags, rp_state, external_context, subpass_contexts_);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002868 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002869}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002870void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002871 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002872 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2873 RecordLayoutTransitions(barrier_tag);
2874 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002875}
John Zulauf1507ee42020-05-18 11:33:09 -06002876
John Zulauf41a9c7c2021-12-07 15:59:53 -07002877void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2878 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002879 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002880 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2881 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002882
ziga-lunarg31a3e772022-03-22 11:48:46 +01002883 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2884 return;
2885 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002886 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2887 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002888 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002889 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2890 RecordLayoutTransitions(barrier_tag);
2891 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002892}
2893
John Zulauf41a9c7c2021-12-07 15:59:53 -07002894void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2895 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002896 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002897 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2898 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002899
John Zulauf355e49b2020-04-24 15:11:15 -06002900 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002901 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002902
2903 // Add the "finalLayout" transitions to external
2904 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002905 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2906 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2907 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002908 const auto &final_transitions = rp_state_->subpass_transitions.back();
2909 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002910 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002911 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002912 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002913 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002914 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002915 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002916 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002917 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002918 }
2919}
2920
John Zulauf06f6f1e2022-04-19 15:28:11 -06002921SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2922 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002923 SyncExecScope result;
2924 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002925 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002926 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002927 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002928 return result;
2929}
2930
Jeremy Gebben40a22942020-12-22 14:22:06 -07002931SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002932 SyncExecScope result;
2933 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002934 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2935 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002936 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002937 return result;
2938}
2939
John Zulaufecf4ac52022-06-06 10:08:42 -06002940SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2941 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2942
2943SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2944 : 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 -07002945
2946template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002947SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2948 : src_exec_scope(src),
2949 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2950 dst_exec_scope(dst),
2951 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002952
2953SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002954 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2955 if (barrier) {
2956 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002957 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002958 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002959
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002960 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002961 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002962 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2963
2964 } else {
2965 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002966 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002967 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2968
2969 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002970 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002971 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2972 }
2973}
2974
2975template <typename Barrier>
2976SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2977 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2978 src_exec_scope = src.exec_scope;
2979 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2980
2981 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002982 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002983 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002984}
2985
John Zulaufb02c1eb2020-10-06 16:33:36 -06002986// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2987void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002988 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002989 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002990 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002991 }
2992}
2993
John Zulauf89311b42020-09-29 16:28:47 -06002994// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2995// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2996// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002997void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002998 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002999 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06003000 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06003001 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003002 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06003003 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06003004 }
John Zulaufbb890452021-12-14 11:30:18 -07003005 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06003006}
John Zulauf9cb530d2019-09-30 14:14:10 -06003007HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
3008 HazardResult hazard;
3009 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003010 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06003011 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003012 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06003013 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003014 }
3015 } else {
John Zulauf361fb532020-07-22 10:45:39 -06003016 // Write operation:
3017 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
3018 // If reads exists -- test only against them because either:
3019 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
3020 // * 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
3021 // the current write happens after the reads, so just test the write against the reades
3022 // Otherwise test against last_write
3023 //
3024 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003025 if (last_reads.size()) {
3026 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003027 if (IsReadHazard(usage_stage, read_access)) {
3028 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3029 break;
3030 }
3031 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003032 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003033 // Write-After-Write check -- if we have a previous write to test against
3034 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003035 }
3036 }
3037 return hazard;
3038}
3039
John Zulaufec943ec2022-06-29 07:52:56 -06003040HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3041 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003042 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003043 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003044}
3045
John Zulaufec943ec2022-06-29 07:52:56 -06003046HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3047 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003048 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3049 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003050 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003051 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003052 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003053 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003054 if (IsRead(usage_bit)) {
3055 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3056 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3057 if (is_raw_hazard) {
3058 // NOTE: we know last_write is non-zero
3059 // See if the ordering rules save us from the simple RAW check above
3060 // First check to see if the current usage is covered by the ordering rules
3061 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3062 const bool usage_is_ordered =
3063 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3064 if (usage_is_ordered) {
3065 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003066 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003067 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003068 }
3069 }
John Zulauf4285ee92020-09-23 10:20:52 -06003070 if (is_raw_hazard) {
3071 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3072 }
John Zulauf5c628d02021-05-04 15:46:36 -06003073 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3074 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003075 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003076 } else {
3077 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003078 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003079 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003080 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003081 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003082 if (usage_write_is_ordered) {
3083 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003084 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003085 }
3086 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3087 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003088 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003089 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3090 if (IsReadHazard(usage_stage, read_access)) {
3091 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3092 break;
3093 }
John Zulaufd14743a2020-07-03 09:42:39 -06003094 }
3095 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003096 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3097 bool ilt_ilt_hazard = false;
3098 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3099 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3100 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3101 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3102 }
3103 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003104 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003105 }
John Zulauf69133422020-05-20 14:55:53 -06003106 }
3107 }
3108 return hazard;
3109}
3110
John Zulaufec943ec2022-06-29 07:52:56 -06003111HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3112 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003113 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003114 using Size = FirstAccesses::size_type;
3115 const auto &recorded_accesses = recorded_use.first_accesses_;
3116 Size count = recorded_accesses.size();
3117 if (count) {
3118 const auto &last_access = recorded_accesses.back();
3119 bool do_write_last = IsWrite(last_access.usage_index);
3120 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003121
John Zulauf4fa68462021-04-26 21:04:22 -06003122 for (Size i = 0; i < count; ++count) {
3123 const auto &first = recorded_accesses[i];
3124 // Skip and quit logic
3125 if (first.tag < tag_range.begin) continue;
3126 if (first.tag >= tag_range.end) {
3127 do_write_last = false; // ignore last since we know it can't be in tag_range
3128 break;
3129 }
3130
John Zulaufec943ec2022-06-29 07:52:56 -06003131 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003132 if (hazard.hazard) {
3133 hazard.AddRecordedAccess(first);
3134 break;
3135 }
3136 }
3137
3138 if (do_write_last && tag_range.includes(last_access.tag)) {
3139 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3140 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3141 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3142 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3143 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3144 // the barrier that applies them
3145 barrier |= recorded_use.first_write_layout_ordering_;
3146 }
3147 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3148 // the active context
3149 if (recorded_use.first_read_stages_) {
3150 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3151 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3152 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3153 // active context.
3154 barrier.exec_scope |= recorded_use.first_read_stages_;
3155 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3156 barrier.access_scope |= FlagBit(last_access.usage_index);
3157 }
John Zulaufec943ec2022-06-29 07:52:56 -06003158 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003159 if (hazard.hazard) {
3160 hazard.AddRecordedAccess(last_access);
3161 }
3162 }
John Zulaufae842002021-04-15 18:20:55 -06003163 }
3164 return hazard;
3165}
3166
John Zulauf2f952d22020-02-10 11:34:51 -07003167// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003168HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003169 HazardResult hazard;
3170 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003171 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3172 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3173 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003174 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003175 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003176 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003177 }
3178 } else {
John Zulauf14940722021-04-12 15:19:02 -06003179 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003180 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003181 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003182 // 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 -07003183 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003184 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003185 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003186 break;
3187 }
3188 }
John Zulauf2f952d22020-02-10 11:34:51 -07003189 }
3190 }
3191 return hazard;
3192}
3193
John Zulaufae842002021-04-15 18:20:55 -06003194HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3195 ResourceUsageTag start_tag) const {
3196 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003197 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003198 // Skip and quit logic
3199 if (first.tag < tag_range.begin) continue;
3200 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003201
3202 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003203 if (hazard.hazard) {
3204 hazard.AddRecordedAccess(first);
3205 break;
3206 }
John Zulaufae842002021-04-15 18:20:55 -06003207 }
3208 return hazard;
3209}
3210
John Zulaufec943ec2022-06-29 07:52:56 -06003211HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3212 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003213 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003214 // Only supporting image layout transitions for now
3215 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3216 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003217 // only test for WAW if there no intervening read operations.
3218 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003219 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003220 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003221 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003222 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003223 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003224 break;
3225 }
3226 }
John Zulaufec943ec2022-06-29 07:52:56 -06003227 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003228 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3229 }
3230
3231 return hazard;
3232}
3233
John Zulaufe0757ba2022-06-10 16:51:45 -06003234HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3235 VkPipelineStageFlags2KHR src_exec_scope,
3236 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3237 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003238 // Only supporting image layout transitions for now
3239 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3240 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003241
John Zulaufe0757ba2022-06-10 16:51:45 -06003242 if ((write_tag >= event_tag) && last_write.any()) {
3243 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3244 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3245 } else {
3246 // only test for WAW if there no intervening read operations.
3247 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3248 if (last_reads.size()) {
3249 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3250 // first scope, or they are a hazard.
3251 const ReadStates &scope_reads = scope_state.last_reads;
3252 const ReadStates::size_type scope_read_count = scope_reads.size();
3253 // Since the hasn't been a write:
3254 // * The current read state is a superset of the scoped one
3255 // * The stage order is the same.
3256 assert(last_reads.size() >= scope_read_count);
3257 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3258 const ReadState &scope_read = scope_reads[read_idx];
3259 const ReadState &current_read = last_reads[read_idx];
3260 assert(scope_read.stage == current_read.stage);
3261 if (current_read.tag > event_tag) {
3262 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3263 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3264 } else {
3265 // The read is in the events first synchronization scope, so we use a barrier hazard check
3266 // If the read stage is not in the src sync scope
3267 // *AND* not execution chained with an existing sync barrier (that's the or)
3268 // then the barrier access is unsafe (R/W after R)
3269 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3270 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3271 break;
3272 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003273 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003274 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003275 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3276 const ReadState &current_read = last_reads[scope_read_count];
3277 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3278 }
3279 } else if (last_write.any()) {
3280 // 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 -07003281 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3282 // So do a normal barrier hazard check
John Zulauf7ad6a1d2022-09-02 11:46:33 -06003283 if (scope_state.IsWriteBarrierHazard(event_queue, src_exec_scope, src_access_scope)) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003284 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003285 }
John Zulauf361fb532020-07-22 10:45:39 -06003286 }
John Zulaufd14743a2020-07-03 09:42:39 -06003287 }
John Zulauf361fb532020-07-22 10:45:39 -06003288
John Zulauf0cb5be22020-01-23 12:18:22 -07003289 return hazard;
3290}
3291
John Zulauf5f13a792020-03-10 07:31:21 -06003292// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3293// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3294// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3295void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003296 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003297 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3298 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003299 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003300 } else if (other.write_tag == write_tag) {
3301 // 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 -06003302 // dependency chaining logic or any stage expansion)
3303 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003304 pending_write_barriers |= other.pending_write_barriers;
3305 pending_layout_transition |= other.pending_layout_transition;
3306 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003307 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003308
John Zulaufd14743a2020-07-03 09:42:39 -06003309 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003310 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003311 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003312 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003313 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003314 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003315 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003316 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3317 // but we should wait on profiling data for that.
3318 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003319 auto &my_read = last_reads[my_read_index];
3320 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003321 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003322 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003323 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003324 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003325 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003326 my_read.pending_dep_chain = other_read.pending_dep_chain;
3327 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3328 // May require tracking more than one access per stage.
3329 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003330 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003331 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003332 // Since I'm overwriting the fragement stage read, also update the input attachment info
3333 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003334 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003335 }
John Zulauf14940722021-04-12 15:19:02 -06003336 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003337 // The read tags match so merge the barriers
3338 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003339 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003340 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003341 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003342
John Zulauf5f13a792020-03-10 07:31:21 -06003343 break;
3344 }
3345 }
3346 } else {
3347 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003348 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003349 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003350 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003351 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003352 }
John Zulauf5f13a792020-03-10 07:31:21 -06003353 }
3354 }
John Zulauf361fb532020-07-22 10:45:39 -06003355 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003356 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3357 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003358
3359 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3360 // of the copy and other into this using the update first logic.
3361 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3362 // of the other first_accesses... )
3363 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3364 FirstAccesses firsts(std::move(first_accesses_));
3365 first_accesses_.clear();
3366 first_read_stages_ = 0U;
3367 auto a = firsts.begin();
3368 auto a_end = firsts.end();
3369 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003370 // TODO: Determine whether some tag offset will be needed for PHASE II
3371 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003372 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3373 ++a;
3374 }
3375 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3376 }
3377 for (; a != a_end; ++a) {
3378 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3379 }
3380 }
John Zulauf5f13a792020-03-10 07:31:21 -06003381}
3382
John Zulauf14940722021-04-12 15:19:02 -06003383void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003384 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3385 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003386 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003387 // Mulitple outstanding reads may be of interest and do dependency chains independently
3388 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3389 const auto usage_stage = PipelineStageBit(usage_index);
3390 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003391 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003392 for (auto &read_access : last_reads) {
3393 if (read_access.stage == usage_stage) {
3394 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003395 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003396 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003397 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003398 } else {
3399 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3400 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3401 // that sync_stages is a subset of barriers may not apply.
3402 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003403 }
3404 }
3405 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003406 for (auto &read_access : last_reads) {
3407 if (read_access.barriers & usage_stage) {
3408 read_access.sync_stages |= usage_stage;
3409 }
3410 }
John Zulaufab7756b2020-12-29 16:10:16 -07003411 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003412 last_read_stages |= usage_stage;
3413 }
John Zulauf4285ee92020-09-23 10:20:52 -06003414
3415 // 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 -07003416 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003417 // TODO Revisit re: multiple reads for a given stage
3418 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003419 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003420 } else {
3421 // Assume write
3422 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003423 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003424 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003425 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003426}
John Zulauf5f13a792020-03-10 07:31:21 -06003427
John Zulauf89311b42020-09-29 16:28:47 -06003428// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3429// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3430// We can overwrite them as *this* write is now after them.
3431//
3432// 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 -06003433void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003434 ClearRead();
3435 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003436 write_tag = tag;
3437 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003438}
3439
John Zulauf1d5f9c12022-05-13 14:51:08 -06003440void ResourceAccessState::ClearWrite() {
3441 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3442 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3443 write_barriers.reset();
3444 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3445 last_write.reset();
3446
3447 write_tag = 0;
3448 write_queue = QueueSyncState::kQueueIdInvalid;
3449}
3450
3451void ResourceAccessState::ClearRead() {
3452 last_reads.clear();
3453 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3454}
3455
John Zulauf89311b42020-09-29 16:28:47 -06003456// Apply the memory barrier without updating the existing barriers. The execution barrier
3457// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3458// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3459// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003460template <typename ScopeOps>
3461void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003462 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3463 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003464 // 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 -06003465 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003466 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3467 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003468 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003469 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003470 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003471 if (layout_transition) {
3472 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3473 }
John Zulaufa0a98292020-09-18 09:30:10 -06003474 }
John Zulauf89311b42020-09-29 16:28:47 -06003475 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3476 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003477
John Zulauf89311b42020-09-29 16:28:47 -06003478 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003479 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3480 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003481 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3482
John Zulaufab7756b2020-12-29 16:10:16 -07003483 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003484 // 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 -06003485 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003486 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3487 stages_in_scope |= read_access.stage;
3488 }
3489 }
3490
3491 for (auto &read_access : last_reads) {
3492 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3493 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3494 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3495 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003496 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003497 }
3498 }
John Zulaufa0a98292020-09-18 09:30:10 -06003499 }
John Zulaufa0a98292020-09-18 09:30:10 -06003500}
3501
John Zulauf14940722021-04-12 15:19:02 -06003502void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003503 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003504 // 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 -06003505 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003506 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003507 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3508 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003509 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003510 }
John Zulauf89311b42020-09-29 16:28:47 -06003511
3512 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003513 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003514 for (auto &read_access : last_reads) {
3515 read_access.barriers |= read_access.pending_dep_chain;
3516 read_execution_barriers |= read_access.barriers;
3517 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003518 }
3519
3520 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3521 write_dependency_chain |= pending_write_dep_chain;
3522 write_barriers |= pending_write_barriers;
3523 pending_write_dep_chain = 0;
3524 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003525}
3526
John Zulaufecf4ac52022-06-06 10:08:42 -06003527// Assumes signal queue != wait queue
3528void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3529 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3530 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3531 assert(signal.queue != wait.queue);
3532 for (auto &read_access : last_reads) {
3533 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3534 // Deflects WAR on wait queue
3535 read_access.barriers = wait.exec_scope;
3536 } else {
3537 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3538 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3539 }
3540 }
3541 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3542 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3543 read_execution_barriers = wait.exec_scope;
3544 write_barriers = wait.valid_accesses;
3545 } else {
3546 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3547 write_barriers.reset();
3548 }
3549 write_dependency_chain = read_execution_barriers;
3550}
3551
John Zulauf3da08bb2022-08-01 17:56:56 -06003552bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) const {
3553 return (usage_queue == queue) && (usage_tag <= tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003554}
3555
John Zulauf3da08bb2022-08-01 17:56:56 -06003556bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) const { return queue == usage_queue; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003557
John Zulauf3da08bb2022-08-01 17:56:56 -06003558bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) const { return tag <= usage_tag; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003559
3560// Return if the resulting state is "empty"
3561template <typename Pred>
3562bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3563 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3564
3565 // Use the predicate to build a mask of the read stages we are synchronizing
3566 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003567 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003568 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003569 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3570 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003571 }
3572 }
3573
John Zulauf434c4e62022-05-19 16:03:56 -06003574 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3575 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3576 uint32_t unsync_count = 0;
3577 for (auto &read_access : last_reads) {
3578 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3579 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3580 sync_reads |= read_access.stage;
3581 } else {
3582 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003583 }
3584 }
3585
3586 if (unsync_count) {
3587 if (sync_reads) {
3588 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3589 ReadStates unsync_reads;
3590 unsync_reads.reserve(unsync_count);
3591 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3592 for (auto &read_access : last_reads) {
3593 if (0 == (read_access.stage & sync_reads)) {
3594 unsync_reads.emplace_back(read_access);
3595 unsync_read_stages |= read_access.stage;
3596 }
3597 }
3598 last_read_stages = unsync_read_stages;
3599 last_reads = std::move(unsync_reads);
3600 }
3601 } else {
3602 // Nothing remains (or it was empty to begin with)
3603 ClearRead();
3604 }
3605
3606 bool all_clear = last_reads.size() == 0;
3607 if (last_write.any()) {
3608 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3609 // Clear any predicated write, or any the write from any any access with synchronized reads.
3610 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3611 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3612 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3613 ClearWrite();
3614 } else {
3615 all_clear = false;
3616 }
3617 }
3618 return all_clear;
3619}
3620
John Zulaufae842002021-04-15 18:20:55 -06003621bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3622 if (!first_accesses_.size()) return false;
3623 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3624 return tag_range.intersects(first_access_range);
3625}
3626
John Zulauf1d5f9c12022-05-13 14:51:08 -06003627void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3628 if (last_write.any()) write_tag += offset;
3629 for (auto &read_access : last_reads) {
3630 read_access.tag += offset;
3631 }
3632 for (auto &first : first_accesses_) {
3633 first.tag += offset;
3634 }
3635}
3636
3637ResourceAccessState::ResourceAccessState()
3638 : write_barriers(~SyncStageAccessFlags(0)),
3639 write_dependency_chain(0),
3640 write_tag(),
3641 write_queue(QueueSyncState::kQueueIdInvalid),
3642 last_write(0),
3643 input_attachment_read(false),
3644 last_read_stages(0),
3645 read_execution_barriers(0),
3646 pending_write_dep_chain(0),
3647 pending_layout_transition(false),
3648 pending_write_barriers(0),
3649 pending_layout_ordering_(),
3650 first_accesses_(),
3651 first_read_stages_(0U),
3652 first_write_layout_ordering_() {}
3653
John Zulauf59e25072020-07-17 10:55:21 -06003654// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003655VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3656 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003657
John Zulaufab7756b2020-12-29 16:10:16 -07003658 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003659 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003660 barriers = read_access.barriers;
3661 break;
John Zulauf59e25072020-07-17 10:55:21 -06003662 }
3663 }
John Zulauf4285ee92020-09-23 10:20:52 -06003664
John Zulauf59e25072020-07-17 10:55:21 -06003665 return barriers;
3666}
3667
John Zulauf1d5f9c12022-05-13 14:51:08 -06003668void ResourceAccessState::SetQueueId(QueueId id) {
3669 for (auto &read_access : last_reads) {
3670 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3671 read_access.queue = id;
3672 }
3673 }
3674 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3675 write_queue = id;
3676 }
3677}
3678
John Zulauf00119522022-05-23 19:07:42 -06003679bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3680 return 0 != (write_dependency_chain & src_exec_scope);
3681}
3682
3683bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3684 return (src_access_scope & last_write).any();
3685}
3686
John Zulaufec943ec2022-06-29 07:52:56 -06003687bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3688 return (write_barriers & src_access_scope).any();
3689}
3690
John Zulaufb7578302022-05-19 13:50:18 -06003691bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3692 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003693 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3694}
3695
3696bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3697 SyncStageAccessFlags src_access_scope) const {
3698 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003699}
3700
John Zulaufe0757ba2022-06-10 16:51:45 -06003701bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3702 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003703 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3704 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3705 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003706 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003707}
3708
John Zulaufec943ec2022-06-29 07:52:56 -06003709bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3710 const SyncStageAccessFlags &src_access_scope) const {
3711 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3712}
3713
John Zulaufcb7e1672022-05-04 13:46:08 -06003714bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003715 assert(IsRead(usage));
3716 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3717 // * the previous reads are not hazards, and thus last_write must be visible and available to
3718 // any reads that happen after.
3719 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3720 // 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 -07003721 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003722}
3723
John Zulaufec943ec2022-06-29 07:52:56 -06003724VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3725 // At apply queue submission order limits on the effect of ordering
3726 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3727 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3728 for (const auto &read_access : last_reads) {
3729 if (read_access.queue != queue_id) {
3730 non_qso_stages |= read_access.stage;
3731 }
3732 }
3733 }
John Zulauf4285ee92020-09-23 10:20:52 -06003734 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003735 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3736 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003737 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003738 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003739 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003740 // 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 -07003741 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003742 }
3743
3744 return ordered_stages;
3745}
3746
John Zulauf14940722021-04-12 15:19:02 -06003747void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003748 // Only record until we record a write.
3749 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003750 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003751 if (0 == (usage_stage & first_read_stages_)) {
3752 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003753 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003754 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003755 if (0 == (read_execution_barriers & usage_stage)) {
3756 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3757 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3758 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003759 }
3760 }
3761}
3762
John Zulauf4fa68462021-04-26 21:04:22 -06003763void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3764 // Only call this after recording an image layout transition
3765 assert(first_accesses_.size());
3766 if (first_accesses_.back().tag == tag) {
3767 // 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 +02003768 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003769 first_write_layout_ordering_ = layout_ordering;
3770 }
3771}
3772
John Zulauf1d5f9c12022-05-13 14:51:08 -06003773ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3774 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3775 : stage(stage_),
3776 access(access_),
3777 barriers(barriers_),
3778 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3779 tag(tag_),
3780 queue(QueueSyncState::kQueueIdInvalid),
3781 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3782
John Zulaufee984022022-04-13 16:39:50 -06003783void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3784 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3785 stage = stage_;
3786 access = access_;
3787 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003788 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003789 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003790 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 -06003791}
3792
John Zulauf00119522022-05-23 19:07:42 -06003793// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3794// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3795// that have bee applied (via semaphore) to those accesses can be chained off of.
3796bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3797 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3798 return (exec_scope & effective_stages) != 0;
3799}
3800
John Zulauf697c0e12022-04-19 16:31:12 -06003801ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3802 ResourceUsageRange reserve;
3803 reserve.begin = tag_limit_.fetch_add(tag_count);
3804 reserve.end = reserve.begin + tag_count;
3805 return reserve;
3806}
3807
John Zulauf3da08bb2022-08-01 17:56:56 -06003808void SyncValidator::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
3809 // We need to go through every queue batch context and clear all accesses this wait synchronizes
3810 // As usual -- two groups, the "last batch" and the signaled semaphores
3811 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
3812 // QueueBatchContext, track which we've done to avoid duplicate traversals
3813 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
3814 for (auto &batch : queue_batch_contexts) {
3815 batch->ApplyTaggedWait(queue_id, tag);
3816 }
3817}
3818
3819void SyncValidator::UpdateFenceWaitInfo(VkFence fence, QueueId queue_id, ResourceUsageTag tag) {
3820 if (fence != VK_NULL_HANDLE) {
3821 // Overwrite the current fence wait information
3822 // NOTE: Not doing fence usage validation here, leaving that in CoreChecks intentionally
3823 auto fence_state = Get<FENCE_STATE>(fence);
3824 waitable_fences_[fence] = {fence_state, tag, queue_id};
3825 }
3826}
3827
3828void SyncValidator::WaitForFence(VkFence fence) {
3829 auto fence_it = waitable_fences_.find(fence);
3830 if (fence_it != waitable_fences_.end()) {
3831 // The fence may no longer be waitable for several valid reasons.
3832 FenceSyncState &wait_for = fence_it->second;
3833 ApplyTaggedWait(wait_for.queue_id, wait_for.tag);
3834 waitable_fences_.erase(fence_it);
3835 }
3836}
3837
John Zulaufbbda4572022-04-19 16:20:45 -06003838const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3839 return GetMappedPlainFromShared(queue_sync_states_, queue);
3840}
3841
3842QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3843
3844std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3845 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3846}
3847
3848std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3849 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3850}
3851
John Zulaufe0757ba2022-06-10 16:51:45 -06003852template <typename T>
3853struct GetBatchTraits {};
3854template <>
3855struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3856 using Batch = std::shared_ptr<QueueBatchContext>;
3857 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3858};
3859
3860template <>
3861struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3862 using Batch = std::shared_ptr<QueueBatchContext>;
3863 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3864};
3865
3866template <typename BatchSet, typename Map, typename Predicate>
3867static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003868 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003869 for (auto &entry : map) {
3870 // Intentional copy
3871 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003872 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003873 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003874 return snapshot;
3875}
3876
3877template <typename Predicate>
3878QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003879 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003880}
3881
3882template <typename Predicate>
3883QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003884 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3885}
3886
3887QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3888 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3889 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3890 if (batch && !layer_data::Contains(snapshot, batch)) {
3891 snapshot.emplace(batch);
3892 }
3893 return false;
3894 };
3895 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3896 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003897}
3898
John Zulaufa8700a52022-08-18 16:22:08 -06003899struct QueueSubmitCmdState {
3900 std::shared_ptr<const QueueSyncState> queue;
3901 std::shared_ptr<QueueBatchContext> last_batch;
3902 std::string submit_func_name;
3903 AccessLogger logger;
3904 SignaledSemaphores signaled;
3905 QueueSubmitCmdState(const char *func_name, const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
3906 : submit_func_name(func_name), logger(&parent_log), signaled(parent_semaphores) {}
3907};
3908
3909bool QueueBatchContext::DoQueueSubmitValidate(const SyncValidator &sync_state, QueueSubmitCmdState &cmd_state,
3910 const VkSubmitInfo2 &batch_info) {
3911 bool skip = false;
3912
3913 // For each submit in the batch...
3914 for (const auto &cb : command_buffers_) {
3915 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
3916 skip |= cb.cb->ValidateFirstUse(*this, cmd_state.submit_func_name.c_str(), cb.index);
3917
3918 // The barriers have already been applied in ValidatFirstUse
3919 ResourceUsageRange tag_range = ImportRecordedAccessLog(*cb.cb);
3920 ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
3921 }
3922 return skip;
3923}
3924
John Zulaufcb7e1672022-05-04 13:46:08 -06003925bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3926 const std::shared_ptr<QueueBatchContext> &batch,
3927 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003928 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003929 const SyncExecScope exec_scope =
3930 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3931 const VkSemaphore sem = sem_state->semaphore();
3932 auto signal_it = signaled_.find(sem);
3933 std::shared_ptr<Signal> insert_signal;
3934 if (signal_it == signaled_.end()) {
3935 if (prev_) {
3936 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3937 if (prev_sig) {
3938 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3939 insert_signal = std::make_shared<Signal>(*prev_sig);
3940 }
3941 }
3942 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3943 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003944 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003945
3946 bool success = false;
3947 if (!signal_it->second) {
3948 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3949 success = true;
3950 }
3951
3952 return success;
3953}
3954
John Zulaufecf4ac52022-06-06 10:08:42 -06003955std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3956 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003957 const auto found_it = signaled_.find(sem);
3958 if (found_it != signaled_.end()) {
3959 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3960 // a bit.
3961 unsignaled = std::move(found_it->second);
3962 if (!prev_) {
3963 // No parent, not need to keep the entry
3964 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3965 signaled_.erase(found_it);
3966 }
3967 } else if (prev_) {
3968 // We can't unsignal prev_ because it's const * by design.
3969 // We put in an empty placeholder
3970 signaled_.emplace(sem, std::shared_ptr<Signal>());
3971 unsignaled = GetPrev(sem);
3972 }
3973 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3974 // but CoreChecks should have reported it
3975
3976 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003977 return unsignaled;
3978}
3979
John Zulaufcb7e1672022-05-04 13:46:08 -06003980void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3981 // Overwrite the s tate with the last state from this
3982 if (from) {
3983 assert(sem == from->sem_state->semaphore());
3984 signaled_[sem] = std::move(from);
3985 } else {
3986 signaled_.erase(sem);
3987 }
3988}
3989
3990void SignaledSemaphores::Reset() {
3991 signaled_.clear();
3992 prev_ = nullptr;
3993}
3994
John Zulaufea943c52022-02-22 11:05:17 -07003995std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3996 // If we don't have one, make it.
3997 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3998 assert(cb_state.get());
3999 auto queue_flags = cb_state->GetQueueFlags();
4000 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
4001}
4002
John Zulaufcb7e1672022-05-04 13:46:08 -06004003std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07004004 return GetMappedInsert(cb_access_state, command_buffer,
4005 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
4006}
4007
4008std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
4009 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
4010}
4011
4012const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
4013 return GetMappedPlainFromShared(cb_access_state, command_buffer);
4014}
4015
4016CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
4017 return GetAccessContextShared(command_buffer).get();
4018}
4019
4020CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
4021 return GetMappedPlainFromShared(cb_access_state, command_buffer);
4022}
4023
John Zulaufd1f85d42020-04-15 12:23:15 -06004024void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004025 auto *access_context = GetAccessContextNoInsert(command_buffer);
4026 if (access_context) {
4027 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06004028 }
4029}
4030
John Zulaufd1f85d42020-04-15 12:23:15 -06004031void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
4032 auto access_found = cb_access_state.find(command_buffer);
4033 if (access_found != cb_access_state.end()) {
4034 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06004035 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06004036 cb_access_state.erase(access_found);
4037 }
4038}
4039
John Zulauf9cb530d2019-09-30 14:14:10 -06004040bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4041 uint32_t regionCount, const VkBufferCopy *pRegions) const {
4042 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004043 const auto *cb_context = GetAccessContext(commandBuffer);
4044 assert(cb_context);
4045 if (!cb_context) return skip;
4046 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06004047
John Zulauf3d84f1b2020-03-09 13:33:25 -06004048 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004049 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4050 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004051
4052 for (uint32_t region = 0; region < regionCount; region++) {
4053 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004054 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004055 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004056 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004057 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004058 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004059 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004060 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004061 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06004062 }
John Zulauf9cb530d2019-09-30 14:14:10 -06004063 }
John Zulauf16adfc92020-04-08 10:28:33 -06004064 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004065 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004066 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004067 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004068 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004069 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004070 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004071 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06004072 }
4073 }
4074 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06004075 }
4076 return skip;
4077}
4078
4079void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4080 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004081 auto *cb_context = GetAccessContext(commandBuffer);
4082 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004083 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004084 auto *context = cb_context->GetCurrentAccessContext();
4085
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004086 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4087 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004088
4089 for (uint32_t region = 0; region < regionCount; region++) {
4090 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004091 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004092 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004093 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004094 }
John Zulauf16adfc92020-04-08 10:28:33 -06004095 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004096 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004097 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004098 }
4099 }
4100}
4101
John Zulauf4a6105a2020-11-17 15:11:05 -07004102void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4103 // Clear out events from the command buffer contexts
4104 for (auto &cb_context : cb_access_state) {
4105 cb_context.second->RecordDestroyEvent(event);
4106 }
4107}
4108
Tony-LunarGef035472021-11-02 10:23:33 -06004109bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4110 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004111 bool skip = false;
4112 const auto *cb_context = GetAccessContext(commandBuffer);
4113 assert(cb_context);
4114 if (!cb_context) return skip;
4115 const auto *context = cb_context->GetCurrentAccessContext();
4116
4117 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004118 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4119 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004120
4121 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4122 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4123 if (src_buffer) {
4124 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004125 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004126 if (hazard.hazard) {
4127 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004128 skip |=
4129 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4130 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4131 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4132 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004133 }
4134 }
4135 if (dst_buffer && !skip) {
4136 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004137 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004138 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004139 skip |=
4140 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4141 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4142 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4143 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004144 }
4145 }
4146 if (skip) break;
4147 }
4148 return skip;
4149}
4150
Tony-LunarGef035472021-11-02 10:23:33 -06004151bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4152 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4153 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4154}
4155
4156bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4157 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4158}
4159
4160void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004161 auto *cb_context = GetAccessContext(commandBuffer);
4162 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004163 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004164 auto *context = cb_context->GetCurrentAccessContext();
4165
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004166 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4167 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004168
4169 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4170 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4171 if (src_buffer) {
4172 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004173 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004174 }
4175 if (dst_buffer) {
4176 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004177 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004178 }
4179 }
4180}
4181
Tony-LunarGef035472021-11-02 10:23:33 -06004182void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4183 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4184}
4185
4186void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4187 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4188}
4189
John Zulauf5c5e88d2019-12-26 11:22:02 -07004190bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4191 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4192 const VkImageCopy *pRegions) const {
4193 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004194 const auto *cb_access_context = GetAccessContext(commandBuffer);
4195 assert(cb_access_context);
4196 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004197
John Zulauf3d84f1b2020-03-09 13:33:25 -06004198 const auto *context = cb_access_context->GetCurrentAccessContext();
4199 assert(context);
4200 if (!context) return skip;
4201
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004202 auto src_image = Get<IMAGE_STATE>(srcImage);
4203 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004204 for (uint32_t region = 0; region < regionCount; region++) {
4205 const auto &copy_region = pRegions[region];
4206 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004207 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004208 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004209 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004210 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004211 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004212 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004213 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004214 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004215 }
4216
4217 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004218 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004219 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004220 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004221 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004222 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004223 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004224 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004225 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004226 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004227 }
4228 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004229
John Zulauf5c5e88d2019-12-26 11:22:02 -07004230 return skip;
4231}
4232
4233void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4234 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4235 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004236 auto *cb_access_context = GetAccessContext(commandBuffer);
4237 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004238 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004239 auto *context = cb_access_context->GetCurrentAccessContext();
4240 assert(context);
4241
Jeremy Gebben9f537102021-10-05 16:37:12 -06004242 auto src_image = Get<IMAGE_STATE>(srcImage);
4243 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004244
4245 for (uint32_t region = 0; region < regionCount; region++) {
4246 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004247 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004248 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004249 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004250 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004251 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004252 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004253 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004254 }
4255 }
4256}
4257
Tony-LunarGb61514a2021-11-02 12:36:51 -06004258bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4259 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004260 bool skip = false;
4261 const auto *cb_access_context = GetAccessContext(commandBuffer);
4262 assert(cb_access_context);
4263 if (!cb_access_context) return skip;
4264
4265 const auto *context = cb_access_context->GetCurrentAccessContext();
4266 assert(context);
4267 if (!context) return skip;
4268
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004269 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4270 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004271
Jeff Leger178b1e52020-10-05 12:22:23 -04004272 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4273 const auto &copy_region = pCopyImageInfo->pRegions[region];
4274 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004275 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004276 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004277 if (hazard.hazard) {
4278 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004279 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004280 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004281 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004282 }
4283 }
4284
4285 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004286 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004287 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004288 if (hazard.hazard) {
4289 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004290 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004291 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004292 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004293 }
4294 if (skip) break;
4295 }
4296 }
4297
4298 return skip;
4299}
4300
Tony-LunarGb61514a2021-11-02 12:36:51 -06004301bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4302 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4303 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4304}
4305
4306bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4307 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4308}
4309
4310void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004311 auto *cb_access_context = GetAccessContext(commandBuffer);
4312 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004313 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004314 auto *context = cb_access_context->GetCurrentAccessContext();
4315 assert(context);
4316
Jeremy Gebben9f537102021-10-05 16:37:12 -06004317 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4318 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004319
4320 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4321 const auto &copy_region = pCopyImageInfo->pRegions[region];
4322 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004323 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004324 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004325 }
4326 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004327 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004328 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004329 }
4330 }
4331}
4332
Tony-LunarGb61514a2021-11-02 12:36:51 -06004333void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4334 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4335}
4336
4337void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4338 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4339}
4340
John Zulauf9cb530d2019-09-30 14:14:10 -06004341bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4342 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4343 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4344 uint32_t bufferMemoryBarrierCount,
4345 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4346 uint32_t imageMemoryBarrierCount,
4347 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4348 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004349 const auto *cb_access_context = GetAccessContext(commandBuffer);
4350 assert(cb_access_context);
4351 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004352
John Zulauf36ef9282021-02-02 11:47:24 -07004353 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4354 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4355 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4356 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004357 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004358 return skip;
4359}
4360
4361void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4362 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4363 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4364 uint32_t bufferMemoryBarrierCount,
4365 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4366 uint32_t imageMemoryBarrierCount,
4367 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004368 auto *cb_access_context = GetAccessContext(commandBuffer);
4369 assert(cb_access_context);
4370 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004371
John Zulauf1bf30522021-09-03 15:39:06 -06004372 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4373 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4374 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4375 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004376}
4377
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004378bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4379 const VkDependencyInfoKHR *pDependencyInfo) const {
4380 bool skip = false;
4381 const auto *cb_access_context = GetAccessContext(commandBuffer);
4382 assert(cb_access_context);
4383 if (!cb_access_context) return skip;
4384
4385 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4386 skip = pipeline_barrier.Validate(*cb_access_context);
4387 return skip;
4388}
4389
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004390bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4391 const VkDependencyInfo *pDependencyInfo) const {
4392 bool skip = false;
4393 const auto *cb_access_context = GetAccessContext(commandBuffer);
4394 assert(cb_access_context);
4395 if (!cb_access_context) return skip;
4396
4397 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4398 skip = pipeline_barrier.Validate(*cb_access_context);
4399 return skip;
4400}
4401
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004402void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4403 auto *cb_access_context = GetAccessContext(commandBuffer);
4404 assert(cb_access_context);
4405 if (!cb_access_context) return;
4406
John Zulauf1bf30522021-09-03 15:39:06 -06004407 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4408 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004409}
4410
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004411void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4412 auto *cb_access_context = GetAccessContext(commandBuffer);
4413 assert(cb_access_context);
4414 if (!cb_access_context) return;
4415
4416 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4417 *pDependencyInfo);
4418}
4419
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004420void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004421 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004422 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004423
John Zulauf5f13a792020-03-10 07:31:21 -06004424 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4425 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004426 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004427 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4428 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004429
John Zulauf1d5f9c12022-05-13 14:51:08 -06004430 QueueId queue_id = QueueSyncState::kQueueIdBase;
4431 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004432 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004433 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004434 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4435 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004436}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004437
John Zulauf355e49b2020-04-24 15:11:15 -06004438bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004439 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004440 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004441 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004442 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004443 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004444 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004445 }
John Zulauf355e49b2020-04-24 15:11:15 -06004446 return skip;
4447}
4448
4449bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4450 VkSubpassContents contents) const {
4451 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004452 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004453 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004454 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004455 return skip;
4456}
4457
4458bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004459 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004460 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004461 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004462 return skip;
4463}
4464
4465bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4466 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004467 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004468 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004469 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004470 return skip;
4471}
4472
John Zulauf3d84f1b2020-03-09 13:33:25 -06004473void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4474 VkResult result) {
4475 // The state tracker sets up the command buffer state
4476 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4477
4478 // Create/initialize the structure that trackers accesses at the command buffer scope.
4479 auto cb_access_context = GetAccessContext(commandBuffer);
4480 assert(cb_access_context);
4481 cb_access_context->Reset();
4482}
4483
4484void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004485 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004486 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004487 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004488 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004489 }
4490}
4491
4492void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4493 VkSubpassContents contents) {
4494 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004495 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004496 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004497 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004498}
4499
4500void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4501 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4502 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004503 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004504}
4505
4506void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4507 const VkRenderPassBeginInfo *pRenderPassBegin,
4508 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4509 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004510 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004511}
4512
Mike Schuchardt2df08912020-12-15 16:28:09 -08004513bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004514 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004515 bool skip = false;
4516
4517 auto cb_context = GetAccessContext(commandBuffer);
4518 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004519 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004520 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004521 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004522}
4523
4524bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4525 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004526 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004527 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004528 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004529 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4530 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004531 return skip;
4532}
4533
Mike Schuchardt2df08912020-12-15 16:28:09 -08004534bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4535 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004536 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004537 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004538 return skip;
4539}
4540
4541bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4542 const VkSubpassEndInfo *pSubpassEndInfo) const {
4543 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004544 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004545 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004546}
4547
4548void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004549 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004550 auto cb_context = GetAccessContext(commandBuffer);
4551 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004552 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004553
sjfricke0bea06e2022-06-05 09:22:26 +09004554 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004555}
4556
4557void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4558 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004559 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004560 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004561 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004562}
4563
4564void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4565 const VkSubpassEndInfo *pSubpassEndInfo) {
4566 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004567 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004568}
4569
4570void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4571 const VkSubpassEndInfo *pSubpassEndInfo) {
4572 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004573 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004574}
4575
sfricke-samsung85584a72021-09-30 21:43:38 -07004576bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004577 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004578 bool skip = false;
4579
4580 auto cb_context = GetAccessContext(commandBuffer);
4581 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004582 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004583
sjfricke0bea06e2022-06-05 09:22:26 +09004584 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004585 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004586 return skip;
4587}
4588
4589bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4590 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004591 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004592 return skip;
4593}
4594
Mike Schuchardt2df08912020-12-15 16:28:09 -08004595bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004596 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004597 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004598 return skip;
4599}
4600
4601bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004602 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004603 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004604 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004605 return skip;
4606}
4607
sjfricke0bea06e2022-06-05 09:22:26 +09004608void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4609 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004610 // Resolve the all subpass contexts to the command buffer contexts
4611 auto cb_context = GetAccessContext(commandBuffer);
4612 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004613 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004614
sjfricke0bea06e2022-06-05 09:22:26 +09004615 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004616}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004617
John Zulauf33fc1d52020-07-17 11:01:10 -06004618// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4619// updates to a resource which do not conflict at the byte level.
4620// TODO: Revisit this rule to see if it needs to be tighter or looser
4621// TODO: Add programatic control over suppression heuristics
4622bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4623 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4624}
4625
John Zulauf3d84f1b2020-03-09 13:33:25 -06004626void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004627 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004628 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004629}
4630
4631void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004632 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004633 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004634}
4635
4636void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004637 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004638 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004639}
locke-lunarga19c71d2020-03-02 18:17:04 -07004640
sfricke-samsung71f04e32022-03-16 01:21:21 -05004641template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004642bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004643 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4644 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004645 bool skip = false;
4646 const auto *cb_access_context = GetAccessContext(commandBuffer);
4647 assert(cb_access_context);
4648 if (!cb_access_context) return skip;
4649
4650 const auto *context = cb_access_context->GetCurrentAccessContext();
4651 assert(context);
4652 if (!context) return skip;
4653
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004654 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4655 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004656
4657 for (uint32_t region = 0; region < regionCount; region++) {
4658 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004659 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004660 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004661 if (src_buffer) {
4662 ResourceAccessRange src_range =
4663 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004664 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004665 if (hazard.hazard) {
4666 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004667 skip |=
4668 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4669 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4670 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4671 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004672 }
4673 }
4674
Jeremy Gebben40a22942020-12-22 14:22:06 -07004675 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004676 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004677 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004678 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004679 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004680 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004681 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004682 }
4683 if (skip) break;
4684 }
4685 if (skip) break;
4686 }
4687 return skip;
4688}
4689
Jeff Leger178b1e52020-10-05 12:22:23 -04004690bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4691 VkImageLayout dstImageLayout, uint32_t regionCount,
4692 const VkBufferImageCopy *pRegions) const {
4693 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004694 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004695}
4696
4697bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4698 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4699 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4700 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004701 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4702}
4703
4704bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4705 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4706 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4707 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4708 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004709}
4710
sfricke-samsung71f04e32022-03-16 01:21:21 -05004711template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004712void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004713 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4714 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004715 auto *cb_access_context = GetAccessContext(commandBuffer);
4716 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004717
Jeff Leger178b1e52020-10-05 12:22:23 -04004718 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004719 auto *context = cb_access_context->GetCurrentAccessContext();
4720 assert(context);
4721
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004722 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4723 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004724
4725 for (uint32_t region = 0; region < regionCount; region++) {
4726 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004727 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004728 if (src_buffer) {
4729 ResourceAccessRange src_range =
4730 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004731 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004732 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004733 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004734 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004735 }
4736 }
4737}
4738
Jeff Leger178b1e52020-10-05 12:22:23 -04004739void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4740 VkImageLayout dstImageLayout, uint32_t regionCount,
4741 const VkBufferImageCopy *pRegions) {
4742 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004743 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004744}
4745
4746void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4747 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4748 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4749 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4750 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004751 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4752}
4753
4754void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4755 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4756 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4757 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4758 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4759 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004760}
4761
sfricke-samsung71f04e32022-03-16 01:21:21 -05004762template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004763bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004764 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4765 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004766 bool skip = false;
4767 const auto *cb_access_context = GetAccessContext(commandBuffer);
4768 assert(cb_access_context);
4769 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004770
locke-lunarga19c71d2020-03-02 18:17:04 -07004771 const auto *context = cb_access_context->GetCurrentAccessContext();
4772 assert(context);
4773 if (!context) return skip;
4774
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004775 auto src_image = Get<IMAGE_STATE>(srcImage);
4776 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004777 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004778 for (uint32_t region = 0; region < regionCount; region++) {
4779 const auto &copy_region = pRegions[region];
4780 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004781 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004782 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004783 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004784 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004785 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004786 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004787 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004788 }
John Zulauf477700e2021-01-06 11:41:49 -07004789 if (dst_mem) {
4790 ResourceAccessRange dst_range =
4791 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004792 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004793 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004794 skip |=
4795 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4796 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4797 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4798 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004799 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004800 }
4801 }
4802 if (skip) break;
4803 }
4804 return skip;
4805}
4806
Jeff Leger178b1e52020-10-05 12:22:23 -04004807bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4808 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4809 const VkBufferImageCopy *pRegions) const {
4810 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004811 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004812}
4813
4814bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4815 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4816 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4817 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004818 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4819}
4820
4821bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4822 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4823 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4824 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4825 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004826}
4827
sfricke-samsung71f04e32022-03-16 01:21:21 -05004828template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004829void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004830 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004831 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004832 auto *cb_access_context = GetAccessContext(commandBuffer);
4833 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004834
Jeff Leger178b1e52020-10-05 12:22:23 -04004835 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004836 auto *context = cb_access_context->GetCurrentAccessContext();
4837 assert(context);
4838
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004839 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004840 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004841 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004842 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004843
4844 for (uint32_t region = 0; region < regionCount; region++) {
4845 const auto &copy_region = pRegions[region];
4846 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004847 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004848 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004849 if (dst_buffer) {
4850 ResourceAccessRange dst_range =
4851 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004852 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004853 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004854 }
4855 }
4856}
4857
Jeff Leger178b1e52020-10-05 12:22:23 -04004858void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4859 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4860 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004861 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004862}
4863
4864void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4865 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4866 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4867 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4868 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004869 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4870}
4871
4872void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4873 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4874 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4875 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4876 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4877 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004878}
4879
4880template <typename RegionType>
4881bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4882 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004883 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004884 bool skip = false;
4885 const auto *cb_access_context = GetAccessContext(commandBuffer);
4886 assert(cb_access_context);
4887 if (!cb_access_context) return skip;
4888
4889 const auto *context = cb_access_context->GetCurrentAccessContext();
4890 assert(context);
4891 if (!context) return skip;
4892
sjfricke0bea06e2022-06-05 09:22:26 +09004893 const char *caller_name = CommandTypeString(cmd_type);
4894
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004895 auto src_image = Get<IMAGE_STATE>(srcImage);
4896 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004897
4898 for (uint32_t region = 0; region < regionCount; region++) {
4899 const auto &blit_region = pRegions[region];
4900 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004901 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4902 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4903 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4904 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4905 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4906 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004907 auto hazard =
4908 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004909 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004910 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004911 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004912 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004913 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004914 }
4915 }
4916
4917 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004918 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4919 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4920 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4921 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4922 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4923 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004924 auto hazard =
4925 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004926 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004927 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004928 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004929 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004930 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004931 }
4932 if (skip) break;
4933 }
4934 }
4935
4936 return skip;
4937}
4938
Jeff Leger178b1e52020-10-05 12:22:23 -04004939bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4940 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4941 const VkImageBlit *pRegions, VkFilter filter) const {
4942 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004943 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004944}
4945
4946bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4947 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4948 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4949 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004950 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004951}
4952
Tony-LunarG542ae912021-11-04 16:06:44 -06004953bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4954 const VkBlitImageInfo2 *pBlitImageInfo) const {
4955 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004956 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4957 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004958}
4959
Jeff Leger178b1e52020-10-05 12:22:23 -04004960template <typename RegionType>
4961void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4962 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4963 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004964 auto *cb_access_context = GetAccessContext(commandBuffer);
4965 assert(cb_access_context);
4966 auto *context = cb_access_context->GetCurrentAccessContext();
4967 assert(context);
4968
Jeremy Gebben9f537102021-10-05 16:37:12 -06004969 auto src_image = Get<IMAGE_STATE>(srcImage);
4970 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004971
4972 for (uint32_t region = 0; region < regionCount; region++) {
4973 const auto &blit_region = pRegions[region];
4974 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004975 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4976 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4977 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4978 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4979 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4980 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004981 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004982 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004983 }
4984 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004985 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4986 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4987 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4988 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4989 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4990 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004991 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004992 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004993 }
4994 }
4995}
locke-lunarg36ba2592020-04-03 09:42:04 -06004996
Jeff Leger178b1e52020-10-05 12:22:23 -04004997void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4998 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4999 const VkImageBlit *pRegions, VkFilter filter) {
5000 auto *cb_access_context = GetAccessContext(commandBuffer);
5001 assert(cb_access_context);
5002 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
5003 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5004 pRegions, filter);
5005 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
5006}
5007
5008void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
5009 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
5010 auto *cb_access_context = GetAccessContext(commandBuffer);
5011 assert(cb_access_context);
5012 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
5013 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
5014 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
5015 pBlitImageInfo->filter, tag);
5016}
5017
Tony-LunarG542ae912021-11-04 16:06:44 -06005018void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
5019 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
5020 auto *cb_access_context = GetAccessContext(commandBuffer);
5021 assert(cb_access_context);
5022 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
5023 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
5024 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
5025 pBlitImageInfo->filter, tag);
5026}
5027
John Zulauffaea0ee2021-01-14 14:01:32 -07005028bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5029 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
5030 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005031 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005032 bool skip = false;
5033 if (drawCount == 0) return skip;
5034
sjfricke0bea06e2022-06-05 09:22:26 +09005035 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005036 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005037 VkDeviceSize size = struct_size;
5038 if (drawCount == 1 || stride == size) {
5039 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005040 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06005041 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5042 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005043 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005044 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06005045 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005046 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005047 }
5048 } else {
5049 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005050 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06005051 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5052 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005053 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005054 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
5055 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5056 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005057 break;
5058 }
5059 }
5060 }
5061 return skip;
5062}
5063
John Zulauf14940722021-04-12 15:19:02 -06005064void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06005065 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
5066 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005067 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005068 VkDeviceSize size = struct_size;
5069 if (drawCount == 1 || stride == size) {
5070 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005071 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005072 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005073 } else {
5074 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005075 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005076 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
5077 tag);
locke-lunargff255f92020-05-13 18:53:52 -06005078 }
5079 }
5080}
5081
John Zulauffaea0ee2021-01-14 14:01:32 -07005082bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5083 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005084 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005085 bool skip = false;
5086
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005087 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005088 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005089 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5090 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005091 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005092 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5093 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5094 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005095 }
5096 return skip;
5097}
5098
John Zulauf14940722021-04-12 15:19:02 -06005099void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005100 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005101 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005102 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005103}
5104
locke-lunarg36ba2592020-04-03 09:42:04 -06005105bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005106 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005107 const auto *cb_access_context = GetAccessContext(commandBuffer);
5108 assert(cb_access_context);
5109 if (!cb_access_context) return skip;
5110
sjfricke0bea06e2022-06-05 09:22:26 +09005111 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005112 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005113}
5114
5115void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005116 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005117 auto *cb_access_context = GetAccessContext(commandBuffer);
5118 assert(cb_access_context);
5119 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005120
locke-lunarg61870c22020-06-09 14:51:50 -06005121 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005122}
locke-lunarge1a67022020-04-29 00:15:36 -06005123
5124bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005125 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005126 const auto *cb_access_context = GetAccessContext(commandBuffer);
5127 assert(cb_access_context);
5128 if (!cb_access_context) return skip;
5129
5130 const auto *context = cb_access_context->GetCurrentAccessContext();
5131 assert(context);
5132 if (!context) return skip;
5133
sjfricke0bea06e2022-06-05 09:22:26 +09005134 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005135 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005136 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005137 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005138}
5139
5140void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005141 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005142 auto *cb_access_context = GetAccessContext(commandBuffer);
5143 assert(cb_access_context);
5144 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5145 auto *context = cb_access_context->GetCurrentAccessContext();
5146 assert(context);
5147
locke-lunarg61870c22020-06-09 14:51:50 -06005148 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5149 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005150}
5151
5152bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5153 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005154 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005155 const auto *cb_access_context = GetAccessContext(commandBuffer);
5156 assert(cb_access_context);
5157 if (!cb_access_context) return skip;
5158
sjfricke0bea06e2022-06-05 09:22:26 +09005159 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5160 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5161 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005162 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005163}
5164
5165void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5166 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005167 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005168 auto *cb_access_context = GetAccessContext(commandBuffer);
5169 assert(cb_access_context);
5170 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005171
locke-lunarg61870c22020-06-09 14:51:50 -06005172 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5173 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5174 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005175}
5176
5177bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5178 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005179 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005180 const auto *cb_access_context = GetAccessContext(commandBuffer);
5181 assert(cb_access_context);
5182 if (!cb_access_context) return skip;
5183
sjfricke0bea06e2022-06-05 09:22:26 +09005184 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5185 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5186 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005187 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005188}
5189
5190void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5191 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005192 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005193 auto *cb_access_context = GetAccessContext(commandBuffer);
5194 assert(cb_access_context);
5195 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005196
locke-lunarg61870c22020-06-09 14:51:50 -06005197 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5198 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5199 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005200}
5201
5202bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5203 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005204 bool skip = false;
5205 if (drawCount == 0) return skip;
5206
locke-lunargff255f92020-05-13 18:53:52 -06005207 const auto *cb_access_context = GetAccessContext(commandBuffer);
5208 assert(cb_access_context);
5209 if (!cb_access_context) return skip;
5210
5211 const auto *context = cb_access_context->GetCurrentAccessContext();
5212 assert(context);
5213 if (!context) return skip;
5214
sjfricke0bea06e2022-06-05 09:22:26 +09005215 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5216 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005217 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005218 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005219
5220 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5221 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5222 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005223 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005224 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005225}
5226
5227void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5228 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005229 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005230 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005231 auto *cb_access_context = GetAccessContext(commandBuffer);
5232 assert(cb_access_context);
5233 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5234 auto *context = cb_access_context->GetCurrentAccessContext();
5235 assert(context);
5236
locke-lunarg61870c22020-06-09 14:51:50 -06005237 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5238 cb_access_context->RecordDrawSubpassAttachment(tag);
5239 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005240
5241 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5242 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5243 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005244 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005245}
5246
5247bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5248 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005249 bool skip = false;
5250 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005251 const auto *cb_access_context = GetAccessContext(commandBuffer);
5252 assert(cb_access_context);
5253 if (!cb_access_context) return skip;
5254
5255 const auto *context = cb_access_context->GetCurrentAccessContext();
5256 assert(context);
5257 if (!context) return skip;
5258
sjfricke0bea06e2022-06-05 09:22:26 +09005259 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5260 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005261 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005262 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005263
5264 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5265 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5266 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005267 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005268 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005269}
5270
5271void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5272 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005273 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005274 auto *cb_access_context = GetAccessContext(commandBuffer);
5275 assert(cb_access_context);
5276 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5277 auto *context = cb_access_context->GetCurrentAccessContext();
5278 assert(context);
5279
locke-lunarg61870c22020-06-09 14:51:50 -06005280 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5281 cb_access_context->RecordDrawSubpassAttachment(tag);
5282 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005283
5284 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5285 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5286 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005287 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005288}
5289
5290bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5291 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005292 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005293 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005294 const auto *cb_access_context = GetAccessContext(commandBuffer);
5295 assert(cb_access_context);
5296 if (!cb_access_context) return skip;
5297
5298 const auto *context = cb_access_context->GetCurrentAccessContext();
5299 assert(context);
5300 if (!context) return skip;
5301
sjfricke0bea06e2022-06-05 09:22:26 +09005302 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5303 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005304 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005305 maxDrawCount, stride, cmd_type);
5306 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005307
5308 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5309 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5310 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005311 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005312 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005313}
5314
5315bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5316 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5317 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005318 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005319 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005320}
5321
sfricke-samsung85584a72021-09-30 21:43:38 -07005322void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5323 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5324 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005325 auto *cb_access_context = GetAccessContext(commandBuffer);
5326 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005327 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005328 auto *context = cb_access_context->GetCurrentAccessContext();
5329 assert(context);
5330
locke-lunarg61870c22020-06-09 14:51:50 -06005331 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5332 cb_access_context->RecordDrawSubpassAttachment(tag);
5333 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5334 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005335
5336 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5337 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5338 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005339 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005340}
5341
sfricke-samsung85584a72021-09-30 21:43:38 -07005342void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5343 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5344 uint32_t stride) {
5345 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5346 stride);
5347 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5348 CMD_DRAWINDIRECTCOUNT);
5349}
locke-lunarge1a67022020-04-29 00:15:36 -06005350bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5351 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5352 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005353 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005354 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005355}
5356
5357void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5358 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5359 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005360 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5361 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005362 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5363 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005364}
5365
5366bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5367 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5368 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005369 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005370 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005371}
5372
5373void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5374 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5375 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005376 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5377 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005378 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5379 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005380}
5381
5382bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5383 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005384 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005385 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005386 const auto *cb_access_context = GetAccessContext(commandBuffer);
5387 assert(cb_access_context);
5388 if (!cb_access_context) return skip;
5389
5390 const auto *context = cb_access_context->GetCurrentAccessContext();
5391 assert(context);
5392 if (!context) return skip;
5393
sjfricke0bea06e2022-06-05 09:22:26 +09005394 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5395 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005396 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005397 offset, maxDrawCount, stride, cmd_type);
5398 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005399
5400 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5401 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5402 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005403 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005404 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005405}
5406
5407bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5408 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5409 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005410 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005411 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005412}
5413
sfricke-samsung85584a72021-09-30 21:43:38 -07005414void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5415 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5416 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005417 auto *cb_access_context = GetAccessContext(commandBuffer);
5418 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005419 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005420 auto *context = cb_access_context->GetCurrentAccessContext();
5421 assert(context);
5422
locke-lunarg61870c22020-06-09 14:51:50 -06005423 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5424 cb_access_context->RecordDrawSubpassAttachment(tag);
5425 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5426 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005427
5428 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5429 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005430 // We will update the index and vertex buffer in SubmitQueue in the future.
5431 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005432}
5433
sfricke-samsung85584a72021-09-30 21:43:38 -07005434void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5435 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5436 uint32_t maxDrawCount, uint32_t stride) {
5437 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5438 maxDrawCount, stride);
5439 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5440 CMD_DRAWINDEXEDINDIRECTCOUNT);
5441}
5442
locke-lunarge1a67022020-04-29 00:15:36 -06005443bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5444 VkDeviceSize offset, VkBuffer countBuffer,
5445 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5446 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005447 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005448 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005449}
5450
5451void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5452 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5453 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005454 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5455 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005456 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5457 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005458}
5459
5460bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5461 VkDeviceSize offset, VkBuffer countBuffer,
5462 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5463 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005464 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005465 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005466}
5467
5468void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5469 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5470 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005471 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5472 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005473 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5474 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005475}
5476
5477bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5478 const VkClearColorValue *pColor, uint32_t rangeCount,
5479 const VkImageSubresourceRange *pRanges) const {
5480 bool skip = false;
5481 const auto *cb_access_context = GetAccessContext(commandBuffer);
5482 assert(cb_access_context);
5483 if (!cb_access_context) return skip;
5484
5485 const auto *context = cb_access_context->GetCurrentAccessContext();
5486 assert(context);
5487 if (!context) return skip;
5488
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005489 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005490
5491 for (uint32_t index = 0; index < rangeCount; index++) {
5492 const auto &range = pRanges[index];
5493 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005494 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005495 if (hazard.hazard) {
5496 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005497 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005498 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005499 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005500 }
5501 }
5502 }
5503 return skip;
5504}
5505
5506void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5507 const VkClearColorValue *pColor, uint32_t rangeCount,
5508 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005509 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005510 auto *cb_access_context = GetAccessContext(commandBuffer);
5511 assert(cb_access_context);
5512 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5513 auto *context = cb_access_context->GetCurrentAccessContext();
5514 assert(context);
5515
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005516 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005517
5518 for (uint32_t index = 0; index < rangeCount; index++) {
5519 const auto &range = pRanges[index];
5520 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005521 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005522 }
5523 }
5524}
5525
5526bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5527 VkImageLayout imageLayout,
5528 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5529 const VkImageSubresourceRange *pRanges) const {
5530 bool skip = false;
5531 const auto *cb_access_context = GetAccessContext(commandBuffer);
5532 assert(cb_access_context);
5533 if (!cb_access_context) return skip;
5534
5535 const auto *context = cb_access_context->GetCurrentAccessContext();
5536 assert(context);
5537 if (!context) return skip;
5538
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005539 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005540
5541 for (uint32_t index = 0; index < rangeCount; index++) {
5542 const auto &range = pRanges[index];
5543 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005544 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005545 if (hazard.hazard) {
5546 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005547 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005548 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005549 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005550 }
5551 }
5552 }
5553 return skip;
5554}
5555
5556void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5557 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5558 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005559 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005560 auto *cb_access_context = GetAccessContext(commandBuffer);
5561 assert(cb_access_context);
5562 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5563 auto *context = cb_access_context->GetCurrentAccessContext();
5564 assert(context);
5565
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005566 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005567
5568 for (uint32_t index = 0; index < rangeCount; index++) {
5569 const auto &range = pRanges[index];
5570 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005571 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005572 }
5573 }
5574}
5575
5576bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5577 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5578 VkDeviceSize dstOffset, VkDeviceSize stride,
5579 VkQueryResultFlags flags) const {
5580 bool skip = false;
5581 const auto *cb_access_context = GetAccessContext(commandBuffer);
5582 assert(cb_access_context);
5583 if (!cb_access_context) return skip;
5584
5585 const auto *context = cb_access_context->GetCurrentAccessContext();
5586 assert(context);
5587 if (!context) return skip;
5588
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005589 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005590
5591 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005592 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005593 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005594 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005595 skip |=
5596 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5597 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005598 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005599 }
5600 }
locke-lunargff255f92020-05-13 18:53:52 -06005601
5602 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005603 return skip;
5604}
5605
5606void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5607 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5608 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005609 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5610 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005611 auto *cb_access_context = GetAccessContext(commandBuffer);
5612 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005613 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005614 auto *context = cb_access_context->GetCurrentAccessContext();
5615 assert(context);
5616
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005617 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005618
5619 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005620 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005621 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005622 }
locke-lunargff255f92020-05-13 18:53:52 -06005623
5624 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005625}
5626
5627bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5628 VkDeviceSize size, uint32_t data) const {
5629 bool skip = false;
5630 const auto *cb_access_context = GetAccessContext(commandBuffer);
5631 assert(cb_access_context);
5632 if (!cb_access_context) return skip;
5633
5634 const auto *context = cb_access_context->GetCurrentAccessContext();
5635 assert(context);
5636 if (!context) return skip;
5637
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005638 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005639
5640 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005641 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005642 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005643 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005644 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005645 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005646 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005647 }
5648 }
5649 return skip;
5650}
5651
5652void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5653 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005654 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005655 auto *cb_access_context = GetAccessContext(commandBuffer);
5656 assert(cb_access_context);
5657 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5658 auto *context = cb_access_context->GetCurrentAccessContext();
5659 assert(context);
5660
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005661 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005662
5663 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005664 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005665 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005666 }
5667}
5668
5669bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5670 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5671 const VkImageResolve *pRegions) const {
5672 bool skip = false;
5673 const auto *cb_access_context = GetAccessContext(commandBuffer);
5674 assert(cb_access_context);
5675 if (!cb_access_context) return skip;
5676
5677 const auto *context = cb_access_context->GetCurrentAccessContext();
5678 assert(context);
5679 if (!context) return skip;
5680
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005681 auto src_image = Get<IMAGE_STATE>(srcImage);
5682 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005683
5684 for (uint32_t region = 0; region < regionCount; region++) {
5685 const auto &resolve_region = pRegions[region];
5686 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005687 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005688 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005689 if (hazard.hazard) {
5690 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005691 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005692 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005693 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005694 }
5695 }
5696
5697 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005698 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005699 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005700 if (hazard.hazard) {
5701 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005702 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005703 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005704 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005705 }
5706 if (skip) break;
5707 }
5708 }
5709
5710 return skip;
5711}
5712
5713void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5714 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5715 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005716 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5717 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005718 auto *cb_access_context = GetAccessContext(commandBuffer);
5719 assert(cb_access_context);
5720 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5721 auto *context = cb_access_context->GetCurrentAccessContext();
5722 assert(context);
5723
Jeremy Gebben9f537102021-10-05 16:37:12 -06005724 auto src_image = Get<IMAGE_STATE>(srcImage);
5725 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005726
5727 for (uint32_t region = 0; region < regionCount; region++) {
5728 const auto &resolve_region = pRegions[region];
5729 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005730 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005731 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005732 }
5733 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005734 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005735 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005736 }
5737 }
5738}
5739
Tony-LunarG562fc102021-11-12 13:58:35 -07005740bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5741 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005742 bool skip = false;
5743 const auto *cb_access_context = GetAccessContext(commandBuffer);
5744 assert(cb_access_context);
5745 if (!cb_access_context) return skip;
5746
5747 const auto *context = cb_access_context->GetCurrentAccessContext();
5748 assert(context);
5749 if (!context) return skip;
5750
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005751 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5752 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005753
5754 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5755 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5756 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005757 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005758 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005759 if (hazard.hazard) {
5760 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005761 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005762 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005763 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005764 }
5765 }
5766
5767 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005768 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005769 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005770 if (hazard.hazard) {
5771 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005772 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005773 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005774 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005775 }
5776 if (skip) break;
5777 }
5778 }
5779
5780 return skip;
5781}
5782
Tony-LunarG562fc102021-11-12 13:58:35 -07005783bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5784 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5785 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5786}
5787
5788bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5789 const VkResolveImageInfo2 *pResolveImageInfo) const {
5790 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5791}
5792
5793void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5794 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005795 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5796 auto *cb_access_context = GetAccessContext(commandBuffer);
5797 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005798 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005799 auto *context = cb_access_context->GetCurrentAccessContext();
5800 assert(context);
5801
Jeremy Gebben9f537102021-10-05 16:37:12 -06005802 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5803 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005804
5805 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5806 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5807 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005808 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005809 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005810 }
5811 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005812 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005813 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005814 }
5815 }
5816}
5817
Tony-LunarG562fc102021-11-12 13:58:35 -07005818void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5819 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5820 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5821}
5822
5823void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5824 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5825}
5826
locke-lunarge1a67022020-04-29 00:15:36 -06005827bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5828 VkDeviceSize dataSize, const void *pData) const {
5829 bool skip = false;
5830 const auto *cb_access_context = GetAccessContext(commandBuffer);
5831 assert(cb_access_context);
5832 if (!cb_access_context) return skip;
5833
5834 const auto *context = cb_access_context->GetCurrentAccessContext();
5835 assert(context);
5836 if (!context) return skip;
5837
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005838 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005839
5840 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005841 // VK_WHOLE_SIZE not allowed
5842 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005843 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005844 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005845 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005846 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005847 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005848 }
5849 }
5850 return skip;
5851}
5852
5853void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5854 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005855 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005856 auto *cb_access_context = GetAccessContext(commandBuffer);
5857 assert(cb_access_context);
5858 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5859 auto *context = cb_access_context->GetCurrentAccessContext();
5860 assert(context);
5861
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005862 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005863
5864 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005865 // VK_WHOLE_SIZE not allowed
5866 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005867 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005868 }
5869}
locke-lunargff255f92020-05-13 18:53:52 -06005870
5871bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5872 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5873 bool skip = false;
5874 const auto *cb_access_context = GetAccessContext(commandBuffer);
5875 assert(cb_access_context);
5876 if (!cb_access_context) return skip;
5877
5878 const auto *context = cb_access_context->GetCurrentAccessContext();
5879 assert(context);
5880 if (!context) return skip;
5881
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005882 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005883
5884 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005885 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005886 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005887 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005888 skip |=
5889 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5890 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005891 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005892 }
5893 }
5894 return skip;
5895}
5896
5897void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5898 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005899 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005900 auto *cb_access_context = GetAccessContext(commandBuffer);
5901 assert(cb_access_context);
5902 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5903 auto *context = cb_access_context->GetCurrentAccessContext();
5904 assert(context);
5905
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005906 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005907
5908 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005909 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005910 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005911 }
5912}
John Zulauf49beb112020-11-04 16:06:31 -07005913
5914bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5915 bool skip = false;
5916 const auto *cb_context = GetAccessContext(commandBuffer);
5917 assert(cb_context);
5918 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005919 const auto *access_context = cb_context->GetCurrentAccessContext();
5920 assert(access_context);
5921 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005922
John Zulaufe0757ba2022-06-10 16:51:45 -06005923 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005924 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005925}
5926
5927void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5928 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5929 auto *cb_context = GetAccessContext(commandBuffer);
5930 assert(cb_context);
5931 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005932
5933 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5934 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005935}
5936
John Zulauf4edde622021-02-15 08:54:50 -07005937bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5938 const VkDependencyInfoKHR *pDependencyInfo) const {
5939 bool skip = false;
5940 const auto *cb_context = GetAccessContext(commandBuffer);
5941 assert(cb_context);
5942 if (!cb_context || !pDependencyInfo) return skip;
5943
John Zulaufe0757ba2022-06-10 16:51:45 -06005944 const auto *access_context = cb_context->GetCurrentAccessContext();
5945 assert(access_context);
5946 if (!access_context) return skip;
5947
5948 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005949 return set_event_op.Validate(*cb_context);
5950}
5951
Tony-LunarGc43525f2021-11-15 16:12:38 -07005952bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5953 const VkDependencyInfo *pDependencyInfo) const {
5954 bool skip = false;
5955 const auto *cb_context = GetAccessContext(commandBuffer);
5956 assert(cb_context);
5957 if (!cb_context || !pDependencyInfo) return skip;
5958
John Zulaufe0757ba2022-06-10 16:51:45 -06005959 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005960 return set_event_op.Validate(*cb_context);
5961}
5962
John Zulauf4edde622021-02-15 08:54:50 -07005963void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5964 const VkDependencyInfoKHR *pDependencyInfo) {
5965 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5966 auto *cb_context = GetAccessContext(commandBuffer);
5967 assert(cb_context);
5968 if (!cb_context || !pDependencyInfo) return;
5969
John Zulaufe0757ba2022-06-10 16:51:45 -06005970 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5971 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005972}
5973
Tony-LunarGc43525f2021-11-15 16:12:38 -07005974void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5975 const VkDependencyInfo *pDependencyInfo) {
5976 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5977 auto *cb_context = GetAccessContext(commandBuffer);
5978 assert(cb_context);
5979 if (!cb_context || !pDependencyInfo) return;
5980
John Zulaufe0757ba2022-06-10 16:51:45 -06005981 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5982 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005983}
5984
John Zulauf49beb112020-11-04 16:06:31 -07005985bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5986 VkPipelineStageFlags stageMask) const {
5987 bool skip = false;
5988 const auto *cb_context = GetAccessContext(commandBuffer);
5989 assert(cb_context);
5990 if (!cb_context) return skip;
5991
John Zulauf36ef9282021-02-02 11:47:24 -07005992 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005993 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005994}
5995
5996void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5997 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5998 auto *cb_context = GetAccessContext(commandBuffer);
5999 assert(cb_context);
6000 if (!cb_context) return;
6001
John Zulauf1bf30522021-09-03 15:39:06 -06006002 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07006003}
6004
John Zulauf4edde622021-02-15 08:54:50 -07006005bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6006 VkPipelineStageFlags2KHR stageMask) const {
6007 bool skip = false;
6008 const auto *cb_context = GetAccessContext(commandBuffer);
6009 assert(cb_context);
6010 if (!cb_context) return skip;
6011
6012 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
6013 return reset_event_op.Validate(*cb_context);
6014}
6015
Tony-LunarGa2662db2021-11-16 07:26:24 -07006016bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
6017 VkPipelineStageFlags2 stageMask) const {
6018 bool skip = false;
6019 const auto *cb_context = GetAccessContext(commandBuffer);
6020 assert(cb_context);
6021 if (!cb_context) return skip;
6022
6023 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
6024 return reset_event_op.Validate(*cb_context);
6025}
6026
John Zulauf4edde622021-02-15 08:54:50 -07006027void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6028 VkPipelineStageFlags2KHR stageMask) {
6029 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
6030 auto *cb_context = GetAccessContext(commandBuffer);
6031 assert(cb_context);
6032 if (!cb_context) return;
6033
John Zulauf1bf30522021-09-03 15:39:06 -06006034 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07006035}
6036
Tony-LunarGa2662db2021-11-16 07:26:24 -07006037void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
6038 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
6039 auto *cb_context = GetAccessContext(commandBuffer);
6040 assert(cb_context);
6041 if (!cb_context) return;
6042
6043 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
6044}
6045
John Zulauf49beb112020-11-04 16:06:31 -07006046bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6047 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6048 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6049 uint32_t bufferMemoryBarrierCount,
6050 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6051 uint32_t imageMemoryBarrierCount,
6052 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
6053 bool skip = false;
6054 const auto *cb_context = GetAccessContext(commandBuffer);
6055 assert(cb_context);
6056 if (!cb_context) return skip;
6057
John Zulauf36ef9282021-02-02 11:47:24 -07006058 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
6059 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
6060 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07006061 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07006062}
6063
6064void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6065 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6066 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6067 uint32_t bufferMemoryBarrierCount,
6068 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6069 uint32_t imageMemoryBarrierCount,
6070 const VkImageMemoryBarrier *pImageMemoryBarriers) {
6071 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
6072 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
6073 imageMemoryBarrierCount, pImageMemoryBarriers);
6074
6075 auto *cb_context = GetAccessContext(commandBuffer);
6076 assert(cb_context);
6077 if (!cb_context) return;
6078
John Zulauf1bf30522021-09-03 15:39:06 -06006079 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06006080 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06006081 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07006082}
6083
John Zulauf4edde622021-02-15 08:54:50 -07006084bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6085 const VkDependencyInfoKHR *pDependencyInfos) const {
6086 bool skip = false;
6087 const auto *cb_context = GetAccessContext(commandBuffer);
6088 assert(cb_context);
6089 if (!cb_context) return skip;
6090
6091 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6092 skip |= wait_events_op.Validate(*cb_context);
6093 return skip;
6094}
6095
6096void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6097 const VkDependencyInfoKHR *pDependencyInfos) {
6098 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6099
6100 auto *cb_context = GetAccessContext(commandBuffer);
6101 assert(cb_context);
6102 if (!cb_context) return;
6103
John Zulauf1bf30522021-09-03 15:39:06 -06006104 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6105 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006106}
6107
Tony-LunarG1364cf52021-11-17 16:10:11 -07006108bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6109 const VkDependencyInfo *pDependencyInfos) const {
6110 bool skip = false;
6111 const auto *cb_context = GetAccessContext(commandBuffer);
6112 assert(cb_context);
6113 if (!cb_context) return skip;
6114
6115 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6116 skip |= wait_events_op.Validate(*cb_context);
6117 return skip;
6118}
6119
6120void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6121 const VkDependencyInfo *pDependencyInfos) {
6122 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6123
6124 auto *cb_context = GetAccessContext(commandBuffer);
6125 assert(cb_context);
6126 if (!cb_context) return;
6127
6128 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6129 pDependencyInfos);
6130}
6131
John Zulauf4a6105a2020-11-17 15:11:05 -07006132void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006133 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006134 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006135 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006136}
6137
6138// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006139SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006140 IgnoreReason reason = NotIgnored;
6141
sjfricke0bea06e2022-06-05 09:22:26 +09006142 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006143 reason = SetVsWait2;
6144 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6145 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006146 } else if (unsynchronized_set) {
6147 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006148 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006149 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006150 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006151 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006152 } else {
6153 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006154 }
6155
6156 return reason;
6157}
6158
Jeremy Gebben40a22942020-12-22 14:22:06 -07006159bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006160 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6161 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6162 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006163}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006164
sjfricke0bea06e2022-06-05 09:22:26 +09006165SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006166 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6167 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006168 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6169 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6170 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006171 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006172 auto &barrier_set = barriers_[0];
6173 barrier_set.dependency_flags = dependencyFlags;
6174 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6175 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006176 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006177 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6178 pMemoryBarriers);
6179 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6180 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6181 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6182 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006183}
6184
sjfricke0bea06e2022-06-05 09:22:26 +09006185SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006186 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006187 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006188 for (uint32_t i = 0; i < event_count; i++) {
6189 const auto &dep_info = dep_infos[i];
6190 auto &barrier_set = barriers_[i];
6191 barrier_set.dependency_flags = dep_info.dependencyFlags;
6192 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6193 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6194 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6195 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6196 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6197 dep_info.pMemoryBarriers);
6198 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6199 dep_info.pBufferMemoryBarriers);
6200 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6201 dep_info.pImageMemoryBarriers);
6202 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006203}
6204
sjfricke0bea06e2022-06-05 09:22:26 +09006205SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006206 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6207 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6208 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6209 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6210 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006211 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6212 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6213 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006214
sjfricke0bea06e2022-06-05 09:22:26 +09006215SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006216 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006217 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006218
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006219bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6220 bool skip = false;
6221 const auto *context = cb_context.GetCurrentAccessContext();
6222 assert(context);
6223 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006224 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6225
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006226 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006227 const auto &barrier_set = barriers_[0];
6228 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6229 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6230 const auto *image_state = image_barrier.image.get();
6231 if (!image_state) continue;
6232 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6233 if (hazard.hazard) {
6234 // PHASE1 TODO -- add tag information to log msg when useful.
6235 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006236 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006237 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6238 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6239 string_SyncHazard(hazard.hazard), image_barrier.index,
6240 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006241 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006242 }
6243 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006244 return skip;
6245}
6246
John Zulaufd5115702021-01-18 12:34:33 -07006247struct SyncOpPipelineBarrierFunctorFactory {
6248 using BarrierOpFunctor = PipelineBarrierOp;
6249 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6250 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6251 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6252 using BufferRange = ResourceAccessRange;
6253 using ImageRange = subresource_adapter::ImageRangeGenerator;
6254 using GlobalRange = ResourceAccessRange;
6255
John Zulauf00119522022-05-23 19:07:42 -06006256 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6257 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006258 }
John Zulauf14940722021-04-12 15:19:02 -06006259 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006260 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6261 }
John Zulauf00119522022-05-23 19:07:42 -06006262 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6263 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006264 }
6265
6266 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6267 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6268 const auto base_address = ResourceBaseAddress(buffer);
6269 return (range + base_address);
6270 }
John Zulauf110413c2021-03-20 05:38:38 -06006271 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006272 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006273
6274 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006275 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006276 return range_gen;
6277 }
6278 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6279};
6280
6281template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006282void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6283 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006284 for (const auto &barrier : barriers) {
6285 const auto *state = barrier.GetState();
6286 if (state) {
6287 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006288 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006289 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6290 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6291 }
6292 }
6293}
6294
6295template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006296void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6297 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006298 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6299 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006300 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006301 }
6302 for (const auto address_type : kAddressTypes) {
6303 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6304 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6305 }
6306}
6307
John Zulaufdab327f2022-07-08 12:02:05 -06006308ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006309 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006310 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006311 return tag;
6312}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006313
John Zulauf0223f142022-07-06 09:05:39 -06006314void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006315 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006316 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6317 assert(barriers_.size() == 1);
6318 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006319 if (!exec_context.ValidForSyncOps()) return;
6320
6321 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6322 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6323 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006324 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6325 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6326 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006327 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006328 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006329 } else {
6330 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006331 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006332 }
6333 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006334}
6335
John Zulauf8eda1562021-04-13 17:06:41 -06006336bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006337 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006338 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6339 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006340 return false;
6341}
6342
John Zulauf4edde622021-02-15 08:54:50 -07006343void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6344 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6345 const VkMemoryBarrier *barriers) {
6346 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006347 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006348 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006349 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006350 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006351 }
6352 if (0 == memory_barrier_count) {
6353 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006354 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006355 }
John Zulauf4edde622021-02-15 08:54:50 -07006356 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006357}
6358
John Zulauf4edde622021-02-15 08:54:50 -07006359void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6360 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6361 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6362 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006363 for (uint32_t index = 0; index < barrier_count; index++) {
6364 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006365 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006366 if (buffer) {
6367 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6368 const auto range = MakeRange(barrier.offset, barrier_size);
6369 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006370 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006371 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006372 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006373 }
6374 }
6375}
6376
John Zulauf4edde622021-02-15 08:54:50 -07006377void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006378 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006379 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006380 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006381 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006382 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6383 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6384 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006385 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006386 }
John Zulauf4edde622021-02-15 08:54:50 -07006387 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006388}
6389
John Zulauf4edde622021-02-15 08:54:50 -07006390void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6391 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006392 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006393 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006394 for (uint32_t index = 0; index < barrier_count; index++) {
6395 const auto &barrier = barriers[index];
6396 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6397 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006398 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006399 if (buffer) {
6400 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6401 const auto range = MakeRange(barrier.offset, barrier_size);
6402 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006403 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006404 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006405 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006406 }
6407 }
6408}
6409
John Zulauf4edde622021-02-15 08:54:50 -07006410void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6411 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6412 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6413 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006414 for (uint32_t index = 0; index < barrier_count; index++) {
6415 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006416 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006417 if (image) {
6418 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6419 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006420 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006421 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006422 image_memory_barriers.emplace_back();
6423 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006424 }
6425 }
6426}
John Zulaufd5115702021-01-18 12:34:33 -07006427
John Zulauf4edde622021-02-15 08:54:50 -07006428void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6429 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006430 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006431 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006432 for (uint32_t index = 0; index < barrier_count; index++) {
6433 const auto &barrier = barriers[index];
6434 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6435 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006436 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006437 if (image) {
6438 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6439 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006440 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006441 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006442 image_memory_barriers.emplace_back();
6443 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006444 }
6445 }
6446}
6447
sjfricke0bea06e2022-06-05 09:22:26 +09006448SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6449 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6450 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6451 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6452 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6453 const VkImageMemoryBarrier *pImageMemoryBarriers)
6454 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006455 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6456 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006457 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006458}
6459
sjfricke0bea06e2022-06-05 09:22:26 +09006460SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6461 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6462 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006463 MakeEventsList(sync_state, eventCount, pEvents);
6464 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6465}
6466
John Zulauf610e28c2021-08-03 17:46:23 -06006467const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6468
John Zulaufd5115702021-01-18 12:34:33 -07006469bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006470 bool skip = false;
6471 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006472 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006473
John Zulauf610e28c2021-08-03 17:46:23 -06006474 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006475 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6476 const auto &barrier_set = barriers_[barrier_set_index];
6477 if (barrier_set.single_exec_scope) {
6478 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6479 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6480 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6481 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6482 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6483 } else {
6484 const auto &barriers = barrier_set.memory_barriers;
6485 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6486 const auto &barrier = barriers[barrier_index];
6487 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6488 const std::string vuid =
6489 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6490 skip =
6491 sync_state.LogInfo(command_buffer_handle, vuid,
6492 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6493 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6494 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6495 }
6496 }
6497 }
6498 }
John Zulaufd5115702021-01-18 12:34:33 -07006499 }
6500
John Zulauf610e28c2021-08-03 17:46:23 -06006501 // The rest is common to record time and replay time.
6502 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6503 return skip;
6504}
6505
John Zulaufbb890452021-12-14 11:30:18 -07006506bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006507 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006508 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006509 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006510
Jeremy Gebben40a22942020-12-22 14:22:06 -07006511 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006512 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006513 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006514 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006515 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006516 size_t barrier_set_index = 0;
6517 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006518 for (const auto &event : events_) {
6519 const auto *sync_event = events_context->Get(event.get());
6520 const auto &barrier_set = barriers_[barrier_set_index];
6521 if (!sync_event) {
6522 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6523 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6524 // new validation error... wait without previously submitted set event...
6525 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 -07006526 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006527 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006528 }
John Zulauf610e28c2021-08-03 17:46:23 -06006529
6530 // For replay calls, don't revalidate "same command buffer" events
6531 if (sync_event->last_command_tag > base_tag) continue;
6532
John Zulauf78394fc2021-07-12 15:41:40 -06006533 const auto event_handle = sync_event->event->event();
6534 // TODO add "destroyed" checks
6535
John Zulaufe0757ba2022-06-10 16:51:45 -06006536 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006537 // Only accumulate barrier and event stages if there is a pending set in the current context
6538 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6539 event_stage_masks |= sync_event->scope.mask_param;
6540 }
6541
John Zulauf78394fc2021-07-12 15:41:40 -06006542 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006543
sjfricke0bea06e2022-06-05 09:22:26 +09006544 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006545 if (ignore_reason) {
6546 switch (ignore_reason) {
6547 case SyncEventState::ResetWaitRace:
6548 case SyncEventState::Reset2WaitRace: {
6549 // Four permuations of Reset and Wait calls...
6550 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006551 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006552 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006553 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6554 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006555 }
6556 const char *const message =
6557 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6558 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6559 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006560 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006561 break;
6562 }
6563 case SyncEventState::SetRace: {
6564 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6565 // this event
6566 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6567 const char *const message =
6568 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6569 const char *const reason = "First synchronization scope is undefined.";
6570 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6571 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006572 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006573 break;
6574 }
6575 case SyncEventState::MissingStageBits: {
6576 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6577 // Issue error message that event waited for is not in wait events scope
6578 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6579 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6580 ". Bits missing from srcStageMask %s. %s";
6581 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6582 sync_state.report_data->FormatHandle(event_handle).c_str(),
6583 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006584 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006585 break;
6586 }
6587 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006588 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006589 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6590 sync_state.report_data->FormatHandle(event_handle).c_str(),
6591 CommandTypeString(sync_event->last_command));
6592 break;
6593 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006594 case SyncEventState::MissingSetEvent: {
6595 // TODO: There are conditions at queue submit time where we can definitively say that
6596 // a missing set event is an error. Add those if not captured in CoreChecks
6597 break;
6598 }
John Zulauf78394fc2021-07-12 15:41:40 -06006599 default:
6600 assert(ignore_reason == SyncEventState::NotIgnored);
6601 }
6602 } else if (barrier_set.image_memory_barriers.size()) {
6603 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006604 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006605 assert(context);
6606 for (const auto &image_memory_barrier : image_memory_barriers) {
6607 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6608 const auto *image_state = image_memory_barrier.image.get();
6609 if (!image_state) continue;
6610 const auto &subresource_range = image_memory_barrier.range;
6611 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006612 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6613 src_access_scope, queue_id, *sync_event,
6614 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006615 if (hazard.hazard) {
6616 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6617 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6618 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6619 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006620 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006621 break;
6622 }
6623 }
6624 }
6625 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6626 // 03839
6627 barrier_set_index += barrier_set_incr;
6628 }
John Zulaufd5115702021-01-18 12:34:33 -07006629
6630 // 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 -07006631 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 -07006632 if (extra_stage_bits) {
6633 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006634 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6635 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006636 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006637 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006638 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006639 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006640 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006641 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006642 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006643 " vkCmdSetEvent may be in previously submitted command buffer.");
6644 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006645 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006646 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006647 }
6648 }
6649 return skip;
6650}
6651
6652struct SyncOpWaitEventsFunctorFactory {
6653 using BarrierOpFunctor = WaitEventBarrierOp;
6654 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6655 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6656 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6657 using BufferRange = EventSimpleRangeGenerator;
6658 using ImageRange = EventImageRangeGenerator;
6659 using GlobalRange = EventSimpleRangeGenerator;
6660
6661 // Need to restrict to only valid exec and access scope for this event
6662 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6663 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006664 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006665 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6666 return barrier;
6667 }
John Zulauf00119522022-05-23 19:07:42 -06006668 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006669 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006670 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006671 }
John Zulauf14940722021-04-12 15:19:02 -06006672 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006673 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6674 }
John Zulauf00119522022-05-23 19:07:42 -06006675 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006676 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006677 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006678 }
6679
6680 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6681 const AccessAddressType address_type = GetAccessAddressType(buffer);
6682 const auto base_address = ResourceBaseAddress(buffer);
6683 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6684 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6685 return filtered_range_gen;
6686 }
John Zulauf110413c2021-03-20 05:38:38 -06006687 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006688 if (!SimpleBinding(image)) return ImageRange();
6689 const auto address_type = GetAccessAddressType(image);
6690 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006691 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6692 false);
John Zulaufd5115702021-01-18 12:34:33 -07006693 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6694
6695 return filtered_range_gen;
6696 }
6697 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6698 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6699 }
6700 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6701 SyncEventState *sync_event;
6702};
6703
John Zulaufdab327f2022-07-08 12:02:05 -06006704ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006705 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006706
John Zulauf0223f142022-07-06 09:05:39 -06006707 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006708 return tag;
6709}
6710
John Zulauf0223f142022-07-06 09:05:39 -06006711void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006712 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6713 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6714 // 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 -06006715 if (!exec_context.ValidForSyncOps()) return;
6716 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6717 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6718 const QueueId queue_id = exec_context.GetQueueId();
6719
John Zulaufd5115702021-01-18 12:34:33 -07006720 access_context->ResolvePreviousAccesses();
6721
John Zulauf4edde622021-02-15 08:54:50 -07006722 size_t barrier_set_index = 0;
6723 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6724 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006725 for (auto &event_shared : events_) {
6726 if (!event_shared.get()) continue;
6727 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006728
sjfricke0bea06e2022-06-05 09:22:26 +09006729 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006730 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006731
John Zulauf4edde622021-02-15 08:54:50 -07006732 const auto &barrier_set = barriers_[barrier_set_index];
6733 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006734 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006735 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6736 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6737 // of the barriers is maintained.
6738 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006739 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6740 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6741 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006742
6743 // Apply the global barrier to the event itself (for race condition tracking)
6744 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6745 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6746 sync_event->barriers |= dst.exec_scope;
6747 } else {
6748 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6749 sync_event->barriers = 0U;
6750 }
John Zulauf4edde622021-02-15 08:54:50 -07006751 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006752 }
6753
6754 // Apply the pending barriers
6755 ResolvePendingBarrierFunctor apply_pending_action(tag);
6756 access_context->ApplyToContext(apply_pending_action);
6757}
6758
John Zulauf8eda1562021-04-13 17:06:41 -06006759bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006760 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6761 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006762}
6763
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006764bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6765 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6766 bool skip = false;
6767 const auto *cb_access_context = GetAccessContext(commandBuffer);
6768 assert(cb_access_context);
6769 if (!cb_access_context) return skip;
6770
6771 const auto *context = cb_access_context->GetCurrentAccessContext();
6772 assert(context);
6773 if (!context) return skip;
6774
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006775 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006776
6777 if (dst_buffer) {
6778 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6779 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6780 if (hazard.hazard) {
6781 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6782 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6783 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006784 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006785 }
6786 }
6787 return skip;
6788}
6789
John Zulauf669dfd52021-01-27 17:15:28 -07006790void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006791 events_.reserve(event_count);
6792 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006793 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006794 }
6795}
John Zulauf6ce24372021-01-30 05:56:25 -07006796
sjfricke0bea06e2022-06-05 09:22:26 +09006797SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006798 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006799 : SyncOpBase(cmd_type),
6800 event_(sync_state.Get<EVENT_STATE>(event)),
6801 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006802
John Zulauf1bf30522021-09-03 15:39:06 -06006803bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6804 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6805}
6806
John Zulaufbb890452021-12-14 11:30:18 -07006807bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6808 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006809 assert(events_context);
6810 bool skip = false;
6811 if (!events_context) return skip;
6812
John Zulaufbb890452021-12-14 11:30:18 -07006813 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006814 const auto *sync_event = events_context->Get(event_);
6815 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6816
John Zulauf1bf30522021-09-03 15:39:06 -06006817 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6818
John Zulauf6ce24372021-01-30 05:56:25 -07006819 const char *const set_wait =
6820 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6821 "hazards.";
6822 const char *message = set_wait; // Only one message this call.
6823 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6824 const char *vuid = nullptr;
6825 switch (sync_event->last_command) {
6826 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006827 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006828 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006829 // Needs a barrier between set and reset
6830 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6831 break;
John Zulauf4edde622021-02-15 08:54:50 -07006832 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006833 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006834 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006835 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6836 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6837 break;
6838 }
6839 default:
6840 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006841 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6842 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006843 break;
6844 }
6845 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006846 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6847 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006848 CommandTypeString(sync_event->last_command));
6849 }
6850 }
6851 return skip;
6852}
6853
John Zulaufdab327f2022-07-08 12:02:05 -06006854ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006855 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006856 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006857 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006858}
6859
John Zulauf8eda1562021-04-13 17:06:41 -06006860bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006861 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6862 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006863}
6864
John Zulauf0223f142022-07-06 09:05:39 -06006865void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6866 if (!exec_context.ValidForSyncOps()) return;
6867 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6868
John Zulaufe0757ba2022-06-10 16:51:45 -06006869 auto *sync_event = events_context->GetFromShared(event_);
6870 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6871
6872 // Update the event state
6873 sync_event->last_command = cmd_type_;
6874 sync_event->last_command_tag = tag;
6875 sync_event->unsynchronized_set = CMD_NONE;
6876 sync_event->ResetFirstScope();
6877 sync_event->barriers = 0U;
6878}
John Zulauf8eda1562021-04-13 17:06:41 -06006879
sjfricke0bea06e2022-06-05 09:22:26 +09006880SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006881 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006882 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006883 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006884 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006885 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006886 dep_info_() {
6887 // Snapshot the current access_context for later inspection at wait time.
6888 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6889 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6890 // or Submit time reference.
6891 if (access_context) {
6892 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6893 }
6894}
John Zulauf4edde622021-02-15 08:54:50 -07006895
sjfricke0bea06e2022-06-05 09:22:26 +09006896SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006897 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006898 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006899 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006900 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006901 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006902 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6903 if (access_context) {
6904 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6905 }
6906}
John Zulauf6ce24372021-01-30 05:56:25 -07006907
6908bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006909 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6910}
6911bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006912 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6913 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006914}
6915
John Zulaufbb890452021-12-14 11:30:18 -07006916bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006917 bool skip = false;
6918
John Zulaufbb890452021-12-14 11:30:18 -07006919 const auto &sync_state = exec_context.GetSyncState();
6920 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006921 assert(events_context);
6922 if (!events_context) return skip;
6923
6924 const auto *sync_event = events_context->Get(event_);
6925 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6926
John Zulauf610e28c2021-08-03 17:46:23 -06006927 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6928
John Zulauf6ce24372021-01-30 05:56:25 -07006929 const char *const reset_set =
6930 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6931 "hazards.";
6932 const char *const wait =
6933 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6934
6935 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006936 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006937 const char *message = nullptr;
6938 switch (sync_event->last_command) {
6939 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006940 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006941 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006942 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006943 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006944 message = reset_set;
6945 break;
6946 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006947 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006948 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006949 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006950 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006951 message = reset_set;
6952 break;
6953 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006954 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006955 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006956 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006957 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006958 message = wait;
6959 break;
6960 default:
6961 // The only other valid last command that wasn't one.
6962 assert(sync_event->last_command == CMD_NONE);
6963 break;
6964 }
John Zulauf4edde622021-02-15 08:54:50 -07006965 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006966 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006967 std::string vuid("SYNC-");
6968 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006969 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6970 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006971 CommandTypeString(sync_event->last_command));
6972 }
6973 }
6974
6975 return skip;
6976}
6977
John Zulaufdab327f2022-07-08 12:02:05 -06006978ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006979 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006980 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006981 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006982 assert(recorded_context_);
6983 if (recorded_context_ && events_context) {
6984 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006985 }
6986 return tag;
6987}
John Zulauf6ce24372021-01-30 05:56:25 -07006988
John Zulauf0223f142022-07-06 09:05:39 -06006989void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006990 // Create a copy of the current context, and merge in the state snapshot at record set event time
6991 // 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 -06006992 if (!exec_context.ValidForSyncOps()) return;
6993 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6994 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6995 const QueueId queue_id = exec_context.GetQueueId();
6996
John Zulaufe0757ba2022-06-10 16:51:45 -06006997 auto merged_context = std::make_shared<AccessContext>(*access_context);
6998 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6999 DoRecord(queue_id, tag, merged_context, events_context);
7000}
7001
7002void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
7003 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07007004 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06007005 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07007006
7007 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
7008 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
7009 // any issues caused by naive scope setting here.
7010
7011 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
7012 // Given:
7013 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
7014 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
7015
7016 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
7017 sync_event->unsynchronized_set = sync_event->last_command;
7018 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06007019 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07007020 // We only set the scope if there isn't one
7021 sync_event->scope = src_exec_scope_;
7022
John Zulaufe0757ba2022-06-10 16:51:45 -06007023 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
7024 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07007025 sync_event->unsynchronized_set = CMD_NONE;
7026 sync_event->first_scope_tag = tag;
7027 }
John Zulauf4edde622021-02-15 08:54:50 -07007028 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09007029 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06007030 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07007031 sync_event->barriers = 0U;
7032}
John Zulauf64ffe552021-02-06 10:25:07 -07007033
sjfricke0bea06e2022-06-05 09:22:26 +09007034SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07007035 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07007036 const VkSubpassBeginInfo *pSubpassBeginInfo)
John Zulaufdab327f2022-07-08 12:02:05 -06007037 : SyncOpBase(cmd_type), rp_context_(nullptr) {
John Zulauf64ffe552021-02-06 10:25:07 -07007038 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06007039 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07007040 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007041 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07007042 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06007043 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07007044 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
7045 // Note that this a safe to presist as long as shared_attachments is not cleared
7046 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08007047 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07007048 attachments_.emplace_back(attachment.get());
7049 }
7050 }
7051 if (pSubpassBeginInfo) {
7052 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
7053 }
7054 }
7055}
7056
7057bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7058 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
7059 bool skip = false;
7060
7061 assert(rp_state_.get());
7062 if (nullptr == rp_state_.get()) return skip;
7063 auto &rp_state = *rp_state_.get();
7064
7065 const uint32_t subpass = 0;
7066
7067 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
7068 // hasn't happened yet)
7069 const std::vector<AccessContext> empty_context_vector;
7070 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
7071 cb_context.GetCurrentAccessContext());
7072
7073 // Validate attachment operations
7074 if (attachments_.size() == 0) return skip;
7075 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007076
7077 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7078 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7079 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7080 // operations (though it's currently a messy approach)
7081 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007082 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007083
7084 // Validate load operations if there were no layout transition hazards
7085 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007086 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007087 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007088 }
7089
7090 return skip;
7091}
7092
John Zulaufdab327f2022-07-08 12:02:05 -06007093ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) {
John Zulauf64ffe552021-02-06 10:25:07 -07007094 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007095 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
John Zulaufdab327f2022-07-08 12:02:05 -06007096 const ResourceUsageTag begin_tag =
7097 cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
7098
7099 // Note: this state update must be after RecordBeginRenderPass as there is no current render pass until that function runs
7100 rp_context_ = cb_context->GetCurrentRenderPassContext();
7101
7102 return begin_tag;
John Zulauf64ffe552021-02-06 10:25:07 -07007103}
7104
John Zulauf8eda1562021-04-13 17:06:41 -06007105bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007106 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007107 return false;
7108}
7109
John Zulaufdab327f2022-07-08 12:02:05 -06007110void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7111 // Need to update the exec_contexts state (which for RenderPass operations *must* be a QueueBatchContext, as
7112 // render pass operations are not allowed in secondary command buffers.
7113 const QueueId queue_id = exec_context.GetQueueId();
7114 assert(queue_id != QueueSyncState::kQueueIdInvalid); // Renderpass replay only valid at submit (not exec) time
7115 if (queue_id == QueueSyncState::kQueueIdInvalid) return;
7116
7117 exec_context.BeginRenderPassReplay(*this, tag);
7118}
John Zulauf8eda1562021-04-13 17:06:41 -06007119
sjfricke0bea06e2022-06-05 09:22:26 +09007120SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7121 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7122 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007123 if (pSubpassBeginInfo) {
7124 subpass_begin_info_.initialize(pSubpassBeginInfo);
7125 }
7126 if (pSubpassEndInfo) {
7127 subpass_end_info_.initialize(pSubpassEndInfo);
7128 }
7129}
7130
7131bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7132 bool skip = false;
7133 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7134 if (!renderpass_context) return skip;
7135
sjfricke0bea06e2022-06-05 09:22:26 +09007136 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007137 return skip;
7138}
7139
John Zulaufdab327f2022-07-08 12:02:05 -06007140ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007141 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007142}
7143
7144bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007145 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007146 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007147}
7148
sjfricke0bea06e2022-06-05 09:22:26 +09007149SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7150 const VkSubpassEndInfo *pSubpassEndInfo)
7151 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007152 if (pSubpassEndInfo) {
7153 subpass_end_info_.initialize(pSubpassEndInfo);
7154 }
7155}
7156
John Zulaufdab327f2022-07-08 12:02:05 -06007157void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7158 exec_context.NextSubpassReplay();
7159}
John Zulauf8eda1562021-04-13 17:06:41 -06007160
John Zulauf64ffe552021-02-06 10:25:07 -07007161bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7162 bool skip = false;
7163 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7164
7165 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007166 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007167 return skip;
7168}
7169
John Zulaufdab327f2022-07-08 12:02:05 -06007170ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007171 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007172}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007173
John Zulauf8eda1562021-04-13 17:06:41 -06007174bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007175 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007176 return false;
7177}
7178
John Zulaufdab327f2022-07-08 12:02:05 -06007179void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7180 exec_context.EndRenderPassReplay();
7181}
John Zulauf8eda1562021-04-13 17:06:41 -06007182
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007183void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7184 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7185 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7186 auto *cb_access_context = GetAccessContext(commandBuffer);
7187 assert(cb_access_context);
7188 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7189 auto *context = cb_access_context->GetCurrentAccessContext();
7190 assert(context);
7191
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007192 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007193
7194 if (dst_buffer) {
7195 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7196 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7197 }
7198}
John Zulaufd05c5842021-03-26 11:32:16 -06007199
John Zulaufae842002021-04-15 18:20:55 -06007200bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7201 const VkCommandBuffer *pCommandBuffers) const {
7202 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007203 const auto *cb_context = GetAccessContext(commandBuffer);
7204 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007205
7206 // Heavyweight, but we need a proxy copy of the active command buffer access context
7207 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007208
7209 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007210 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007211 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7212
John Zulaufae842002021-04-15 18:20:55 -06007213 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7214 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007215
7216 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7217 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007218 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007219
7220 // The barriers have already been applied in ValidatFirstUse
7221 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007222 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007223 }
7224
John Zulaufae842002021-04-15 18:20:55 -06007225 return skip;
7226}
7227
7228void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7229 const VkCommandBuffer *pCommandBuffers) {
7230 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007231 auto *cb_context = GetAccessContext(commandBuffer);
7232 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007233 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007234 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007235 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7236 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007237 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007238 }
John Zulaufae842002021-04-15 18:20:55 -06007239}
7240
John Zulauf1d5f9c12022-05-13 14:51:08 -06007241void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7242 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7243 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7244
7245 const auto queue_state = GetQueueSyncStateShared(queue);
7246 if (!queue_state) return; // Invalid queue
7247 QueueId waited_queue = queue_state->GetQueueId();
John Zulauf3da08bb2022-08-01 17:56:56 -06007248 ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007249
John Zulauf3da08bb2022-08-01 17:56:56 -06007250 // Eliminate waitable fences from the current queue.
7251 layer_data::EraseIf(waitable_fences_, [waited_queue](const SignaledFence &sf) { return sf.second.queue_id == waited_queue; });
John Zulauf1d5f9c12022-05-13 14:51:08 -06007252}
7253
7254void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7255 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007256
7257 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7258 for (auto &batch : queue_batch_contexts) {
7259 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007260 }
7261
John Zulauf3da08bb2022-08-01 17:56:56 -06007262 // As we we've waited for everything on device, any waits are mooted.
7263 waitable_fences_.clear();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007264}
7265
John Zulauf697c0e12022-04-19 16:31:12 -06007266template <>
7267thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7268
John Zulaufbbda4572022-04-19 16:20:45 -06007269bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7270 VkFence fence) const {
John Zulaufa8700a52022-08-18 16:22:08 -06007271 SubmitInfoConverter submit_info(submitCount, pSubmits);
John Zulauf3298da92022-09-01 13:58:39 -06007272 return ValidateQueueSubmit(queue, submitCount, submit_info.info2s.data(), fence, "vkQueueSubmit");
John Zulaufa8700a52022-08-18 16:22:08 -06007273}
7274
7275bool SyncValidator::ValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2 *pSubmits, VkFence fence,
7276 const char *func_name) const {
John Zulaufbbda4572022-04-19 16:20:45 -06007277 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007278
7279 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007280 if (!enabled[sync_validation_queue_submit]) return skip;
7281
John Zulaufa8700a52022-08-18 16:22:08 -06007282 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, func_name, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007283 cmd_state->queue = GetQueueSyncStateShared(queue);
7284 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007285
John Zulauf697c0e12022-04-19 16:31:12 -06007286 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7287 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7288
7289 // verify each submit batch
7290 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7291 // most recently created batch
7292 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7293 std::shared_ptr<QueueBatchContext> batch;
7294 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
John Zulaufa8700a52022-08-18 16:22:08 -06007295 const VkSubmitInfo2 &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007296 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
John Zulaufa8700a52022-08-18 16:22:08 -06007297 batch->SetupCommandBufferInfo(submit);
7298 batch->SetupAccessContext(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007299
John Zulaufe0757ba2022-06-10 16:51:45 -06007300 // Skip import and validation of empty batches
7301 if (batch->GetTagRange().size()) {
7302 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007303
John Zulaufa8700a52022-08-18 16:22:08 -06007304 skip |= batch->DoQueueSubmitValidate(*this, *cmd_state, submit);
John Zulauf697c0e12022-04-19 16:31:12 -06007305 }
7306
John Zulaufe0757ba2022-06-10 16:51:45 -06007307 // Empty batches could have semaphores, though.
John Zulaufa8700a52022-08-18 16:22:08 -06007308 for (uint32_t sem_idx = 0; sem_idx < submit.signalSemaphoreInfoCount; ++sem_idx) {
7309 const VkSemaphoreSubmitInfo &semaphore_info = submit.pSignalSemaphoreInfos[sem_idx];
John Zulauf697c0e12022-04-19 16:31:12 -06007310 // Make a copy of the state, signal the copy and pend it...
John Zulaufa8700a52022-08-18 16:22:08 -06007311 auto sem_state = Get<SEMAPHORE_STATE>(semaphore_info.semaphore);
John Zulauf697c0e12022-04-19 16:31:12 -06007312 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007313 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007314 }
7315 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7316 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7317 last_batch = batch;
7318 }
7319 // The most recently created batch will become the queue's "last batch" in the record phase
7320 if (batch) {
7321 cmd_state->last_batch = std::move(batch);
7322 }
7323
7324 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007325 return skip;
7326}
7327
7328void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7329 VkResult result) {
7330 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007331
John Zulaufa8700a52022-08-18 16:22:08 -06007332 RecordQueueSubmit(queue, fence, result);
7333}
7334
7335void SyncValidator::RecordQueueSubmit(VkQueue queue, VkFence fence, VkResult result) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007336 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007337 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7338
John Zulaufcb7e1672022-05-04 13:46:08 -06007339 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7340 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007341 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007342
7343 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007344 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7345
John Zulauf697c0e12022-04-19 16:31:12 -06007346 // Don't need to look up the queue state again, but we need a non-const version
7347 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007348
John Zulaufcb7e1672022-05-04 13:46:08 -06007349 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7350 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7351 // QBC's are those referenced by unwaited signals and the last batch.
7352 for (auto &sig_sem : cmd_state->signaled) {
7353 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007354 auto &sig_batch = sig_sem.second->batch;
7355 sig_batch->ResetAccessLog();
7356 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7357 if (sig_batch != cmd_state->last_batch) {
7358 sig_batch->ResetEventsContext();
7359 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007360 }
7361 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007362 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007363 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007364
John Zulaufcb7e1672022-05-04 13:46:08 -06007365 // Update the queue to point to the last batch from the submit
7366 if (cmd_state->last_batch) {
7367 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007368
7369 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7370 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7371 auto last_batch = queue_state->LastBatch();
7372 if (last_batch) {
7373 last_batch->ResetEventsContext();
7374 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007375 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007376 }
7377
7378 // Update the global access log from the one built during validation
7379 global_access_log_.MergeMove(std::move(cmd_state->logger));
7380
John Zulauf3da08bb2022-08-01 17:56:56 -06007381 ResourceUsageRange fence_tag_range = ReserveGlobalTagRange(1U);
7382 UpdateFenceWaitInfo(fence, queue_state->GetQueueId(), fence_tag_range.begin);
John Zulaufbbda4572022-04-19 16:20:45 -06007383}
7384
7385bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7386 VkFence fence) const {
John Zulauf3298da92022-09-01 13:58:39 -06007387 return ValidateQueueSubmit(queue, submitCount, pSubmits, fence, "vkQueueSubmit2KHR");
John Zulaufa8700a52022-08-18 16:22:08 -06007388}
7389bool SyncValidator::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7390 VkFence fence) const {
John Zulauf3298da92022-09-01 13:58:39 -06007391 return ValidateQueueSubmit(queue, submitCount, pSubmits, fence, "vkQueueSubmit2");
John Zulaufbbda4572022-04-19 16:20:45 -06007392}
7393
7394void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7395 VkFence fence, VkResult result) {
7396 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulaufa8700a52022-08-18 16:22:08 -06007397 RecordQueueSubmit(queue, fence, result);
7398}
7399void SyncValidator::PostCallRecordQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits, VkFence fence,
7400 VkResult result) {
7401 StateTracker::PostCallRecordQueueSubmit2(queue, submitCount, pSubmits, fence, result);
7402 RecordQueueSubmit(queue, fence, result);
John Zulaufbbda4572022-04-19 16:20:45 -06007403}
7404
John Zulauf3da08bb2022-08-01 17:56:56 -06007405void SyncValidator::PostCallRecordGetFenceStatus(VkDevice device, VkFence fence, VkResult result) {
7406 StateTracker::PostCallRecordGetFenceStatus(device, fence, result);
7407 if (!enabled[sync_validation_queue_submit]) return;
7408 if (result == VK_SUCCESS) {
7409 // fence is signalled, mark it as waited for
7410 WaitForFence(fence);
7411 }
7412}
7413
7414void SyncValidator::PostCallRecordWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
7415 uint64_t timeout, VkResult result) {
7416 StateTracker::PostCallRecordWaitForFences(device, fenceCount, pFences, waitAll, timeout, result);
7417 if (!enabled[sync_validation_queue_submit]) return;
7418 if ((result == VK_SUCCESS) && ((VK_TRUE == waitAll) || (1 == fenceCount))) {
7419 // We can only know the pFences have signal if we waited for all of them, or there was only one of them
7420 for (uint32_t i = 0; i < fenceCount; i++) {
7421 WaitForFence(pFences[i]);
7422 }
7423 }
7424}
7425
John Zulaufd0ec59f2021-03-13 14:25:08 -07007426AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7427 : view_(view), view_mask_(), gen_store_() {
7428 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7429 const IMAGE_STATE &image_state = *view_->image_state.get();
7430 const auto base_address = ResourceBaseAddress(image_state);
7431 const auto *encoder = image_state.fragment_encoder.get();
7432 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007433 // Get offset and extent for the view, accounting for possible depth slicing
7434 const VkOffset3D zero_offset = view->GetOffset();
7435 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007436 // Intentional copy
7437 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7438 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007439 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7440 view->IsDepthSliced());
7441 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007442
7443 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7444 if (depth && (depth != view_mask_)) {
7445 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007446 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007447 }
7448 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7449 if (stencil && (stencil != view_mask_)) {
7450 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007451 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7452 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007453 }
7454}
7455
7456const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7457 const ImageRangeGen *got = nullptr;
7458 switch (gen_type) {
7459 case kViewSubresource:
7460 got = &gen_store_[kViewSubresource];
7461 break;
7462 case kRenderArea:
7463 got = &gen_store_[kRenderArea];
7464 break;
7465 case kDepthOnlyRenderArea:
7466 got =
7467 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7468 break;
7469 case kStencilOnlyRenderArea:
7470 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7471 : &gen_store_[Gen::kStencilOnlyRenderArea];
7472 break;
7473 default:
7474 assert(got);
7475 }
7476 return got;
7477}
7478
7479AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7480 assert(IsValid());
7481 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7482 if (depth_op) {
7483 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7484 if (stencil_op) {
7485 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7486 return kRenderArea;
7487 }
7488 return kDepthOnlyRenderArea;
7489 }
7490 if (stencil_op) {
7491 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7492 return kStencilOnlyRenderArea;
7493 }
7494
7495 assert(depth_op || stencil_op);
7496 return kRenderArea;
7497}
7498
7499AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007500
John Zulaufe0757ba2022-06-10 16:51:45 -06007501void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007502 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7503 for (auto &event_pair : map_) {
7504 assert(event_pair.second); // Shouldn't be storing empty
7505 auto &sync_event = *event_pair.second;
7506 // 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 -06007507 // But only if occuring before the tag
7508 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007509 sync_event.barriers |= dst.exec_scope;
7510 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7511 }
7512 }
7513}
John Zulaufbb890452021-12-14 11:30:18 -07007514
John Zulaufe0757ba2022-06-10 16:51:45 -06007515void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7516 const SyncExecScope src_scope =
7517 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7518 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7519 ApplyBarrier(src_scope, dst_scope, tag);
7520}
7521
7522SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7523 // We need a deep copy of the const context to update during validation phase
7524 for (const auto &event : from.map_) {
7525 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7526 }
7527 return *this;
7528}
7529
John Zulaufcb7e1672022-05-04 13:46:08 -06007530QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
John Zulaufdab327f2022-07-08 12:02:05 -06007531 : CommandExecutionContext(&sync_state),
7532 queue_state_(&queue_state),
7533 tag_range_(0, 0),
7534 current_access_context_(&access_context_),
7535 batch_log_(nullptr) {}
John Zulaufcb7e1672022-05-04 13:46:08 -06007536
John Zulauf1d5f9c12022-05-13 14:51:08 -06007537void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007538 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007539}
John Zulauf697c0e12022-04-19 16:31:12 -06007540
7541VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7542
John Zulauf1d5f9c12022-05-13 14:51:08 -06007543void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
John Zulauf3da08bb2022-08-01 17:56:56 -06007544 ResourceAccessState::QueueTagPredicate predicate{queue_id, tag};
7545 access_context_.EraseIf([&predicate](ResourceAccessRangeMap::value_type &access) {
7546 // Apply..Wait returns true if the waited access is empty...
7547 return access.second.ApplyQueueTagWait(predicate);
7548 });
John Zulaufe0757ba2022-06-10 16:51:45 -06007549
7550 if (queue_id == GetQueueId()) {
7551 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7552 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007553}
7554
7555// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007556void QueueBatchContext::ApplyDeviceWait() {
7557 access_context_.Reset();
7558 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7559}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007560
John Zulaufdab327f2022-07-08 12:02:05 -06007561HazardResult QueueBatchContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
7562 // Queue batch handling requires dealing with renderpass state and picking the correct access context
7563 if (rp_replay_) {
7564 return rp_replay_.replay_context->DetectFirstUseHazard(GetQueueId(), tag_range, *current_access_context_);
7565 }
7566 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, access_context_);
7567}
7568
7569void QueueBatchContext::BeginRenderPassReplay(const SyncOpBeginRenderPass &begin_op, const ResourceUsageTag tag) {
7570 current_access_context_ = rp_replay_.Begin(GetQueueFlags(), begin_op, access_context_);
7571 current_access_context_->ResolvePreviousAccesses();
7572}
7573
7574void QueueBatchContext::NextSubpassReplay() {
7575 current_access_context_ = rp_replay_.Next();
7576 current_access_context_->ResolvePreviousAccesses();
7577}
7578
7579void QueueBatchContext::EndRenderPassReplay() {
7580 rp_replay_.End(access_context_);
7581 current_access_context_ = &access_context_;
7582}
7583
7584AccessContext *QueueBatchContext::RenderPassReplayState::Begin(VkQueueFlags queue_flags, const SyncOpBeginRenderPass &begin_op_,
7585 const AccessContext &external_context) {
7586 Reset();
7587
7588 begin_op = &begin_op_;
7589 subpass = 0;
7590
7591 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7592 assert(rp_context);
7593 replay_context = &rp_context->GetContexts()[0];
7594
7595 InitSubpassContexts(queue_flags, *rp_context->GetRenderPassState(), &external_context, subpass_contexts);
7596 return &subpass_contexts[0];
7597}
7598
7599AccessContext *QueueBatchContext::RenderPassReplayState::Next() {
7600 subpass++;
7601
7602 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7603
7604 replay_context = &rp_context->GetContexts()[subpass];
7605 return &subpass_contexts[subpass];
7606}
7607
7608void QueueBatchContext::RenderPassReplayState::End(AccessContext &external_context) {
7609 external_context.ResolveChildContexts(subpass_contexts);
7610 Reset();
7611}
7612
John Zulaufecf4ac52022-06-06 10:08:42 -06007613class ApplySemaphoreBarrierAction {
7614 public:
7615 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7616 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7617
7618 private:
7619 const SemaphoreScope &signal_;
7620 const SemaphoreScope wait_;
7621};
7622
7623std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7624 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007625 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007626 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007627
John Zulaufcb7e1672022-05-04 13:46:08 -06007628 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7629 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007630 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007631
John Zulaufecf4ac52022-06-06 10:08:42 -06007632 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007633
John Zulaufecf4ac52022-06-06 10:08:42 -06007634 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007635 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007636 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7637 if (signal_scope.queue == wait_scope.queue) {
7638 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7639 // valid accesses for the sync scope.
7640 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7641 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7642 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007643 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007644 } else {
7645 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7646 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007647 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007648 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7649 // enforce deep constness.
7650 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007651}
7652
John Zulaufa8700a52022-08-18 16:22:08 -06007653void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const VkSubmitInfo2 &submit_info,
John Zulaufcb7e1672022-05-04 13:46:08 -06007654 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007655 // Copy in the event state from the previous batch (on this queue)
7656 if (prev) {
7657 events_context_.DeepCopy(prev->events_context_);
7658 }
7659
John Zulaufecf4ac52022-06-06 10:08:42 -06007660 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7661 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
John Zulaufa8700a52022-08-18 16:22:08 -06007662 const uint32_t wait_count = submit_info.waitSemaphoreInfoCount;
7663 const VkSemaphoreSubmitInfo *wait_infos = submit_info.pWaitSemaphoreInfos;
7664 for (const auto &wait_info : layer_data::make_span(wait_infos, wait_count)) {
7665 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(wait_info.semaphore, wait_info.stageMask, signaled);
John Zulaufecf4ac52022-06-06 10:08:42 -06007666 if (resolved) {
7667 batches_resolved.emplace(std::move(resolved));
7668 }
John Zulaufa8700a52022-08-18 16:22:08 -06007669 }
John Zulauf697c0e12022-04-19 16:31:12 -06007670
John Zulaufecf4ac52022-06-06 10:08:42 -06007671 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7672 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7673 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007674 }
7675
John Zulauf697c0e12022-04-19 16:31:12 -06007676 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007677 async_batches_ =
7678 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7679 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007680 });
7681 for (const auto &async_batch : async_batches_) {
7682 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7683 }
7684}
7685
John Zulaufa8700a52022-08-18 16:22:08 -06007686void QueueBatchContext::SetupCommandBufferInfo(const VkSubmitInfo2 &submit_info) {
John Zulauf697c0e12022-04-19 16:31:12 -06007687 // Create the list of command buffers to submit
John Zulaufa8700a52022-08-18 16:22:08 -06007688 const uint32_t cb_count = submit_info.commandBufferInfoCount;
7689 const VkCommandBufferSubmitInfo *const cb_infos = submit_info.pCommandBufferInfos;
John Zulauf697c0e12022-04-19 16:31:12 -06007690 command_buffers_.reserve(cb_count);
John Zulaufa8700a52022-08-18 16:22:08 -06007691
7692 for (const auto &cb_info : layer_data::make_span(cb_infos, cb_count)) {
7693 auto cb_context = sync_state_->GetAccessContextShared(cb_info.commandBuffer);
John Zulauf697c0e12022-04-19 16:31:12 -06007694 if (cb_context) {
7695 tag_range_.end += cb_context->GetTagLimit();
John Zulaufa8700a52022-08-18 16:22:08 -06007696 command_buffers_.emplace_back(static_cast<uint32_t>(&cb_info - cb_infos), std::move(cb_context));
John Zulauf697c0e12022-04-19 16:31:12 -06007697 }
7698 }
7699}
7700
7701// Look up the usage informaiton from the local or global logger
7702std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7703 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7704 std::stringstream out;
7705 AccessLogger::AccessRecord access = use_logger[tag];
7706 if (access.IsValid()) {
7707 const AccessLogger::BatchRecord &batch = *access.batch;
7708 const ResourceUsageRecord &record = *access.record;
7709 // Queue and Batch information
7710 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7711 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7712
7713 // Commandbuffer Usages Information
John Zulauf3298da92022-09-01 13:58:39 -06007714 out << ", " << record;
7715 out << ", " << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf697c0e12022-04-19 16:31:12 -06007716 out << ", reset_no: " << std::to_string(record.reset_count);
7717 }
7718 return out.str();
7719}
7720
7721VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7722
John Zulauf00119522022-05-23 19:07:42 -06007723QueueId QueueBatchContext::GetQueueId() const {
7724 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7725 return id;
7726}
7727
John Zulauf697c0e12022-04-19 16:31:12 -06007728void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7729 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7730 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7731 SetTagBias(global_tags.begin);
7732 // Add an access log for the batches range and point the batch at it.
7733 logger_ = &logger;
7734 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7735}
7736
7737void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7738 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7739 batch_log_->Append(submitted_cb.GetAccessLog());
7740}
7741
7742void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7743 const auto size = tag_range_.size();
7744 tag_range_.begin = bias;
7745 tag_range_.end = bias + size;
7746 access_context_.SetStartTag(bias);
7747}
7748
John Zulauf697c0e12022-04-19 16:31:12 -06007749AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7750 const ResourceUsageRange &range) {
7751 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7752 assert(inserted.second);
7753 return &inserted.first->second;
7754}
7755
7756void AccessLogger::MergeMove(AccessLogger &&child) {
7757 for (auto &range : child.access_log_map_) {
7758 BatchLog &child_batch = range.second;
7759 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7760 insert_pair.first->second = std::move(child_batch);
7761 assert(insert_pair.second);
7762 }
7763 child.Reset();
7764}
7765
7766void AccessLogger::Reset() {
7767 prev_ = nullptr;
7768 access_log_map_.clear();
7769}
7770
7771// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7772// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7773// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7774// the contexts Resolve all history from previous all contexts when created
7775void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7776 last_batch_ = std::move(last);
7777 last_batch_->ResetAccessLog();
7778}
7779
7780// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7781// scope state.
7782// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7783// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7784uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7785
7786void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7787 log_.insert(log_.end(), other.cbegin(), other.cend());
7788 for (const auto &record : other) {
7789 assert(record.cb_state);
7790 cbs_referenced_.insert(record.cb_state->shared_from_this());
7791 }
7792}
7793
7794AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7795 assert(index < log_.size());
7796 return AccessRecord{&batch_, &log_[index]};
7797}
7798
7799AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7800 AccessRecord access_record = {nullptr, nullptr};
7801
7802 auto found_range = access_log_map_.find(tag);
7803 if (found_range != access_log_map_.cend()) {
7804 const ResourceUsageTag bias = found_range->first.begin;
7805 assert(tag >= bias);
7806 access_record = found_range->second[tag - bias];
7807 } else if (prev_) {
7808 access_record = (*prev_)[tag];
7809 }
7810
7811 return access_record;
7812}
John Zulaufcb7e1672022-05-04 13:46:08 -06007813
John Zulaufecf4ac52022-06-06 10:08:42 -06007814// This is a const method, force the returned value to be const
7815std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007816 std::shared_ptr<Signal> prev_state;
7817 if (prev_) {
7818 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7819 }
7820 return prev_state;
7821}
John Zulaufecf4ac52022-06-06 10:08:42 -06007822
7823SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7824 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7825 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7826 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7827 assert(batch);
7828 assert(sem_state);
7829}
John Zulauf3da08bb2022-08-01 17:56:56 -06007830
7831FenceSyncState::FenceSyncState() : fence(), tag(kInvalidTag), queue_id(QueueSyncState::kQueueIdInvalid) {}
John Zulaufa8700a52022-08-18 16:22:08 -06007832
7833VkSemaphoreSubmitInfo SubmitInfoConverter::BatchStore::WaitSemaphore(const VkSubmitInfo &info, uint32_t index) {
7834 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7835 semaphore_info.semaphore = info.pWaitSemaphores[index];
7836 semaphore_info.stageMask = info.pWaitDstStageMask[index];
7837 return semaphore_info;
7838}
7839VkCommandBufferSubmitInfo SubmitInfoConverter::BatchStore::CommandBuffer(const VkSubmitInfo &info, uint32_t index) {
7840 auto cb_info = lvl_init_struct<VkCommandBufferSubmitInfo>();
7841 cb_info.commandBuffer = info.pCommandBuffers[index];
7842 return cb_info;
7843}
7844
7845VkSemaphoreSubmitInfo SubmitInfoConverter::BatchStore::SignalSemaphore(const VkSubmitInfo &info, uint32_t index) {
7846 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7847 semaphore_info.semaphore = info.pSignalSemaphores[index];
7848 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7849 return semaphore_info;
7850}
7851
7852SubmitInfoConverter::BatchStore::BatchStore(const VkSubmitInfo &info) {
7853 info2 = lvl_init_struct<VkSubmitInfo2>();
7854
7855 info2.waitSemaphoreInfoCount = info.waitSemaphoreCount;
7856 waits.reserve(info2.waitSemaphoreInfoCount);
7857 for (uint32_t i = 0; i < info2.waitSemaphoreInfoCount; ++i) {
7858 waits.emplace_back(WaitSemaphore(info, i));
7859 }
7860 info2.pWaitSemaphoreInfos = waits.data();
7861
7862 info2.commandBufferInfoCount = info.commandBufferCount;
7863 cbs.reserve(info2.commandBufferInfoCount);
7864 for (uint32_t i = 0; i < info2.commandBufferInfoCount; ++i) {
7865 cbs.emplace_back(CommandBuffer(info, i));
7866 }
7867 info2.pCommandBufferInfos = cbs.data();
7868
7869 info2.signalSemaphoreInfoCount = info.signalSemaphoreCount;
7870 signals.reserve(info2.signalSemaphoreInfoCount);
7871 for (uint32_t i = 0; i < info2.signalSemaphoreInfoCount; ++i) {
7872 signals.emplace_back(SignalSemaphore(info, i));
7873 }
7874 info2.pSignalSemaphoreInfos = signals.data();
7875}
7876
7877SubmitInfoConverter::SubmitInfoConverter(uint32_t count, const VkSubmitInfo *infos) {
7878 info_store.reserve(count);
7879 info2s.reserve(count);
7880 for (uint32_t batch = 0; batch < count; ++batch) {
7881 info_store.emplace_back(infos[batch]);
7882 info2s.emplace_back(info_store.back().info2);
7883 }
7884}