blob: 757d36f830ccdce3112cd4073271da0a8efa099a [file] [log] [blame]
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001/* Copyright (c) 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2019-2022 Valve Corporation
3 * Copyright (c) 2019-2022 LunarG, Inc.
John Zulauf9cb530d2019-09-30 14:14:10 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: John Zulauf <jzulauf@lunarg.com>
John Zulaufab7756b2020-12-29 16:10:16 -070018 * Author: Locke Lin <locke@lunarg.com>
19 * Author: Jeremy Gebben <jeremyg@lunarg.com>
John Zulauf9cb530d2019-09-30 14:14:10 -060020 */
21
22#include <limits>
23#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060024#include <memory>
25#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060026#include "synchronization_validation.h"
Jeremy Gebben5f585ae2021-02-02 09:03:06 -070027#include "sync_utils.h"
John Zulauf9cb530d2019-09-30 14:14:10 -060028
John Zulaufea943c52022-02-22 11:05:17 -070029// Utilities to DRY up Get... calls
30template <typename Map, typename Key = typename Map::key_type, typename RetVal = layer_data::optional<typename Map::mapped_type>>
31RetVal GetMappedOptional(const Map &map, const Key &key) {
32 RetVal ret_val;
33 auto it = map.find(key);
34 if (it != map.cend()) {
35 ret_val.emplace(it->second);
36 }
37 return ret_val;
38}
39template <typename Map, typename Fn>
40typename Map::mapped_type GetMapped(const Map &map, const typename Map::key_type &key, Fn &&default_factory) {
41 auto value = GetMappedOptional(map, key);
42 return (value) ? *value : default_factory();
43}
44
45template <typename Map, typename Fn>
John Zulauf397e68b2022-04-19 11:44:07 -060046typename Map::mapped_type GetMappedInsert(Map &map, const typename Map::key_type &key, Fn &&emplace_factory) {
John Zulaufea943c52022-02-22 11:05:17 -070047 auto value = GetMappedOptional(map, key);
48 if (value) {
49 return *value;
50 }
John Zulauf397e68b2022-04-19 11:44:07 -060051 auto insert_it = map.emplace(std::make_pair(key, emplace_factory()));
John Zulaufea943c52022-02-22 11:05:17 -070052 assert(insert_it.second);
53
54 return insert_it.first->second;
55}
56
57template <typename Map, typename Key = typename Map::key_type, typename Mapped = typename Map::mapped_type,
58 typename Value = typename Mapped::element_type>
59Value *GetMappedPlainFromShared(const Map &map, const Key &key) {
60 auto value = GetMappedOptional<Map, Key>(map, key);
61 if (value) return value->get();
62 return nullptr;
63}
64
Jeremy Gebben6fbf8242021-06-21 09:14:46 -060065static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.Binding(); }
John Zulauf264cce02021-02-05 14:40:47 -070066
John Zulauf29d00532021-03-04 13:28:54 -070067static bool SimpleBinding(const IMAGE_STATE &image_state) {
Jeremy Gebben62c3bf42021-07-21 15:38:24 -060068 bool simple =
Jeremy Gebben82e11d52021-07-26 09:19:37 -060069 SimpleBinding(static_cast<const BINDABLE &>(image_state)) || image_state.IsSwapchainImage() || image_state.bind_swapchain;
John Zulauf29d00532021-03-04 13:28:54 -070070
71 // If it's not simple we must have an encoder.
72 assert(!simple || image_state.fragment_encoder.get());
73 return simple;
74}
75
John Zulauf4fa68462021-04-26 21:04:22 -060076static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
77static const std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
John Zulauf43cc7462020-12-03 12:33:12 -070078 AccessAddressType::kLinear, AccessAddressType::kIdealized};
79
John Zulaufd5115702021-01-18 12:34:33 -070080static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
John Zulauf264cce02021-02-05 14:40:47 -070081static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
82 return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
83}
John Zulaufd5115702021-01-18 12:34:33 -070084
John Zulauf9cb530d2019-09-30 14:14:10 -060085static const char *string_SyncHazardVUID(SyncHazard hazard) {
86 switch (hazard) {
87 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070088 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060089 break;
90 case SyncHazard::READ_AFTER_WRITE:
91 return "SYNC-HAZARD-READ_AFTER_WRITE";
92 break;
93 case SyncHazard::WRITE_AFTER_READ:
94 return "SYNC-HAZARD-WRITE_AFTER_READ";
95 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
97 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
98 break;
John Zulauf2f952d22020-02-10 11:34:51 -070099 case SyncHazard::READ_RACING_WRITE:
100 return "SYNC-HAZARD-READ-RACING-WRITE";
101 break;
102 case SyncHazard::WRITE_RACING_WRITE:
103 return "SYNC-HAZARD-WRITE-RACING-WRITE";
104 break;
105 case SyncHazard::WRITE_RACING_READ:
106 return "SYNC-HAZARD-WRITE-RACING-READ";
107 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600108 default:
109 assert(0);
110 }
111 return "SYNC-HAZARD-INVALID";
112}
113
John Zulauf59e25072020-07-17 10:55:21 -0600114static bool IsHazardVsRead(SyncHazard hazard) {
115 switch (hazard) {
116 case SyncHazard::NONE:
117 return false;
118 break;
119 case SyncHazard::READ_AFTER_WRITE:
120 return false;
121 break;
122 case SyncHazard::WRITE_AFTER_READ:
123 return true;
124 break;
125 case SyncHazard::WRITE_AFTER_WRITE:
126 return false;
127 break;
128 case SyncHazard::READ_RACING_WRITE:
129 return false;
130 break;
131 case SyncHazard::WRITE_RACING_WRITE:
132 return false;
133 break;
134 case SyncHazard::WRITE_RACING_READ:
135 return true;
136 break;
137 default:
138 assert(0);
139 }
140 return false;
141}
142
John Zulauf9cb530d2019-09-30 14:14:10 -0600143static const char *string_SyncHazard(SyncHazard hazard) {
144 switch (hazard) {
145 case SyncHazard::NONE:
146 return "NONR";
147 break;
148 case SyncHazard::READ_AFTER_WRITE:
149 return "READ_AFTER_WRITE";
150 break;
151 case SyncHazard::WRITE_AFTER_READ:
152 return "WRITE_AFTER_READ";
153 break;
154 case SyncHazard::WRITE_AFTER_WRITE:
155 return "WRITE_AFTER_WRITE";
156 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700157 case SyncHazard::READ_RACING_WRITE:
158 return "READ_RACING_WRITE";
159 break;
160 case SyncHazard::WRITE_RACING_WRITE:
161 return "WRITE_RACING_WRITE";
162 break;
163 case SyncHazard::WRITE_RACING_READ:
164 return "WRITE_RACING_READ";
165 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600166 default:
167 assert(0);
168 }
169 return "INVALID HAZARD";
170}
171
John Zulauf37ceaed2020-07-03 16:18:15 -0600172static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
173 // Return the info for the first bit found
174 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700175 for (size_t i = 0; i < flags.size(); i++) {
176 if (flags.test(i)) {
177 info = &syncStageAccessInfoByStageAccessIndex[i];
178 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600179 }
180 }
181 return info;
182}
183
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700184static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600185 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700186 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600187 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700188 } else {
189 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
190 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
191 if ((flags & info.stage_access_bit).any()) {
192 if (!out_str.empty()) {
193 out_str.append(sep);
194 }
195 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600196 }
John Zulauf59e25072020-07-17 10:55:21 -0600197 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700198 if (out_str.length() == 0) {
199 out_str.append("Unhandled SyncStageAccess");
200 }
John Zulauf59e25072020-07-17 10:55:21 -0600201 }
202 return out_str;
203}
204
John Zulauf397e68b2022-04-19 11:44:07 -0600205std::ostream &operator<<(std::ostream &out, const ResourceUsageRecord &record) {
206 out << "command: " << CommandTypeString(record.command);
207 out << ", seq_no: " << record.seq_num;
208 if (record.sub_command != 0) {
209 out << ", subcmd: " << record.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700210 }
John Zulauf397e68b2022-04-19 11:44:07 -0600211 return out;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700212}
John Zulauf397e68b2022-04-19 11:44:07 -0600213
John Zulauf4fa68462021-04-26 21:04:22 -0600214static std::string string_UsageIndex(SyncStageAccessIndex usage_index) {
215 const char *stage_access_name = "INVALID_STAGE_ACCESS";
216 if (usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())) {
217 stage_access_name = syncStageAccessInfoByStageAccessIndex[usage_index].name;
218 }
219 return std::string(stage_access_name);
220}
221
John Zulauf397e68b2022-04-19 11:44:07 -0600222struct SyncNodeFormatter {
223 const debug_report_data *report_data;
224 const BASE_NODE *node;
225 const char *label;
226
227 SyncNodeFormatter(const SyncValidator &sync_state, const CMD_BUFFER_STATE *cb_state)
228 : report_data(sync_state.report_data), node(cb_state), label("command_buffer") {}
229 SyncNodeFormatter(const SyncValidator &sync_state, const QUEUE_STATE *q_state)
230 : report_data(sync_state.report_data), node(q_state), label("queue") {}
231};
232
233std::ostream &operator<<(std::ostream &out, const SyncNodeFormatter &formater) {
234 if (formater.node) {
235 out << ", " << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
240 out << ", " << formater.label << ": null handle";
241 }
242 return out;
243}
244
245std::ostream &operator<<(std::ostream &out, const HazardResult &hazard) {
246 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
247 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
248 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
249 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
250 out << "(";
251 if (!hazard.recorded_access.get()) {
252 // if we have a recorded usage the usage is reported from the recorded contexts point of view
253 out << "usage: " << usage_info.name << ", ";
254 }
255 out << "prior_usage: " << stage_access_name;
256 if (IsHazardVsRead(hazard.hazard)) {
257 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
258 out << ", read_barriers: " << string_VkPipelineStageFlags2KHR(barriers);
259 } else {
260 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
261 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
262 }
263 return out;
264}
265
John Zulauf4fa68462021-04-26 21:04:22 -0600266struct NoopBarrierAction {
267 explicit NoopBarrierAction() {}
268 void operator()(ResourceAccessState *access) const {}
John Zulauf5c628d02021-05-04 15:46:36 -0600269 const bool layout_transition = false;
John Zulauf4fa68462021-04-26 21:04:22 -0600270};
271
John Zulaufdab327f2022-07-08 12:02:05 -0600272static void InitSubpassContexts(VkQueueFlags queue_flags, const RENDER_PASS_STATE &rp_state, const AccessContext *external_context,
273 std::vector<AccessContext> &subpass_contexts) {
274 const auto &create_info = rp_state.createInfo;
275 // Add this for all subpasses here so that they exsist during next subpass validation
276 subpass_contexts.clear();
277 subpass_contexts.reserve(create_info.subpassCount);
278 for (uint32_t pass = 0; pass < create_info.subpassCount; pass++) {
279 subpass_contexts.emplace_back(pass, queue_flags, rp_state.subpass_dependencies, subpass_contexts, external_context);
280 }
281}
282
John Zulauf4fa68462021-04-26 21:04:22 -0600283// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
284CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
285 : CommandBufferAccessContext(from.sync_state_) {
286 // Copy only the needed fields out of from for a temporary, proxy command buffer context
287 cb_state_ = from.cb_state_;
288 queue_flags_ = from.queue_flags_;
289 destroyed_ = from.destroyed_;
290 access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
291 command_number_ = from.command_number_;
292 subcommand_number_ = from.subcommand_number_;
293 reset_count_ = from.reset_count_;
294
295 const auto *from_context = from.GetCurrentAccessContext();
296 assert(from_context);
297
298 // Construct a fully resolved single access context out of from
299 const NoopBarrierAction noop_barrier;
300 for (AccessAddressType address_type : kAddressTypes) {
301 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
302 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
303 }
304 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
305 cb_access_context_.ImportAsyncContexts(*from_context);
306
307 events_context_ = from.events_context_;
308
309 // We don't want to copy the full render_pass_context_ history just for the proxy.
310}
311
312std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf397e68b2022-04-19 11:44:07 -0600313 if (tag >= access_log_.size()) return std::string();
314
John Zulauf4fa68462021-04-26 21:04:22 -0600315 std::stringstream out;
316 assert(tag < access_log_.size());
317 const auto &record = access_log_[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600318 out << record;
319 if (cb_state_.get() != record.cb_state) {
320 out << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600321 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600322 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600323 return out.str();
324}
John Zulauf397e68b2022-04-19 11:44:07 -0600325
John Zulauf4fa68462021-04-26 21:04:22 -0600326std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
327 std::stringstream out;
328 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
329 out << ", " << FormatUsage(access.tag) << ")";
330 return out.str();
331}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700332
John Zulauf397e68b2022-04-19 11:44:07 -0600333std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600334 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600335 out << hazard;
336 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600337 return out.str();
338}
339
John Zulaufdab327f2022-07-08 12:02:05 -0600340
John Zulauf0223f142022-07-06 09:05:39 -0600341bool CommandExecutionContext::ValidForSyncOps() const {
342 bool valid = GetCurrentEventsContext() && GetCurrentAccessContext();
343 assert(valid);
344 return valid;
345}
346
John Zulaufd14743a2020-07-03 09:42:39 -0600347// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
348// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
349// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700350static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700351static const SyncStageAccessFlags kColorAttachmentAccessScope =
352 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
353 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
354 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
355 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700356static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
357 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700358static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
359 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
360 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
361 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700362static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700363static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600364
John Zulauf8e3c3e92021-01-06 11:19:36 -0700365ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700366 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700367 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
368 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
369 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
370
John Zulaufee984022022-04-13 16:39:50 -0600371// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
372static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600373
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600374static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600375
John Zulaufcb7e1672022-05-04 13:46:08 -0600376VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600377 if (size == VK_WHOLE_SIZE) {
378 return (whole_size - offset);
379 }
380 return size;
381}
382
John Zulauf3e86bf02020-09-12 10:47:57 -0600383static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
384 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
385}
386
John Zulauf16adfc92020-04-08 10:28:33 -0600387template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600388static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600389 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
390}
391
John Zulauf355e49b2020-04-24 15:11:15 -0600392static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600393
John Zulauf3e86bf02020-09-12 10:47:57 -0600394static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
395 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
396}
397
398static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
399 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
400}
401
John Zulauf4a6105a2020-11-17 15:11:05 -0700402// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
403//
John Zulauf10f1f522020-12-18 12:00:35 -0700404// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
405//
John Zulauf4a6105a2020-11-17 15:11:05 -0700406// Usage:
407// Constructor() -- initializes the generator to point to the begin of the space declared.
408// * -- the current range of the generator empty signfies end
409// ++ -- advance to the next non-empty range (or end)
410
411// A wrapper for a single range with the same semantics as the actual generators below
412template <typename KeyType>
413class SingleRangeGenerator {
414 public:
415 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700416 const KeyType &operator*() const { return current_; }
417 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700418 SingleRangeGenerator &operator++() {
419 current_ = KeyType(); // just one real range
420 return *this;
421 }
422
423 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
424
425 private:
426 SingleRangeGenerator() = default;
427 const KeyType range_;
428 KeyType current_;
429};
430
John Zulaufae842002021-04-15 18:20:55 -0600431// Generate the ranges that are the intersection of range and the entries in the RangeMap
432template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
433class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700434 public:
John Zulaufd5115702021-01-18 12:34:33 -0700435 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600436 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700437 // Default construction for KeyType *must* be empty range
438 assert(current_.empty());
439 }
John Zulaufae842002021-04-15 18:20:55 -0600440 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 SeekBegin();
442 }
John Zulaufae842002021-04-15 18:20:55 -0600443 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700444
John Zulauf4a6105a2020-11-17 15:11:05 -0700445 const KeyType &operator*() const { return current_; }
446 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600447 MapRangesRangeGenerator &operator++() {
448 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700449 UpdateCurrent();
450 return *this;
451 }
452
John Zulaufae842002021-04-15 18:20:55 -0600453 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700454
John Zulaufae842002021-04-15 18:20:55 -0600455 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700456 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600457 if (map_pos_ != map_->cend()) {
458 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700459 } else {
460 current_ = KeyType();
461 }
462 }
463 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600464 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700465 UpdateCurrent();
466 }
John Zulaufae842002021-04-15 18:20:55 -0600467
468 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
469 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
470 template <typename Pred>
471 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
472 do {
473 ++map_pos_;
474 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
475 UpdateCurrent();
476 return *this;
477 }
478
John Zulauf4a6105a2020-11-17 15:11:05 -0700479 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600480 const RangeMap *map_;
481 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700482 KeyType current_;
483};
John Zulaufd5115702021-01-18 12:34:33 -0700484using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600485using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700486
John Zulaufae842002021-04-15 18:20:55 -0600487// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
488template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
489class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
490 public:
491 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
492 // Default constructed is safe to dereference for "empty" test, but for no other operation.
493 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
494 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
495 : Base(filter, range), pred_(pred) {}
496 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
497
498 PredicatedMapRangesRangeGenerator &operator++() {
499 Base::PredicatedIncrement(pred_);
500 return *this;
501 }
502
503 protected:
504 Predicate pred_;
505};
John Zulauf4a6105a2020-11-17 15:11:05 -0700506
507// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600508// Templated to allow for different Range generators or map sources...
509template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700510class FilteredGeneratorGenerator {
511 public:
John Zulaufd5115702021-01-18 12:34:33 -0700512 // Default constructed is safe to dereference for "empty" test, but for no other operation.
513 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
514 // Default construction for KeyType *must* be empty range
515 assert(current_.empty());
516 }
John Zulaufae842002021-04-15 18:20:55 -0600517 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700518 SeekBegin();
519 }
John Zulaufd5115702021-01-18 12:34:33 -0700520 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700521 const KeyType &operator*() const { return current_; }
522 const KeyType *operator->() const { return &current_; }
523 FilteredGeneratorGenerator &operator++() {
524 KeyType gen_range = GenRange();
525 KeyType filter_range = FilterRange();
526 current_ = KeyType();
527 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
528 if (gen_range.end > filter_range.end) {
529 // if the generated range is beyond the filter_range, advance the filter range
530 filter_range = AdvanceFilter();
531 } else {
532 gen_range = AdvanceGen();
533 }
534 current_ = gen_range & filter_range;
535 }
536 return *this;
537 }
538
539 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
540
541 private:
542 KeyType AdvanceFilter() {
543 ++filter_pos_;
544 auto filter_range = FilterRange();
545 if (filter_range.valid()) {
546 FastForwardGen(filter_range);
547 }
548 return filter_range;
549 }
550 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700551 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700552 auto gen_range = GenRange();
553 if (gen_range.valid()) {
554 FastForwardFilter(gen_range);
555 }
556 return gen_range;
557 }
558
559 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700560 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700561
562 KeyType FastForwardFilter(const KeyType &range) {
563 auto filter_range = FilterRange();
564 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700565 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700566 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
567 if (retry_count < kRetryLimit) {
568 ++filter_pos_;
569 filter_range = FilterRange();
570 retry_count++;
571 } else {
572 // Okay we've tried walking, do a seek.
573 filter_pos_ = filter_->lower_bound(range);
574 break;
575 }
576 }
577 return FilterRange();
578 }
579
580 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
581 // faster.
582 KeyType FastForwardGen(const KeyType &range) {
583 auto gen_range = GenRange();
584 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700585 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700586 gen_range = GenRange();
587 }
588 return gen_range;
589 }
590
591 void SeekBegin() {
592 auto gen_range = GenRange();
593 if (gen_range.empty()) {
594 current_ = KeyType();
595 filter_pos_ = filter_->cend();
596 } else {
597 filter_pos_ = filter_->lower_bound(gen_range);
598 current_ = gen_range & FilterRange();
599 }
600 }
601
John Zulaufae842002021-04-15 18:20:55 -0600602 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700603 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600604 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700605 KeyType current_;
606};
607
608using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
609
John Zulauf5c5e88d2019-12-26 11:22:02 -0700610
John Zulauf3e86bf02020-09-12 10:47:57 -0600611ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
612 VkDeviceSize stride) {
613 VkDeviceSize range_start = offset + first_index * stride;
614 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600615 if (count == UINT32_MAX) {
616 range_size = buf_whole_size - range_start;
617 } else {
618 range_size = count * stride;
619 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600620 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600621}
622
locke-lunarg654e3692020-06-04 17:19:15 -0600623SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
624 VkShaderStageFlagBits stage_flag) {
625 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
626 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
627 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
628 }
629 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
630 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
631 assert(0);
632 }
633 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
634 return stage_access->second.uniform_read;
635 }
636
637 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
638 // Because if write hazard happens, read hazard might or might not happen.
639 // But if write hazard doesn't happen, read hazard is impossible to happen.
640 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700641 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600642 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700643 // TODO: sampled_read
644 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600645}
646
locke-lunarg37047832020-06-12 13:44:45 -0600647bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
648 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
649 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
650 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
651 ? true
652 : false;
653}
654
655bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
656 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
657 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
658 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
659 ? true
660 : false;
661}
662
John Zulauf355e49b2020-04-24 15:11:15 -0600663// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600664template <typename Action>
665static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
666 Action &action) {
667 // At this point the "apply over range" logic only supports a single memory binding
668 if (!SimpleBinding(image_state)) return;
669 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600670 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700671 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200672 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600673 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700674 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600675 }
676}
677
John Zulauf7635de32020-05-29 17:14:15 -0600678// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
679// Used by both validation and record operations
680//
681// The signature for Action() reflect the needs of both uses.
682template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
684 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600685 const auto &rp_ci = rp_state.createInfo;
686 const auto *attachment_ci = rp_ci.pAttachments;
687 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
688
689 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
690 const auto *color_attachments = subpass_ci.pColorAttachments;
691 const auto *color_resolve = subpass_ci.pResolveAttachments;
692 if (color_resolve && color_attachments) {
693 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
694 const auto &color_attach = color_attachments[i].attachment;
695 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
696 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
697 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700698 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
699 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600700 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700701 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
702 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600703 }
704 }
705 }
706
707 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700708 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600709 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
710 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
711 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
712 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
713 const auto src_ci = attachment_ci[src_at];
714 // The formats are required to match so we can pick either
715 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
716 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
717 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600718
719 // Figure out which aspects are actually touched during resolve operations
720 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700721 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600722 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600723 aspect_string = "depth/stencil";
724 } else if (resolve_depth) {
725 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700726 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600727 aspect_string = "depth";
728 } else if (resolve_stencil) {
729 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700730 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600731 aspect_string = "stencil";
732 }
733
John Zulaufd0ec59f2021-03-13 14:25:08 -0700734 if (aspect_string) {
735 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
736 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
737 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
738 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600739 }
740 }
741}
742
743// Action for validating resolve operations
744class ValidateResolveAction {
745 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700746 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
sjfricke0bea06e2022-06-05 09:22:26 +0900747 const CommandExecutionContext &exec_context, CMD_TYPE cmd_type)
John Zulauf7635de32020-05-29 17:14:15 -0600748 : render_pass_(render_pass),
749 subpass_(subpass),
750 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700751 exec_context_(exec_context),
sjfricke0bea06e2022-06-05 09:22:26 +0900752 cmd_type_(cmd_type),
John Zulauf7635de32020-05-29 17:14:15 -0600753 skip_(false) {}
754 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulaufd0ec59f2021-03-13 14:25:08 -0700755 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
756 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600757 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700758 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600759 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +0900760 skip_ |= exec_context_.GetSyncState().LogError(
761 render_pass_, string_SyncHazardVUID(hazard.hazard),
762 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32
763 ". Access info %s.",
764 CommandTypeString(cmd_type_), string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at,
765 dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600766 }
767 }
768 // Providing a mechanism for the constructing caller to get the result of the validation
769 bool GetSkip() const { return skip_; }
770
771 private:
772 VkRenderPass render_pass_;
773 const uint32_t subpass_;
774 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700775 const CommandExecutionContext &exec_context_;
sjfricke0bea06e2022-06-05 09:22:26 +0900776 CMD_TYPE cmd_type_;
John Zulauf7635de32020-05-29 17:14:15 -0600777 bool skip_;
778};
779
780// Update action for resolve operations
781class UpdateStateResolveAction {
782 public:
John Zulauf14940722021-04-12 15:19:02 -0600783 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700784 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
785 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600786 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700787 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600788 }
789
790 private:
791 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600792 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600793};
794
John Zulauf59e25072020-07-17 10:55:21 -0600795void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600796 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600797 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600798 usage_index = usage_index_;
799 hazard = hazard_;
800 prior_access = prior_;
801 tag = tag_;
802}
803
John Zulauf4fa68462021-04-26 21:04:22 -0600804void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
805 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
806}
807
John Zulauf1d5f9c12022-05-13 14:51:08 -0600808void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
809
John Zulauf540266b2020-04-06 18:54:53 -0600810AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
811 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600812 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600813 Reset();
814 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700815 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
816 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600817 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600818 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600819 const auto prev_pass = prev_dep.first->pass;
820 const auto &prev_barriers = prev_dep.second;
821 assert(prev_dep.second.size());
822 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
823 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700824 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600825
826 async_.reserve(subpass_dep.async.size());
827 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700828 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600829 }
John Zulauf22aefed2021-03-11 18:14:35 -0700830 if (has_barrier_from_external) {
831 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
832 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
833 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600834 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600835 if (subpass_dep.barrier_to_external.size()) {
836 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600837 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700838}
839
John Zulauf5f13a792020-03-10 07:31:21 -0600840template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600841HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600842 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600843 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600844 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600845
846 HazardResult hazard;
847 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
848 hazard = detector.Detect(prev);
849 }
850 return hazard;
851}
852
John Zulauf4a6105a2020-11-17 15:11:05 -0700853template <typename Action>
854void AccessContext::ForAll(Action &&action) {
855 for (const auto address_type : kAddressTypes) {
856 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600857 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700858 action(address_type, access);
859 }
860 }
861}
862
John Zulauf3da08bb2022-08-01 17:56:56 -0600863template <typename Predicate>
864void AccessContext::EraseIf(Predicate &&pred) {
865 for (const auto address_type : kAddressTypes) {
866 auto &accesses = GetAccessStateMap(address_type);
867 // Note: Don't forward, we don't want r-values moved, since we're going to make multiple calls.
868 layer_data::EraseIf(accesses, pred);
869 }
870}
871
John Zulauf3d84f1b2020-03-09 13:33:25 -0600872// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
873// the DAG of the contexts (for example subpasses)
874template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600875HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600876 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600877 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600878
John Zulauf1a224292020-06-30 14:52:13 -0600879 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600880 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
881 // so we'll check these first
882 for (const auto &async_context : async_) {
883 hazard = async_context->DetectAsyncHazard(type, detector, range);
884 if (hazard.hazard) return hazard;
885 }
John Zulauf5f13a792020-03-10 07:31:21 -0600886 }
887
John Zulauf1a224292020-06-30 14:52:13 -0600888 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600889
John Zulauf69133422020-05-20 14:55:53 -0600890 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600891 const auto the_end = accesses.cend(); // End is not invalidated
892 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600893 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600894
John Zulauf3cafbf72021-03-26 16:55:19 -0600895 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600896 // Cover any leading gap, or gap between entries
897 if (detect_prev) {
898 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
899 // Cover any leading gap, or gap between entries
900 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600901 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600902 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600903 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600904 if (hazard.hazard) return hazard;
905 }
John Zulauf69133422020-05-20 14:55:53 -0600906 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
907 gap.begin = pos->first.end;
908 }
909
910 hazard = detector.Detect(pos);
911 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600912 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600913 }
914
915 if (detect_prev) {
916 // Detect in the trailing empty as needed
917 gap.end = range.end;
918 if (gap.non_empty()) {
919 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600920 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600921 }
922
923 return hazard;
924}
925
926// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
927template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700928HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
929 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600930 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600931 auto pos = accesses.lower_bound(range);
932 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600933
John Zulauf3d84f1b2020-03-09 13:33:25 -0600934 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600935 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700936 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600937 if (hazard.hazard) break;
938 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600939 }
John Zulauf16adfc92020-04-08 10:28:33 -0600940
John Zulauf3d84f1b2020-03-09 13:33:25 -0600941 return hazard;
942}
943
John Zulaufb02c1eb2020-10-06 16:33:36 -0600944struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700945 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600946 void operator()(ResourceAccessState *access) const {
947 assert(access);
948 access->ApplyBarriers(barriers, true);
949 }
950 const std::vector<SyncBarrier> &barriers;
951};
952
John Zulaufe0757ba2022-06-10 16:51:45 -0600953struct QueueTagOffsetBarrierAction {
954 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
955 void operator()(ResourceAccessState *access) const {
956 access->OffsetTag(tag_offset);
957 access->SetQueueId(queue_id);
958 };
959 QueueId queue_id;
960 ResourceUsageTag tag_offset;
961};
962
John Zulauf22aefed2021-03-11 18:14:35 -0700963struct ApplyTrackbackStackAction {
964 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
965 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
966 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600967 void operator()(ResourceAccessState *access) const {
968 assert(access);
969 assert(!access->HasPendingState());
970 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600971 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
972 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700973 if (previous_barrier) {
974 assert(bool(*previous_barrier));
975 (*previous_barrier)(access);
976 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977 }
978 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700979 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600980};
981
982// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
983// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
984// *different* map from dest.
985// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
986// range [first, last)
987template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600988static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
989 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600990 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600991 auto at = entry;
992 for (auto pos = first; pos != last; ++pos) {
993 // Every member of the input iterator range must fit within the remaining portion of entry
994 assert(at->first.includes(pos->first));
995 assert(at != dest->end());
996 // Trim up at to the same size as the entry to resolve
997 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600998 auto access = pos->second; // intentional copy
999 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -06001000 at->second.Resolve(access);
1001 ++at; // Go to the remaining unused section of entry
1002 }
1003}
1004
John Zulaufa0a98292020-09-18 09:30:10 -06001005static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
1006 SyncBarrier merged = {};
1007 for (const auto &barrier : barriers) {
1008 merged.Merge(barrier);
1009 }
1010 return merged;
1011}
1012
John Zulaufb02c1eb2020-10-06 16:33:36 -06001013template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -07001014void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -06001015 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
1016 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001017 if (!range.non_empty()) return;
1018
John Zulauf355e49b2020-04-24 15:11:15 -06001019 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
1020 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001021 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001022 if (current->pos_B->valid) {
1023 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001024 auto access = src_pos->second; // intentional copy
1025 barrier_action(&access);
1026
John Zulauf16adfc92020-04-08 10:28:33 -06001027 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001028 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1029 trimmed->second.Resolve(access);
1030 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001031 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001032 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001033 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001034 }
John Zulauf16adfc92020-04-08 10:28:33 -06001035 } else {
1036 // we have to descend to fill this gap
1037 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001038 ResourceAccessRange recurrence_range = current_range;
1039 // The current context is empty for the current range, so recur to fill the gap.
1040 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1041 // is not valid, to minimize that recurrence
1042 if (current->pos_B.at_end()) {
1043 // Do the remainder here....
1044 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001045 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001046 // Recur only over the range until B becomes valid (within the limits of range).
1047 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001048 }
John Zulauf22aefed2021-03-11 18:14:35 -07001049 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1050
John Zulauf355e49b2020-04-24 15:11:15 -06001051 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1052 // iterator of the outer while.
1053
1054 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1055 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1056 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001057 const auto seek_to = recurrence_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
locke-lunarg88dbb542020-06-23 22:05:42 -06001058 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001059 current.seek(seek_to);
1060 } else if (!current->pos_A->valid && infill_state) {
1061 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1062 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1063 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001064 }
John Zulauf5f13a792020-03-10 07:31:21 -06001065 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001066 if (current->range.non_empty()) {
1067 ++current;
1068 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001069 }
John Zulauf1a224292020-06-30 14:52:13 -06001070
1071 // Infill if range goes passed both the current and resolve map prior contents
1072 if (recur_to_infill && (current->range.end < range.end)) {
1073 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001074 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001075 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001076}
1077
John Zulauf22aefed2021-03-11 18:14:35 -07001078template <typename BarrierAction>
1079void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1080 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1081 const BarrierAction &previous_barrier) const {
1082 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1083 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1084}
1085
John Zulauf43cc7462020-12-03 12:33:12 -07001086void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001087 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1088 const ResourceAccessStateFunction *previous_barrier) const {
1089 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001090 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001091 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1092 ResourceAccessState state_copy;
1093 if (previous_barrier) {
1094 assert(bool(*previous_barrier));
1095 state_copy = *infill_state;
1096 (*previous_barrier)(&state_copy);
1097 infill_state = &state_copy;
1098 }
1099 sparse_container::update_range_value(*descent_map, range, *infill_state,
1100 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001101 }
1102 } else {
1103 // Look for something to fill the gap further along.
1104 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001105 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001106 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001107 }
John Zulauf5f13a792020-03-10 07:31:21 -06001108 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001109}
1110
John Zulauf4a6105a2020-11-17 15:11:05 -07001111// Non-lazy import of all accesses, WaitEvents needs this.
1112void AccessContext::ResolvePreviousAccesses() {
1113 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001114 if (!prev_.size()) return; // If no previous contexts, nothing to do
1115
John Zulauf4a6105a2020-11-17 15:11:05 -07001116 for (const auto address_type : kAddressTypes) {
1117 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1118 }
1119}
1120
John Zulauf43cc7462020-12-03 12:33:12 -07001121AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1122 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001123}
1124
John Zulauf1507ee42020-05-18 11:33:09 -06001125static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001126 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1127 ? SYNC_ACCESS_INDEX_NONE
1128 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1129 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001130 return stage_access;
1131}
1132static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001133 const auto stage_access =
1134 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1135 ? SYNC_ACCESS_INDEX_NONE
1136 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1137 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001138 return stage_access;
1139}
1140
John Zulauf7635de32020-05-29 17:14:15 -06001141// Caller must manage returned pointer
1142static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001143 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001144 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001145 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1146 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001147 return proxy;
1148}
1149
John Zulaufb02c1eb2020-10-06 16:33:36 -06001150template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001151void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1152 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1153 const ResourceAccessState *infill_state) const {
1154 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1155 if (!attachment_gen) return;
1156
1157 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1158 const AccessAddressType address_type = view_gen.GetAddressType();
1159 for (; range_gen->non_empty(); ++range_gen) {
1160 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001161 }
John Zulauf62f10592020-04-03 12:20:02 -06001162}
1163
John Zulauf1d5f9c12022-05-13 14:51:08 -06001164template <typename ResolveOp>
1165void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1166 const ResourceAccessState *infill_state, bool recur_to_infill) {
1167 for (auto address_type : kAddressTypes) {
1168 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1169 recur_to_infill);
1170 }
1171}
1172
John Zulauf7635de32020-05-29 17:14:15 -06001173// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001174bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001175 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001176 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001177 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001178 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1179 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1180 // those affects have not been recorded yet.
1181 //
1182 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1183 // to apply and only copy then, if this proves a hot spot.
1184 std::unique_ptr<AccessContext> proxy_for_prev;
1185 TrackBack proxy_track_back;
1186
John Zulauf355e49b2020-04-24 15:11:15 -06001187 const auto &transitions = rp_state.subpass_transitions[subpass];
1188 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001189 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1190
1191 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001192 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001193 if (prev_needs_proxy) {
1194 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001195 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001196 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001197 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001198 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001199 }
1200 track_back = &proxy_track_back;
1201 }
1202 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001203 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001204 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001205 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001206 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001207 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1208 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1209 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1210 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1211 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1212 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001213 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001214 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1215 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1216 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1217 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1218 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001219 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001220 }
John Zulauf355e49b2020-04-24 15:11:15 -06001221 }
1222 }
1223 return skip;
1224}
1225
John Zulaufbb890452021-12-14 11:30:18 -07001226bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001227 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001228 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001229 bool skip = false;
1230 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001231
John Zulauf1507ee42020-05-18 11:33:09 -06001232 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1233 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001234 const auto &view_gen = attachment_views[i];
1235 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001236 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001237
1238 // Need check in the following way
1239 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1240 // vs. transition
1241 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1242 // for each aspect loaded.
1243
1244 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001245 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001246 const bool is_color = !(has_depth || has_stencil);
1247
1248 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001249 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001250
John Zulaufaff20662020-06-01 14:07:58 -06001251 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001252 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001253
John Zulaufb02c1eb2020-10-06 16:33:36 -06001254 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001255 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001256 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001257 aspect = "color";
1258 } else {
John Zulauf57261402021-08-13 11:32:06 -06001259 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001260 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1261 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001262 aspect = "depth";
1263 }
John Zulauf57261402021-08-13 11:32:06 -06001264 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001265 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1266 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001267 aspect = "stencil";
1268 checked_stencil = true;
1269 }
1270 }
1271
1272 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001273 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001274 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001275 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001276 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001277 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001278 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001279 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1280 " aspect %s during load with loadOp %s.",
1281 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1282 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001283 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001284 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001285 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001286 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001287 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001288 }
1289 }
1290 }
1291 }
1292 return skip;
1293}
1294
John Zulaufaff20662020-06-01 14:07:58 -06001295// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1296// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1297// store is part of the same Next/End operation.
1298// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001299bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001300 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001301 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001302 bool skip = false;
1303 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001304
1305 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1306 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001307 const AttachmentViewGen &view_gen = attachment_views[i];
1308 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001309 const auto &ci = attachment_ci[i];
1310
1311 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1312 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1313 // sake, we treat DONT_CARE as writing.
1314 const bool has_depth = FormatHasDepth(ci.format);
1315 const bool has_stencil = FormatHasStencil(ci.format);
1316 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001317 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001318 if (!has_stencil && !store_op_stores) continue;
1319
1320 HazardResult hazard;
1321 const char *aspect = nullptr;
1322 bool checked_stencil = false;
1323 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001324 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1325 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001326 aspect = "color";
1327 } else {
John Zulauf57261402021-08-13 11:32:06 -06001328 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001329 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001330 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1331 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001332 aspect = "depth";
1333 }
1334 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001335 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1336 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001337 aspect = "stencil";
1338 checked_stencil = true;
1339 }
1340 }
1341
1342 if (hazard.hazard) {
1343 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1344 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001345 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1346 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1347 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001348 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1349 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001350 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001351 }
1352 }
1353 }
1354 return skip;
1355}
1356
John Zulaufbb890452021-12-14 11:30:18 -07001357bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001358 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001359 CMD_TYPE cmd_type, uint32_t subpass) const {
1360 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001361 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001362 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001363}
1364
John Zulauf06f6f1e2022-04-19 15:28:11 -06001365void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1366
John Zulauf3d84f1b2020-03-09 13:33:25 -06001367class HazardDetector {
1368 SyncStageAccessIndex usage_index_;
1369
1370 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001371 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001372 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001373 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001374 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001375 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001376};
1377
John Zulauf69133422020-05-20 14:55:53 -06001378class HazardDetectorWithOrdering {
1379 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001380 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001381
1382 public:
1383 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001384 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001385 }
John Zulauf14940722021-04-12 15:19:02 -06001386 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001387 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001388 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001389 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001390};
1391
John Zulauf16adfc92020-04-08 10:28:33 -06001392HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001393 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001394 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001395 const auto base_address = ResourceBaseAddress(buffer);
1396 HazardDetector detector(usage_index);
1397 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001398}
1399
John Zulauf69133422020-05-20 14:55:53 -06001400template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001401HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1402 DetectOptions options) const {
1403 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1404 if (!attachment_gen) return HazardResult();
1405
1406 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1407 const auto address_type = view_gen.GetAddressType();
1408 for (; range_gen->non_empty(); ++range_gen) {
1409 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1410 if (hazard.hazard) return hazard;
1411 }
1412
1413 return HazardResult();
1414}
1415
1416template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001417HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1418 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001419 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001420 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001421 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001422 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001423 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001424 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001425 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001426 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001427 if (hazard.hazard) return hazard;
1428 }
1429 return HazardResult();
1430}
John Zulauf110413c2021-03-20 05:38:38 -06001431template <typename Detector>
1432HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001433 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1434 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001435 if (!SimpleBinding(image)) return HazardResult();
1436 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001437 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1438 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001439 const auto address_type = ImageAddressType(image);
1440 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001441 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1442 if (hazard.hazard) return hazard;
1443 }
1444 return HazardResult();
1445}
John Zulauf69133422020-05-20 14:55:53 -06001446
John Zulauf540266b2020-04-06 18:54:53 -06001447HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1448 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001449 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001450 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1451 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001452 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001453 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001454}
1455
1456HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001457 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001458 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001459 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001460}
1461
John Zulaufd0ec59f2021-03-13 14:25:08 -07001462HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1463 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1464 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1465 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1466}
1467
John Zulauf69133422020-05-20 14:55:53 -06001468HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001469 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001470 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001471 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001472 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001473}
1474
John Zulauf3d84f1b2020-03-09 13:33:25 -06001475class BarrierHazardDetector {
1476 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001477 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001478 SyncStageAccessFlags src_access_scope)
1479 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1480
John Zulauf5f13a792020-03-10 07:31:21 -06001481 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001482 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001483 }
John Zulauf14940722021-04-12 15:19:02 -06001484 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001485 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001486 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001487 }
1488
1489 private:
1490 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001491 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001492 SyncStageAccessFlags src_access_scope_;
1493};
1494
John Zulauf4a6105a2020-11-17 15:11:05 -07001495class EventBarrierHazardDetector {
1496 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001497 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001498 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001499 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001500 : usage_index_(usage_index),
1501 src_exec_scope_(src_exec_scope),
1502 src_access_scope_(src_access_scope),
1503 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001504 scope_queue_id_(queue_id),
1505 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001506 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001507 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001508
John Zulaufe0757ba2022-06-10 16:51:45 -06001509 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1510 // Need to piece together coverage of pos->first range:
1511 // Copy the range as we'll be chopping it up as needed
1512 ResourceAccessRange range = pos->first;
1513 const ResourceAccessState &access = pos->second;
1514 HazardResult hazard;
1515
1516 bool in_scope = AdvanceScope(range);
1517 bool unscoped_tested = false;
1518 while (in_scope && !hazard.IsHazard()) {
1519 if (range.begin < ScopeBegin()) {
1520 if (!unscoped_tested) {
1521 unscoped_tested = true;
1522 hazard = access.DetectHazard(usage_index_);
1523 }
1524 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1525 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1526 range.begin = ScopeBegin();
1527 } else { // in_scope implied that ScopeRange and range intersect
1528 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1529 scope_tag_);
1530 if (!hazard.IsHazard()) {
1531 range.begin = ScopeEnd();
1532 in_scope = AdvanceScope(range); // contains a non_empty check
1533 }
1534 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001535 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001536 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1537 hazard = access.DetectHazard(usage_index_);
1538 }
1539 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001540 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001541
John Zulauf14940722021-04-12 15:19:02 -06001542 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001543 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1544 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1545 }
1546
1547 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001548 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1549 bool ScopeValid() const { return !ScopeInvalid(); }
1550 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1551
1552 // Hiding away the std::pair grunge...
1553 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1554 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1555 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1556 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1557
1558 bool AdvanceScope(const ResourceAccessRange &range) {
1559 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1560 if (!range.non_empty()) return false;
1561 if (ScopeInvalid()) return false;
1562
1563 if (ScopeRange().strictly_less(range)) {
1564 ScopeSeek(range);
1565 }
1566
1567 return ScopeValid() && ScopeRange().intersects(range);
1568 }
1569
John Zulauf4a6105a2020-11-17 15:11:05 -07001570 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001571 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001572 SyncStageAccessFlags src_access_scope_;
1573 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001574 QueueId scope_queue_id_;
1575 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001576 SyncEventState::ScopeMap::const_iterator scope_pos_;
1577 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001578};
1579
John Zulaufe0757ba2022-06-10 16:51:45 -06001580HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1581 VkPipelineStageFlags2KHR src_exec_scope,
1582 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1583 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001584 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1585 // first access scope map to use, and there's no easy way to plumb it in below.
1586 const auto address_type = ImageAddressType(image);
1587 const auto &event_scope = sync_event.FirstScope(address_type);
1588
1589 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001590 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001591 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001592}
1593
John Zulaufd0ec59f2021-03-13 14:25:08 -07001594HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1595 DetectOptions options) const {
1596 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1597 barrier.src_access_scope);
1598 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1599}
1600
Jeremy Gebben40a22942020-12-22 14:22:06 -07001601HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001602 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001603 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001604 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001605 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001606 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001607}
1608
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001609HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001610 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001611 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001612}
John Zulauf355e49b2020-04-24 15:11:15 -06001613
John Zulauf9cb530d2019-09-30 14:14:10 -06001614template <typename Flags, typename Map>
1615SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1616 SyncStageAccessFlags scope = 0;
1617 for (const auto &bit_scope : map) {
1618 if (flag_mask < bit_scope.first) break;
1619
1620 if (flag_mask & bit_scope.first) {
1621 scope |= bit_scope.second;
1622 }
1623 }
1624 return scope;
1625}
1626
Jeremy Gebben40a22942020-12-22 14:22:06 -07001627SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001628 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1629}
1630
Jeremy Gebben40a22942020-12-22 14:22:06 -07001631SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1632 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001633}
1634
Jeremy Gebben40a22942020-12-22 14:22:06 -07001635// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1636SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001637 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1638 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1639 // of the union of all stage/access types for all the stages and the same unions for the access mask...
John Zulauf9cb530d2019-09-30 14:14:10 -06001640 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1641}
1642
1643template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001644void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001645 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1646 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001647 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001648 auto pos = accesses->lower_bound(range);
1649 if (pos == accesses->end() || !pos->first.intersects(range)) {
1650 // The range is empty, fill it with a default value.
1651 pos = action.Infill(accesses, pos, range);
1652 } else if (range.begin < pos->first.begin) {
1653 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001654 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001655 } else if (pos->first.begin < range.begin) {
1656 // Trim the beginning if needed
1657 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1658 ++pos;
1659 }
1660
1661 const auto the_end = accesses->end();
1662 while ((pos != the_end) && pos->first.intersects(range)) {
1663 if (pos->first.end > range.end) {
1664 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1665 }
1666
1667 pos = action(accesses, pos);
1668 if (pos == the_end) break;
1669
1670 auto next = pos;
1671 ++next;
1672 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1673 // Need to infill if next is disjoint
1674 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001675 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001676 next = action.Infill(accesses, next, new_range);
1677 }
1678 pos = next;
1679 }
1680}
John Zulaufd5115702021-01-18 12:34:33 -07001681
1682// Give a comparable interface for range generators and ranges
1683template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001684void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001685 assert(range);
1686 UpdateMemoryAccessState(accesses, *range, action);
1687}
1688
John Zulauf4a6105a2020-11-17 15:11:05 -07001689template <typename Action, typename RangeGen>
1690void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1691 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001692 RangeGen &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
John Zulauf4a6105a2020-11-17 15:11:05 -07001693 for (; range_gen->non_empty(); ++range_gen) {
1694 UpdateMemoryAccessState(accesses, *range_gen, action);
1695 }
1696}
John Zulauf9cb530d2019-09-30 14:14:10 -06001697
John Zulaufd0ec59f2021-03-13 14:25:08 -07001698template <typename Action, typename RangeGen>
1699void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1700 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1701 for (; range_gen->non_empty(); ++range_gen) {
1702 UpdateMemoryAccessState(accesses, *range_gen, action);
1703 }
1704}
John Zulauf9cb530d2019-09-30 14:14:10 -06001705struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001706 using Iterator = ResourceAccessRangeMap::iterator;
1707 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001708 // this is only called on gaps, and never returns a gap.
1709 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001710 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001711 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001712 }
John Zulauf5f13a792020-03-10 07:31:21 -06001713
John Zulauf5c5e88d2019-12-26 11:22:02 -07001714 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001715 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001716 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001717 return pos;
1718 }
1719
John Zulauf43cc7462020-12-03 12:33:12 -07001720 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001721 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001722 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001723 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001724 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001725 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001726 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001727 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001728};
1729
John Zulauf4a6105a2020-11-17 15:11:05 -07001730// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001731struct PipelineBarrierOp {
1732 SyncBarrier barrier;
1733 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001734 ResourceAccessState::QueueScopeOps scope;
1735 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1736 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001737 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001738 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001739};
John Zulauf00119522022-05-23 19:07:42 -06001740
John Zulaufecf4ac52022-06-06 10:08:42 -06001741// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1742struct BatchBarrierOp : public PipelineBarrierOp {
1743 void operator()(ResourceAccessState *access_state) const {
1744 access_state->ApplyBarrier(scope, barrier, layout_transition);
1745 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1746 }
1747 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1748};
1749
John Zulauf4a6105a2020-11-17 15:11:05 -07001750// The barrier operation for wait events
1751struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001752 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001753 SyncBarrier barrier;
1754 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001755
1756 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001757 bool layout_transition_)
John Zulaufe0757ba2022-06-10 16:51:45 -06001758 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
John Zulaufb7578302022-05-19 13:50:18 -06001759 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001760};
John Zulauf1e331ec2020-12-04 18:29:38 -07001761
John Zulauf4a6105a2020-11-17 15:11:05 -07001762// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1763// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1764// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001765template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001766class ApplyBarrierOpsFunctor {
1767 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001768 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001769 // Only called with a gap, and pos at the lower_bound(range)
1770 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1771 if (!infill_default_) {
1772 return pos;
1773 }
1774 ResourceAccessState default_state;
1775 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1776 return inserted;
1777 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001778
John Zulauf5c628d02021-05-04 15:46:36 -06001779 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001780 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001781 for (const auto &op : barrier_ops_) {
1782 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001783 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001784
John Zulauf89311b42020-09-29 16:28:47 -06001785 if (resolve_) {
1786 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1787 // another walk
1788 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001789 }
1790 return pos;
1791 }
1792
John Zulauf89311b42020-09-29 16:28:47 -06001793 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001794 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1795 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001796 barrier_ops_.reserve(size_hint);
1797 }
John Zulauf5c628d02021-05-04 15:46:36 -06001798 void EmplaceBack(const BarrierOp &op) {
1799 barrier_ops_.emplace_back(op);
1800 infill_default_ |= op.layout_transition;
1801 }
John Zulauf89311b42020-09-29 16:28:47 -06001802
1803 private:
1804 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001805 bool infill_default_;
1806 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001807 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001808};
1809
John Zulauf4a6105a2020-11-17 15:11:05 -07001810// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1811// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1812template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001813class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1814 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1815
John Zulauf4a6105a2020-11-17 15:11:05 -07001816 public:
John Zulaufee984022022-04-13 16:39:50 -06001817 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001818};
1819
John Zulauf1e331ec2020-12-04 18:29:38 -07001820// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001821class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1822 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1823
John Zulauf1e331ec2020-12-04 18:29:38 -07001824 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001825 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001826};
1827
John Zulauf8e3c3e92021-01-06 11:19:36 -07001828void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001829 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001830 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001831 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001832}
1833
John Zulauf8e3c3e92021-01-06 11:19:36 -07001834void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001835 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001836 if (!SimpleBinding(buffer)) return;
1837 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001838 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001839}
John Zulauf355e49b2020-04-24 15:11:15 -06001840
John Zulauf8e3c3e92021-01-06 11:19:36 -07001841void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001842 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1843 if (!SimpleBinding(image)) return;
1844 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001845 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001846 const auto address_type = ImageAddressType(image);
1847 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1848 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1849}
1850void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001851 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001852 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001853 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001854 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001855 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001856 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001857 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001858 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001859 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001860}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001861
1862void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001863 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001864 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1865 if (!gen) return;
1866 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1867 const auto address_type = view_gen.GetAddressType();
1868 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1869 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001870}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001871
John Zulauf8e3c3e92021-01-06 11:19:36 -07001872void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001873 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001874 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001875 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1876 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001877 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001878}
1879
John Zulaufd0ec59f2021-03-13 14:25:08 -07001880template <typename Action, typename RangeGen>
1881void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1882 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1883 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001884}
1885
1886template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001887void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1888 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1889 if (!gen) return;
1890 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001891}
1892
John Zulaufd0ec59f2021-03-13 14:25:08 -07001893void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1894 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001895 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001896 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001897 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001898}
1899
John Zulaufd0ec59f2021-03-13 14:25:08 -07001900void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001901 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001902 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001903
1904 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1905 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001906 const auto &view_gen = attachment_views[i];
1907 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001908
1909 const auto &ci = attachment_ci[i];
1910 const bool has_depth = FormatHasDepth(ci.format);
1911 const bool has_stencil = FormatHasStencil(ci.format);
1912 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001913 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001914
1915 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001916 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1917 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001918 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001919 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001920 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1921 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001922 }
John Zulauf57261402021-08-13 11:32:06 -06001923 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001924 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001925 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1926 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001927 }
1928 }
1929 }
1930 }
1931}
1932
John Zulauf540266b2020-04-06 18:54:53 -06001933template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001934void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001935 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001936 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001937 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001938 }
1939}
1940
1941void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001942 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1943 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001944 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001945 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001946 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001947 }
1948 }
1949}
1950
John Zulauf4fa68462021-04-26 21:04:22 -06001951// Caller must ensure that lifespan of this is less than from
1952void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1953
John Zulauf355e49b2020-04-24 15:11:15 -06001954// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001955HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1956 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001957
John Zulauf355e49b2020-04-24 15:11:15 -06001958 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001959 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001960
1961 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001962 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1963 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001964 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001965 if (!hazard.hazard) {
1966 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001967 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001968 }
John Zulaufa0a98292020-09-18 09:30:10 -06001969
John Zulauf355e49b2020-04-24 15:11:15 -06001970 return hazard;
1971}
1972
John Zulaufb02c1eb2020-10-06 16:33:36 -06001973void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001974 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001975 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001976 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001977 for (const auto &transition : transitions) {
1978 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001979 const auto &view_gen = attachment_views[transition.attachment];
1980 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001981
1982 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1983 assert(trackback);
1984
1985 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001986 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001987 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001988 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001989 auto &target_map = GetAccessStateMap(address_type);
1990 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001991 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1992 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001993 }
1994
John Zulauf86356ca2020-10-19 11:46:41 -06001995 // If there were no transitions skip this global map walk
1996 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001997 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001998 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001999 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002000}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002001
sjfricke0bea06e2022-06-05 09:22:26 +09002002bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002003 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002004 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002005 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002006 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002007 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002008 return skip;
2009 }
sjfricke0bea06e2022-06-05 09:22:26 +09002010 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002011
2012 using DescriptorClass = cvdescriptorset::DescriptorClass;
2013 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2014 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002015 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2016
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002017 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002018 const auto raster_state = pipe->RasterizationState();
2019 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002020 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002021 }
locke-lunarg61870c22020-06-09 14:51:50 -06002022 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002023 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002024 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2025 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002026 SyncStageAccessIndex sync_index =
2027 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2028
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002029 for (uint32_t index = 0; index < binding->count; index++) {
2030 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002031 switch (descriptor->GetClass()) {
2032 case DescriptorClass::ImageSampler:
2033 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002034 if (descriptor->Invalid()) {
2035 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002036 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002037
2038 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2039 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2040 const auto *img_view_state = image_descriptor->GetImageViewState();
2041 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2042
John Zulauf361fb532020-07-22 10:45:39 -06002043 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002044 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2045 // Descriptors, so we do not have to worry about depth slicing here.
2046 // See: VUID 00343
2047 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002048 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002049 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002050
2051 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2052 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2053 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002054 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002055 hazard =
2056 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2057 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002058 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002059 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2060 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002061 }
John Zulauf110413c2021-03-20 05:38:38 -06002062
John Zulauf33fc1d52020-07-17 11:01:10 -06002063 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002064 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002065 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002066 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2067 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002068 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002069 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2070 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2071 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002072 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2073 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002074 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002075 }
2076 break;
2077 }
2078 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002079 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2080 if (texel_descriptor->Invalid()) {
2081 continue;
2082 }
2083 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2084 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002085 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002086 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002087 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002088 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002089 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002090 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002091 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002092 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2093 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2094 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002095 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002096 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002097 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002098 }
2099 break;
2100 }
2101 case DescriptorClass::GeneralBuffer: {
2102 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002103 if (buffer_descriptor->Invalid()) {
2104 continue;
2105 }
2106 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002107 const ResourceAccessRange range =
2108 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002109 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002110 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002111 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002112 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002113 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002114 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002115 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2116 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2117 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002118 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002119 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002120 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002121 }
2122 break;
2123 }
2124 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2125 default:
2126 break;
2127 }
2128 }
2129 }
2130 }
2131 return skip;
2132}
2133
2134void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002135 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002136 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002137 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002138 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002139 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002140 return;
2141 }
2142
2143 using DescriptorClass = cvdescriptorset::DescriptorClass;
2144 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2145 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002146 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2147
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002148 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002149 const auto raster_state = pipe->RasterizationState();
2150 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002151 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002152 }
locke-lunarg61870c22020-06-09 14:51:50 -06002153 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002154 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002155 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2156 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002157 SyncStageAccessIndex sync_index =
2158 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2159
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002160 for (uint32_t i = 0; i < binding->count; i++) {
2161 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002162 switch (descriptor->GetClass()) {
2163 case DescriptorClass::ImageSampler:
2164 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002165 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2166 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2167 if (image_descriptor->Invalid()) {
2168 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002169 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002170 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002171 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2172 // Descriptors, so we do not have to worry about depth slicing here.
2173 // See: VUID 00343
2174 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002175 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002176 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002177 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2178 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2179 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2180 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002181 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002182 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2183 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002184 }
locke-lunarg61870c22020-06-09 14:51:50 -06002185 break;
2186 }
2187 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002188 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2189 if (texel_descriptor->Invalid()) {
2190 continue;
2191 }
2192 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2193 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002194 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002195 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002196 break;
2197 }
2198 case DescriptorClass::GeneralBuffer: {
2199 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002200 if (buffer_descriptor->Invalid()) {
2201 continue;
2202 }
2203 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002204 const ResourceAccessRange range =
2205 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002206 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002207 break;
2208 }
2209 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2210 default:
2211 break;
2212 }
2213 }
2214 }
2215 }
2216}
2217
sjfricke0bea06e2022-06-05 09:22:26 +09002218bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002219 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002220 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002221 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002222 return skip;
2223 }
2224
2225 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2226 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002227 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002228
2229 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002230 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002231 if (binding_description.binding < binding_buffers_size) {
2232 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002233 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002234
locke-lunarg1ae57d62020-11-18 10:49:19 -07002235 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002236 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2237 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002238 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002239 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002240 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002241 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002242 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002243 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2244 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002245 }
2246 }
2247 }
2248 return skip;
2249}
2250
John Zulauf14940722021-04-12 15:19:02 -06002251void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002252 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002253 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002254 return;
2255 }
2256 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2257 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002258 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002259
2260 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002261 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002262 if (binding_description.binding < binding_buffers_size) {
2263 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002264 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002265
locke-lunarg1ae57d62020-11-18 10:49:19 -07002266 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002267 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2268 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002269 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2270 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002271 }
2272 }
2273}
2274
sjfricke0bea06e2022-06-05 09:22:26 +09002275bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002276 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002277 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002278 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002279 }
locke-lunarg61870c22020-06-09 14:51:50 -06002280
locke-lunarg1ae57d62020-11-18 10:49:19 -07002281 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002282 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002283 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2284 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002285 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002286 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002287 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002288 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002289 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2290 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002291 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002292 }
2293
2294 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2295 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002296 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002297 return skip;
2298}
2299
John Zulauf14940722021-04-12 15:19:02 -06002300void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002301 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) return;
locke-lunarg61870c22020-06-09 14:51:50 -06002302
locke-lunarg1ae57d62020-11-18 10:49:19 -07002303 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002304 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002305 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2306 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002307 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002308
2309 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2310 // We will detect more accurate range in the future.
2311 RecordDrawVertex(UINT32_MAX, 0, tag);
2312}
2313
sjfricke0bea06e2022-06-05 09:22:26 +09002314bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002315 bool skip = false;
2316 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002317 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002318 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002319}
2320
John Zulauf14940722021-04-12 15:19:02 -06002321void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002322 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002323 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002324 }
locke-lunarg61870c22020-06-09 14:51:50 -06002325}
2326
John Zulauf00119522022-05-23 19:07:42 -06002327QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2328
sjfricke0bea06e2022-06-05 09:22:26 +09002329ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002330 const VkRect2D &render_area,
2331 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002332 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002333 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2334 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulaufab84f242022-08-04 18:38:40 -06002335 render_pass_contexts_.emplace_back(layer_data::make_unique<RenderPassAccessContext>(rp_state, render_area, GetQueueFlags(),
2336 attachment_views, &cb_access_context_));
2337 current_renderpass_context_ = render_pass_contexts_.back().get();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002338 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002339 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002340 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002341}
2342
sjfricke0bea06e2022-06-05 09:22:26 +09002343ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002344 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002345 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002346
sjfricke0bea06e2022-06-05 09:22:26 +09002347 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2348 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2349 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002350
2351 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002352 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002353 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002354}
2355
sjfricke0bea06e2022-06-05 09:22:26 +09002356ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002357 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002358 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002359
sjfricke0bea06e2022-06-05 09:22:26 +09002360 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2361 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002362
2363 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002364 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002365 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002366 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002367}
2368
John Zulauf4a6105a2020-11-17 15:11:05 -07002369void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2370 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002371 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002372 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002373 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002374 }
2375}
2376
John Zulaufae842002021-04-15 18:20:55 -06002377// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002378bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002379 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002380 if (!exec_context.ValidForSyncOps()) return false;
2381
2382 const QueueId queue_id = exec_context.GetQueueId();
2383 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002384 bool skip = false;
2385 ResourceUsageRange tag_range = {0, 0};
2386 const AccessContext *recorded_context = GetCurrentAccessContext();
2387 assert(recorded_context);
2388 HazardResult hazard;
John Zulaufdab327f2022-07-08 12:02:05 -06002389 ReplayGuard replay_guard(exec_context, *this);
2390
John Zulaufbb890452021-12-14 11:30:18 -07002391 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002392 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002393 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002394 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002395 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002396 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002397 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2398 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002399 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002400 };
2401 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002402 // we update the range to any include layout transition first use writes,
2403 // as they are stored along with the source scope (as effective barrier) when recorded
2404 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002405 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002406
John Zulauf0223f142022-07-06 09:05:39 -06002407 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2408 // we need to fetch the current access context each time
John Zulaufdab327f2022-07-08 12:02:05 -06002409 hazard = exec_context.DetectFirstUseHazard(tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002410 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002411 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002412 }
2413 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002414 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002415 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002416 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002417 }
2418
2419 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002420 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002421 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002422 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002423 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002424 }
2425
2426 return skip;
2427}
2428
sjfricke0bea06e2022-06-05 09:22:26 +09002429void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002430 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2431 assert(recorded_context);
2432
2433 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2434 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002435 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002436 // we update the range to any include layout transition first use writes,
2437 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002438 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002439 }
2440
2441 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2442 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002443 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002444}
2445
John Zulauf1d5f9c12022-05-13 14:51:08 -06002446void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002447 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002448 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002449}
2450
John Zulaufdab327f2022-07-08 12:02:05 -06002451HazardResult CommandBufferAccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
2452 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, *GetCurrentAccessContext());
2453}
2454
John Zulauf3c788ef2022-02-22 12:12:30 -07002455ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002456 // The execution references ensure lifespan for the referenced child CB's...
2457 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002458 InsertRecordedAccessLogEntries(recorded_context);
2459 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002460 return tag_range;
2461}
2462
John Zulauf3c788ef2022-02-22 12:12:30 -07002463void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2464 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2465 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2466}
2467
John Zulauf41a9c7c2021-12-07 15:59:53 -07002468ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2469 ResourceUsageTag next = access_log_.size();
2470 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2471 return next;
2472}
2473
2474ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2475 command_number_++;
2476 subcommand_number_ = 0;
2477 ResourceUsageTag next = access_log_.size();
2478 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2479 return next;
2480}
2481
2482ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2483 if (index == 0) {
2484 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2485 }
2486 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2487}
2488
John Zulaufbb890452021-12-14 11:30:18 -07002489void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2490 auto tag = sync_op->Record(this);
2491 // As renderpass operations can have side effects on the command buffer access context,
2492 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002493 sync_ops_.emplace_back(tag, std::move(sync_op));
2494}
2495
John Zulaufae842002021-04-15 18:20:55 -06002496class HazardDetectFirstUse {
2497 public:
John Zulauf0223f142022-07-06 09:05:39 -06002498 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2499 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002500 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002501 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002502 }
2503 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2504 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2505 }
2506
2507 private:
2508 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002509 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002510 const ResourceUsageRange &tag_range_;
2511};
2512
2513// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2514// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002515HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002516 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002517 HazardResult hazard;
2518 for (const auto address_type : kAddressTypes) {
2519 const auto &recorded_access_map = GetAccessStateMap(address_type);
2520 for (const auto &recorded_access : recorded_access_map) {
2521 // Cull any entries not in the current tag range
2522 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002523 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002524 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2525 if (hazard.hazard) break;
2526 }
2527 }
2528
2529 return hazard;
2530}
2531
John Zulaufbb890452021-12-14 11:30:18 -07002532bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002533 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002534 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002535 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002536 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002537 if (!pipe) {
2538 return skip;
2539 }
2540
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002541 const auto raster_state = pipe->RasterizationState();
2542 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002543 return skip;
2544 }
sjfricke0bea06e2022-06-05 09:22:26 +09002545 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002546 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002547 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002548
John Zulauf1a224292020-06-30 14:52:13 -06002549 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002550 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002551 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2552 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002553 if (location >= subpass.colorAttachmentCount ||
2554 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002555 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002556 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002557 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2558 if (!view_gen.IsValid()) continue;
2559 HazardResult hazard =
2560 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2561 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002562 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002563 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002564 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002565 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002566 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002567 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002568 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2569 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002570 }
2571 }
2572 }
locke-lunarg37047832020-06-12 13:44:45 -06002573
2574 // PHASE1 TODO: Add layout based read/vs. write selection.
2575 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002576 const auto ds_state = pipe->DepthStencilState();
2577 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002578
2579 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2580 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2581 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002582 bool depth_write = false, stencil_write = false;
2583
2584 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002585 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002586 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2587 depth_write = true;
2588 }
2589 // PHASE1 TODO: It needs to check if stencil is writable.
2590 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2591 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2592 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002593 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002594 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2595 stencil_write = true;
2596 }
2597
2598 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2599 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002600 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2601 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2602 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002603 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002604 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002605 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002606 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002607 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002608 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002609 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002610 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002611 }
2612 }
2613 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002614 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2615 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2616 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002617 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002618 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002619 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002620 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002621 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002622 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002623 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002624 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002625 }
locke-lunarg61870c22020-06-09 14:51:50 -06002626 }
2627 }
2628 return skip;
2629}
2630
sjfricke0bea06e2022-06-05 09:22:26 +09002631void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2632 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002633 if (!pipe) {
2634 return;
2635 }
2636
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002637 const auto *raster_state = pipe->RasterizationState();
2638 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002639 return;
2640 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002641 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002642 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002643
John Zulauf1a224292020-06-30 14:52:13 -06002644 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002645 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002646 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2647 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002648 if (location >= subpass.colorAttachmentCount ||
2649 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002650 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002651 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002652 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2653 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2654 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2655 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002656 }
2657 }
locke-lunarg37047832020-06-12 13:44:45 -06002658
2659 // PHASE1 TODO: Add layout based read/vs. write selection.
2660 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002661 const auto *ds_state = pipe->DepthStencilState();
2662 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002663 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2664 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2665 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002666 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002667 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2668 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002669
2670 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002671 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2672 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002673 depth_write = true;
2674 }
2675 // PHASE1 TODO: It needs to check if stencil is writable.
2676 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2677 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2678 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002679 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002680 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2681 stencil_write = true;
2682 }
2683
John Zulaufd0ec59f2021-03-13 14:25:08 -07002684 if (depth_write || stencil_write) {
2685 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2686 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2687 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2688 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002689 }
locke-lunarg61870c22020-06-09 14:51:50 -06002690 }
2691}
2692
sjfricke0bea06e2022-06-05 09:22:26 +09002693bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002694 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002695 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002696 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002697 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002698 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002699 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002700
John Zulauf355e49b2020-04-24 15:11:15 -06002701 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002702 if (next_subpass >= subpass_contexts_.size()) {
2703 return skip;
2704 }
John Zulauf1507ee42020-05-18 11:33:09 -06002705 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002706 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002707 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002708 if (!skip) {
2709 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2710 // on a copy of the (empty) next context.
2711 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2712 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002713 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002714 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002715 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002716 }
John Zulauf7635de32020-05-29 17:14:15 -06002717 return skip;
2718}
sjfricke0bea06e2022-06-05 09:22:26 +09002719bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002720 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002721 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002722 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002723 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002724 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2725 cmd_type);
2726 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002727 return skip;
2728}
2729
John Zulauf64ffe552021-02-06 10:25:07 -07002730AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002731 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002732}
2733
John Zulaufbb890452021-12-14 11:30:18 -07002734bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002735 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002736 bool skip = false;
2737
John Zulauf7635de32020-05-29 17:14:15 -06002738 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2739 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2740 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2741 // to apply and only copy then, if this proves a hot spot.
2742 std::unique_ptr<AccessContext> proxy_for_current;
2743
John Zulauf355e49b2020-04-24 15:11:15 -06002744 // Validate the "finalLayout" transitions to external
2745 // Get them from where there we're hidding in the extra entry.
2746 const auto &final_transitions = rp_state_->subpass_transitions.back();
2747 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002748 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002749 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002750 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2751 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002752
2753 if (transition.prev_pass == current_subpass_) {
2754 if (!proxy_for_current) {
2755 // 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 -07002756 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002757 }
2758 context = proxy_for_current.get();
2759 }
2760
John Zulaufa0a98292020-09-18 09:30:10 -06002761 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2762 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002763 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002764 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002765 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002766 if (hazard.tag == kInvalidTag) {
2767 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002768 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002769 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2770 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2771 " final image layout transition (old_layout: %s, new_layout: %s).",
2772 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2773 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2774 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002775 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002776 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2777 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2778 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2779 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2780 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002781 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002782 }
John Zulauf355e49b2020-04-24 15:11:15 -06002783 }
2784 }
2785 return skip;
2786}
2787
John Zulauf14940722021-04-12 15:19:02 -06002788void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002789 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002790 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002791}
2792
John Zulauf14940722021-04-12 15:19:02 -06002793void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002794 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2795 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002796
2797 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2798 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002799 const AttachmentViewGen &view_gen = attachment_views_[i];
2800 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002801
2802 const auto &ci = attachment_ci[i];
2803 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002804 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002805 const bool is_color = !(has_depth || has_stencil);
2806
2807 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002808 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2809 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2810 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2811 SyncOrdering::kColorAttachment, tag);
2812 }
John Zulauf1507ee42020-05-18 11:33:09 -06002813 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002814 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002815 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2816 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2817 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2818 SyncOrdering::kDepthStencilAttachment, tag);
2819 }
John Zulauf1507ee42020-05-18 11:33:09 -06002820 }
2821 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002822 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2823 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2824 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2825 SyncOrdering::kDepthStencilAttachment, tag);
2826 }
John Zulauf1507ee42020-05-18 11:33:09 -06002827 }
2828 }
2829 }
2830 }
2831}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002832AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2833 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2834 AttachmentViewGenVector view_gens;
2835 VkExtent3D extent = CastTo3D(render_area.extent);
2836 VkOffset3D offset = CastTo3D(render_area.offset);
2837 view_gens.reserve(attachment_views.size());
2838 for (const auto *view : attachment_views) {
2839 view_gens.emplace_back(view, offset, extent);
2840 }
2841 return view_gens;
2842}
John Zulauf64ffe552021-02-06 10:25:07 -07002843RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2844 VkQueueFlags queue_flags,
2845 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2846 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002847 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulaufdab327f2022-07-08 12:02:05 -06002848 // Add this for all subpasses here so that they exist during next subpass validation
2849 InitSubpassContexts(queue_flags, rp_state, external_context, subpass_contexts_);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002850 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002851}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002852void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002853 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002854 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2855 RecordLayoutTransitions(barrier_tag);
2856 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002857}
John Zulauf1507ee42020-05-18 11:33:09 -06002858
John Zulauf41a9c7c2021-12-07 15:59:53 -07002859void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2860 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002861 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002862 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2863 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002864
ziga-lunarg31a3e772022-03-22 11:48:46 +01002865 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2866 return;
2867 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002868 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2869 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002870 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002871 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2872 RecordLayoutTransitions(barrier_tag);
2873 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002874}
2875
John Zulauf41a9c7c2021-12-07 15:59:53 -07002876void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2877 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002878 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002879 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2880 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002881
John Zulauf355e49b2020-04-24 15:11:15 -06002882 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002883 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002884
2885 // Add the "finalLayout" transitions to external
2886 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002887 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2888 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2889 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002890 const auto &final_transitions = rp_state_->subpass_transitions.back();
2891 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002892 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002893 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002894 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002895 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002896 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002897 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002898 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002899 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002900 }
2901}
2902
John Zulauf06f6f1e2022-04-19 15:28:11 -06002903SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2904 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002905 SyncExecScope result;
2906 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002907 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002908 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002909 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002910 return result;
2911}
2912
Jeremy Gebben40a22942020-12-22 14:22:06 -07002913SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002914 SyncExecScope result;
2915 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002916 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2917 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002918 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002919 return result;
2920}
2921
John Zulaufecf4ac52022-06-06 10:08:42 -06002922SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2923 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2924
2925SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2926 : 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 -07002927
2928template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002929SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2930 : src_exec_scope(src),
2931 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2932 dst_exec_scope(dst),
2933 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002934
2935SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002936 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2937 if (barrier) {
2938 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002939 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002940 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002941
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002942 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002943 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002944 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2945
2946 } else {
2947 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002948 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002949 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2950
2951 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002952 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002953 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2954 }
2955}
2956
2957template <typename Barrier>
2958SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2959 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2960 src_exec_scope = src.exec_scope;
2961 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2962
2963 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002964 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002965 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002966}
2967
John Zulaufb02c1eb2020-10-06 16:33:36 -06002968// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2969void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002970 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002971 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002972 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002973 }
2974}
2975
John Zulauf89311b42020-09-29 16:28:47 -06002976// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2977// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2978// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002979void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002980 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002981 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002982 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002983 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002984 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002985 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002986 }
John Zulaufbb890452021-12-14 11:30:18 -07002987 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002988}
John Zulauf9cb530d2019-09-30 14:14:10 -06002989HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2990 HazardResult hazard;
2991 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002992 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002993 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002994 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002995 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002996 }
2997 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002998 // Write operation:
2999 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
3000 // If reads exists -- test only against them because either:
3001 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
3002 // * 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
3003 // the current write happens after the reads, so just test the write against the reades
3004 // Otherwise test against last_write
3005 //
3006 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003007 if (last_reads.size()) {
3008 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003009 if (IsReadHazard(usage_stage, read_access)) {
3010 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3011 break;
3012 }
3013 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003014 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003015 // Write-After-Write check -- if we have a previous write to test against
3016 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003017 }
3018 }
3019 return hazard;
3020}
3021
John Zulaufec943ec2022-06-29 07:52:56 -06003022HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3023 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003024 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003025 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003026}
3027
John Zulaufec943ec2022-06-29 07:52:56 -06003028HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3029 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003030 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3031 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003032 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003033 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003034 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003035 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003036 if (IsRead(usage_bit)) {
3037 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3038 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3039 if (is_raw_hazard) {
3040 // NOTE: we know last_write is non-zero
3041 // See if the ordering rules save us from the simple RAW check above
3042 // First check to see if the current usage is covered by the ordering rules
3043 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3044 const bool usage_is_ordered =
3045 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3046 if (usage_is_ordered) {
3047 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003048 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003049 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003050 }
3051 }
John Zulauf4285ee92020-09-23 10:20:52 -06003052 if (is_raw_hazard) {
3053 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3054 }
John Zulauf5c628d02021-05-04 15:46:36 -06003055 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3056 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003057 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003058 } else {
3059 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003060 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003061 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003062 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003063 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003064 if (usage_write_is_ordered) {
3065 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003066 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003067 }
3068 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3069 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003070 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003071 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3072 if (IsReadHazard(usage_stage, read_access)) {
3073 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3074 break;
3075 }
John Zulaufd14743a2020-07-03 09:42:39 -06003076 }
3077 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003078 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3079 bool ilt_ilt_hazard = false;
3080 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3081 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3082 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3083 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3084 }
3085 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003086 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003087 }
John Zulauf69133422020-05-20 14:55:53 -06003088 }
3089 }
3090 return hazard;
3091}
3092
John Zulaufec943ec2022-06-29 07:52:56 -06003093HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3094 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003095 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003096 using Size = FirstAccesses::size_type;
3097 const auto &recorded_accesses = recorded_use.first_accesses_;
3098 Size count = recorded_accesses.size();
3099 if (count) {
3100 const auto &last_access = recorded_accesses.back();
3101 bool do_write_last = IsWrite(last_access.usage_index);
3102 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003103
John Zulauf4fa68462021-04-26 21:04:22 -06003104 for (Size i = 0; i < count; ++count) {
3105 const auto &first = recorded_accesses[i];
3106 // Skip and quit logic
3107 if (first.tag < tag_range.begin) continue;
3108 if (first.tag >= tag_range.end) {
3109 do_write_last = false; // ignore last since we know it can't be in tag_range
3110 break;
3111 }
3112
John Zulaufec943ec2022-06-29 07:52:56 -06003113 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003114 if (hazard.hazard) {
3115 hazard.AddRecordedAccess(first);
3116 break;
3117 }
3118 }
3119
3120 if (do_write_last && tag_range.includes(last_access.tag)) {
3121 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3122 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3123 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3124 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3125 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3126 // the barrier that applies them
3127 barrier |= recorded_use.first_write_layout_ordering_;
3128 }
3129 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3130 // the active context
3131 if (recorded_use.first_read_stages_) {
3132 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3133 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3134 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3135 // active context.
3136 barrier.exec_scope |= recorded_use.first_read_stages_;
3137 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3138 barrier.access_scope |= FlagBit(last_access.usage_index);
3139 }
John Zulaufec943ec2022-06-29 07:52:56 -06003140 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003141 if (hazard.hazard) {
3142 hazard.AddRecordedAccess(last_access);
3143 }
3144 }
John Zulaufae842002021-04-15 18:20:55 -06003145 }
3146 return hazard;
3147}
3148
John Zulauf2f952d22020-02-10 11:34:51 -07003149// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003150HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003151 HazardResult hazard;
3152 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003153 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3154 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3155 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003156 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003157 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003158 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003159 }
3160 } else {
John Zulauf14940722021-04-12 15:19:02 -06003161 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003162 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003163 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003164 // 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 -07003165 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003166 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003167 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003168 break;
3169 }
3170 }
John Zulauf2f952d22020-02-10 11:34:51 -07003171 }
3172 }
3173 return hazard;
3174}
3175
John Zulaufae842002021-04-15 18:20:55 -06003176HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3177 ResourceUsageTag start_tag) const {
3178 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003179 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003180 // Skip and quit logic
3181 if (first.tag < tag_range.begin) continue;
3182 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003183
3184 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003185 if (hazard.hazard) {
3186 hazard.AddRecordedAccess(first);
3187 break;
3188 }
John Zulaufae842002021-04-15 18:20:55 -06003189 }
3190 return hazard;
3191}
3192
John Zulaufec943ec2022-06-29 07:52:56 -06003193HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3194 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003195 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003196 // Only supporting image layout transitions for now
3197 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3198 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003199 // only test for WAW if there no intervening read operations.
3200 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003201 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003202 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003203 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003204 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003205 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003206 break;
3207 }
3208 }
John Zulaufec943ec2022-06-29 07:52:56 -06003209 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003210 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3211 }
3212
3213 return hazard;
3214}
3215
John Zulaufe0757ba2022-06-10 16:51:45 -06003216HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3217 VkPipelineStageFlags2KHR src_exec_scope,
3218 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3219 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003220 // Only supporting image layout transitions for now
3221 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3222 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003223
John Zulaufe0757ba2022-06-10 16:51:45 -06003224 if ((write_tag >= event_tag) && last_write.any()) {
3225 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3226 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3227 } else {
3228 // only test for WAW if there no intervening read operations.
3229 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3230 if (last_reads.size()) {
3231 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3232 // first scope, or they are a hazard.
3233 const ReadStates &scope_reads = scope_state.last_reads;
3234 const ReadStates::size_type scope_read_count = scope_reads.size();
3235 // Since the hasn't been a write:
3236 // * The current read state is a superset of the scoped one
3237 // * The stage order is the same.
3238 assert(last_reads.size() >= scope_read_count);
3239 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3240 const ReadState &scope_read = scope_reads[read_idx];
3241 const ReadState &current_read = last_reads[read_idx];
3242 assert(scope_read.stage == current_read.stage);
3243 if (current_read.tag > event_tag) {
3244 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3245 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3246 } else {
3247 // The read is in the events first synchronization scope, so we use a barrier hazard check
3248 // If the read stage is not in the src sync scope
3249 // *AND* not execution chained with an existing sync barrier (that's the or)
3250 // then the barrier access is unsafe (R/W after R)
3251 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3252 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3253 break;
3254 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003255 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003256 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003257 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3258 const ReadState &current_read = last_reads[scope_read_count];
3259 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3260 }
3261 } else if (last_write.any()) {
3262 // 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 -07003263 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3264 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003265 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3266 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003267 }
John Zulauf361fb532020-07-22 10:45:39 -06003268 }
John Zulaufd14743a2020-07-03 09:42:39 -06003269 }
John Zulauf361fb532020-07-22 10:45:39 -06003270
John Zulauf0cb5be22020-01-23 12:18:22 -07003271 return hazard;
3272}
3273
John Zulauf5f13a792020-03-10 07:31:21 -06003274// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3275// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3276// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3277void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003278 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003279 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3280 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003281 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003282 } else if (other.write_tag == write_tag) {
3283 // 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 -06003284 // dependency chaining logic or any stage expansion)
3285 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003286 pending_write_barriers |= other.pending_write_barriers;
3287 pending_layout_transition |= other.pending_layout_transition;
3288 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003289 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003290
John Zulaufd14743a2020-07-03 09:42:39 -06003291 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003292 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003293 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003294 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003295 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003296 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003297 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003298 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3299 // but we should wait on profiling data for that.
3300 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003301 auto &my_read = last_reads[my_read_index];
3302 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003303 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003304 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003305 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003306 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003307 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003308 my_read.pending_dep_chain = other_read.pending_dep_chain;
3309 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3310 // May require tracking more than one access per stage.
3311 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003312 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003313 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003314 // Since I'm overwriting the fragement stage read, also update the input attachment info
3315 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003316 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003317 }
John Zulauf14940722021-04-12 15:19:02 -06003318 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003319 // The read tags match so merge the barriers
3320 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003321 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003322 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003323 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003324
John Zulauf5f13a792020-03-10 07:31:21 -06003325 break;
3326 }
3327 }
3328 } else {
3329 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003330 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003331 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003332 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003333 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003334 }
John Zulauf5f13a792020-03-10 07:31:21 -06003335 }
3336 }
John Zulauf361fb532020-07-22 10:45:39 -06003337 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003338 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3339 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003340
3341 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3342 // of the copy and other into this using the update first logic.
3343 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3344 // of the other first_accesses... )
3345 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3346 FirstAccesses firsts(std::move(first_accesses_));
3347 first_accesses_.clear();
3348 first_read_stages_ = 0U;
3349 auto a = firsts.begin();
3350 auto a_end = firsts.end();
3351 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003352 // TODO: Determine whether some tag offset will be needed for PHASE II
3353 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003354 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3355 ++a;
3356 }
3357 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3358 }
3359 for (; a != a_end; ++a) {
3360 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3361 }
3362 }
John Zulauf5f13a792020-03-10 07:31:21 -06003363}
3364
John Zulauf14940722021-04-12 15:19:02 -06003365void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003366 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3367 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003368 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003369 // Mulitple outstanding reads may be of interest and do dependency chains independently
3370 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3371 const auto usage_stage = PipelineStageBit(usage_index);
3372 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003373 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003374 for (auto &read_access : last_reads) {
3375 if (read_access.stage == usage_stage) {
3376 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003377 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003378 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003379 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003380 } else {
3381 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3382 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3383 // that sync_stages is a subset of barriers may not apply.
3384 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003385 }
3386 }
3387 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003388 for (auto &read_access : last_reads) {
3389 if (read_access.barriers & usage_stage) {
3390 read_access.sync_stages |= usage_stage;
3391 }
3392 }
John Zulaufab7756b2020-12-29 16:10:16 -07003393 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003394 last_read_stages |= usage_stage;
3395 }
John Zulauf4285ee92020-09-23 10:20:52 -06003396
3397 // 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 -07003398 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003399 // TODO Revisit re: multiple reads for a given stage
3400 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003401 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003402 } else {
3403 // Assume write
3404 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003405 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003406 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003407 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003408}
John Zulauf5f13a792020-03-10 07:31:21 -06003409
John Zulauf89311b42020-09-29 16:28:47 -06003410// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3411// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3412// We can overwrite them as *this* write is now after them.
3413//
3414// 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 -06003415void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003416 ClearRead();
3417 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003418 write_tag = tag;
3419 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003420}
3421
John Zulauf1d5f9c12022-05-13 14:51:08 -06003422void ResourceAccessState::ClearWrite() {
3423 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3424 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3425 write_barriers.reset();
3426 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3427 last_write.reset();
3428
3429 write_tag = 0;
3430 write_queue = QueueSyncState::kQueueIdInvalid;
3431}
3432
3433void ResourceAccessState::ClearRead() {
3434 last_reads.clear();
3435 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3436}
3437
John Zulauf89311b42020-09-29 16:28:47 -06003438// Apply the memory barrier without updating the existing barriers. The execution barrier
3439// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3440// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3441// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003442template <typename ScopeOps>
3443void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003444 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3445 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003446 // 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 -06003447 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003448 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3449 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003450 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003451 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003452 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003453 if (layout_transition) {
3454 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3455 }
John Zulaufa0a98292020-09-18 09:30:10 -06003456 }
John Zulauf89311b42020-09-29 16:28:47 -06003457 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3458 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003459
John Zulauf89311b42020-09-29 16:28:47 -06003460 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003461 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3462 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003463 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3464
John Zulaufab7756b2020-12-29 16:10:16 -07003465 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003466 // 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 -06003467 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003468 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3469 stages_in_scope |= read_access.stage;
3470 }
3471 }
3472
3473 for (auto &read_access : last_reads) {
3474 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3475 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3476 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3477 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003478 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003479 }
3480 }
John Zulaufa0a98292020-09-18 09:30:10 -06003481 }
John Zulaufa0a98292020-09-18 09:30:10 -06003482}
3483
John Zulauf14940722021-04-12 15:19:02 -06003484void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003485 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003486 // 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 -06003487 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003488 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003489 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3490 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003491 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003492 }
John Zulauf89311b42020-09-29 16:28:47 -06003493
3494 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003495 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003496 for (auto &read_access : last_reads) {
3497 read_access.barriers |= read_access.pending_dep_chain;
3498 read_execution_barriers |= read_access.barriers;
3499 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003500 }
3501
3502 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3503 write_dependency_chain |= pending_write_dep_chain;
3504 write_barriers |= pending_write_barriers;
3505 pending_write_dep_chain = 0;
3506 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003507}
3508
John Zulaufecf4ac52022-06-06 10:08:42 -06003509// Assumes signal queue != wait queue
3510void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3511 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3512 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3513 assert(signal.queue != wait.queue);
3514 for (auto &read_access : last_reads) {
3515 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3516 // Deflects WAR on wait queue
3517 read_access.barriers = wait.exec_scope;
3518 } else {
3519 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3520 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3521 }
3522 }
3523 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3524 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3525 read_execution_barriers = wait.exec_scope;
3526 write_barriers = wait.valid_accesses;
3527 } else {
3528 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3529 write_barriers.reset();
3530 }
3531 write_dependency_chain = read_execution_barriers;
3532}
3533
John Zulauf3da08bb2022-08-01 17:56:56 -06003534bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) const {
3535 return (usage_queue == queue) && (usage_tag <= tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003536}
3537
John Zulauf3da08bb2022-08-01 17:56:56 -06003538bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) const { return queue == usage_queue; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003539
John Zulauf3da08bb2022-08-01 17:56:56 -06003540bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) const { return tag <= usage_tag; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003541
3542// Return if the resulting state is "empty"
3543template <typename Pred>
3544bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3545 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3546
3547 // Use the predicate to build a mask of the read stages we are synchronizing
3548 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003549 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003550 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003551 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3552 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003553 }
3554 }
3555
John Zulauf434c4e62022-05-19 16:03:56 -06003556 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3557 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3558 uint32_t unsync_count = 0;
3559 for (auto &read_access : last_reads) {
3560 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3561 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3562 sync_reads |= read_access.stage;
3563 } else {
3564 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003565 }
3566 }
3567
3568 if (unsync_count) {
3569 if (sync_reads) {
3570 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3571 ReadStates unsync_reads;
3572 unsync_reads.reserve(unsync_count);
3573 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3574 for (auto &read_access : last_reads) {
3575 if (0 == (read_access.stage & sync_reads)) {
3576 unsync_reads.emplace_back(read_access);
3577 unsync_read_stages |= read_access.stage;
3578 }
3579 }
3580 last_read_stages = unsync_read_stages;
3581 last_reads = std::move(unsync_reads);
3582 }
3583 } else {
3584 // Nothing remains (or it was empty to begin with)
3585 ClearRead();
3586 }
3587
3588 bool all_clear = last_reads.size() == 0;
3589 if (last_write.any()) {
3590 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3591 // Clear any predicated write, or any the write from any any access with synchronized reads.
3592 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3593 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3594 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3595 ClearWrite();
3596 } else {
3597 all_clear = false;
3598 }
3599 }
3600 return all_clear;
3601}
3602
John Zulaufae842002021-04-15 18:20:55 -06003603bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3604 if (!first_accesses_.size()) return false;
3605 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3606 return tag_range.intersects(first_access_range);
3607}
3608
John Zulauf1d5f9c12022-05-13 14:51:08 -06003609void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3610 if (last_write.any()) write_tag += offset;
3611 for (auto &read_access : last_reads) {
3612 read_access.tag += offset;
3613 }
3614 for (auto &first : first_accesses_) {
3615 first.tag += offset;
3616 }
3617}
3618
3619ResourceAccessState::ResourceAccessState()
3620 : write_barriers(~SyncStageAccessFlags(0)),
3621 write_dependency_chain(0),
3622 write_tag(),
3623 write_queue(QueueSyncState::kQueueIdInvalid),
3624 last_write(0),
3625 input_attachment_read(false),
3626 last_read_stages(0),
3627 read_execution_barriers(0),
3628 pending_write_dep_chain(0),
3629 pending_layout_transition(false),
3630 pending_write_barriers(0),
3631 pending_layout_ordering_(),
3632 first_accesses_(),
3633 first_read_stages_(0U),
3634 first_write_layout_ordering_() {}
3635
John Zulauf59e25072020-07-17 10:55:21 -06003636// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003637VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3638 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003639
John Zulaufab7756b2020-12-29 16:10:16 -07003640 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003641 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003642 barriers = read_access.barriers;
3643 break;
John Zulauf59e25072020-07-17 10:55:21 -06003644 }
3645 }
John Zulauf4285ee92020-09-23 10:20:52 -06003646
John Zulauf59e25072020-07-17 10:55:21 -06003647 return barriers;
3648}
3649
John Zulauf1d5f9c12022-05-13 14:51:08 -06003650void ResourceAccessState::SetQueueId(QueueId id) {
3651 for (auto &read_access : last_reads) {
3652 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3653 read_access.queue = id;
3654 }
3655 }
3656 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3657 write_queue = id;
3658 }
3659}
3660
John Zulauf00119522022-05-23 19:07:42 -06003661bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3662 return 0 != (write_dependency_chain & src_exec_scope);
3663}
3664
3665bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3666 return (src_access_scope & last_write).any();
3667}
3668
John Zulaufec943ec2022-06-29 07:52:56 -06003669bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3670 return (write_barriers & src_access_scope).any();
3671}
3672
John Zulaufb7578302022-05-19 13:50:18 -06003673bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3674 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003675 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3676}
3677
3678bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3679 SyncStageAccessFlags src_access_scope) const {
3680 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003681}
3682
John Zulaufe0757ba2022-06-10 16:51:45 -06003683bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3684 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003685 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3686 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3687 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003688 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003689}
3690
John Zulaufec943ec2022-06-29 07:52:56 -06003691bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3692 const SyncStageAccessFlags &src_access_scope) const {
3693 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3694}
3695
John Zulaufcb7e1672022-05-04 13:46:08 -06003696bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003697 assert(IsRead(usage));
3698 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3699 // * the previous reads are not hazards, and thus last_write must be visible and available to
3700 // any reads that happen after.
3701 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3702 // 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 -07003703 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003704}
3705
John Zulaufec943ec2022-06-29 07:52:56 -06003706VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3707 // At apply queue submission order limits on the effect of ordering
3708 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3709 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3710 for (const auto &read_access : last_reads) {
3711 if (read_access.queue != queue_id) {
3712 non_qso_stages |= read_access.stage;
3713 }
3714 }
3715 }
John Zulauf4285ee92020-09-23 10:20:52 -06003716 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003717 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3718 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003719 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003720 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003721 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003722 // 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 -07003723 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003724 }
3725
3726 return ordered_stages;
3727}
3728
John Zulauf14940722021-04-12 15:19:02 -06003729void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003730 // Only record until we record a write.
3731 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003732 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003733 if (0 == (usage_stage & first_read_stages_)) {
3734 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003735 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003736 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003737 if (0 == (read_execution_barriers & usage_stage)) {
3738 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3739 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3740 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003741 }
3742 }
3743}
3744
John Zulauf4fa68462021-04-26 21:04:22 -06003745void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3746 // Only call this after recording an image layout transition
3747 assert(first_accesses_.size());
3748 if (first_accesses_.back().tag == tag) {
3749 // 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 +02003750 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003751 first_write_layout_ordering_ = layout_ordering;
3752 }
3753}
3754
John Zulauf1d5f9c12022-05-13 14:51:08 -06003755ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3756 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3757 : stage(stage_),
3758 access(access_),
3759 barriers(barriers_),
3760 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3761 tag(tag_),
3762 queue(QueueSyncState::kQueueIdInvalid),
3763 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3764
John Zulaufee984022022-04-13 16:39:50 -06003765void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3766 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3767 stage = stage_;
3768 access = access_;
3769 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003770 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003771 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003772 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 -06003773}
3774
John Zulauf00119522022-05-23 19:07:42 -06003775// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3776// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3777// that have bee applied (via semaphore) to those accesses can be chained off of.
3778bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3779 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3780 return (exec_scope & effective_stages) != 0;
3781}
3782
John Zulauf697c0e12022-04-19 16:31:12 -06003783ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3784 ResourceUsageRange reserve;
3785 reserve.begin = tag_limit_.fetch_add(tag_count);
3786 reserve.end = reserve.begin + tag_count;
3787 return reserve;
3788}
3789
John Zulauf3da08bb2022-08-01 17:56:56 -06003790void SyncValidator::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
3791 // We need to go through every queue batch context and clear all accesses this wait synchronizes
3792 // As usual -- two groups, the "last batch" and the signaled semaphores
3793 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
3794 // QueueBatchContext, track which we've done to avoid duplicate traversals
3795 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
3796 for (auto &batch : queue_batch_contexts) {
3797 batch->ApplyTaggedWait(queue_id, tag);
3798 }
3799}
3800
3801void SyncValidator::UpdateFenceWaitInfo(VkFence fence, QueueId queue_id, ResourceUsageTag tag) {
3802 if (fence != VK_NULL_HANDLE) {
3803 // Overwrite the current fence wait information
3804 // NOTE: Not doing fence usage validation here, leaving that in CoreChecks intentionally
3805 auto fence_state = Get<FENCE_STATE>(fence);
3806 waitable_fences_[fence] = {fence_state, tag, queue_id};
3807 }
3808}
3809
3810void SyncValidator::WaitForFence(VkFence fence) {
3811 auto fence_it = waitable_fences_.find(fence);
3812 if (fence_it != waitable_fences_.end()) {
3813 // The fence may no longer be waitable for several valid reasons.
3814 FenceSyncState &wait_for = fence_it->second;
3815 ApplyTaggedWait(wait_for.queue_id, wait_for.tag);
3816 waitable_fences_.erase(fence_it);
3817 }
3818}
3819
John Zulaufbbda4572022-04-19 16:20:45 -06003820const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3821 return GetMappedPlainFromShared(queue_sync_states_, queue);
3822}
3823
3824QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3825
3826std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3827 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3828}
3829
3830std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3831 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3832}
3833
John Zulaufe0757ba2022-06-10 16:51:45 -06003834template <typename T>
3835struct GetBatchTraits {};
3836template <>
3837struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3838 using Batch = std::shared_ptr<QueueBatchContext>;
3839 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3840};
3841
3842template <>
3843struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3844 using Batch = std::shared_ptr<QueueBatchContext>;
3845 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3846};
3847
3848template <typename BatchSet, typename Map, typename Predicate>
3849static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003850 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003851 for (auto &entry : map) {
3852 // Intentional copy
3853 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003854 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003855 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003856 return snapshot;
3857}
3858
3859template <typename Predicate>
3860QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003861 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003862}
3863
3864template <typename Predicate>
3865QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003866 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3867}
3868
3869QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3870 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3871 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3872 if (batch && !layer_data::Contains(snapshot, batch)) {
3873 snapshot.emplace(batch);
3874 }
3875 return false;
3876 };
3877 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3878 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003879}
3880
John Zulaufcb7e1672022-05-04 13:46:08 -06003881bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3882 const std::shared_ptr<QueueBatchContext> &batch,
3883 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003884 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003885 const SyncExecScope exec_scope =
3886 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3887 const VkSemaphore sem = sem_state->semaphore();
3888 auto signal_it = signaled_.find(sem);
3889 std::shared_ptr<Signal> insert_signal;
3890 if (signal_it == signaled_.end()) {
3891 if (prev_) {
3892 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3893 if (prev_sig) {
3894 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3895 insert_signal = std::make_shared<Signal>(*prev_sig);
3896 }
3897 }
3898 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3899 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003900 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003901
3902 bool success = false;
3903 if (!signal_it->second) {
3904 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3905 success = true;
3906 }
3907
3908 return success;
3909}
3910
John Zulaufecf4ac52022-06-06 10:08:42 -06003911std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3912 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003913 const auto found_it = signaled_.find(sem);
3914 if (found_it != signaled_.end()) {
3915 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3916 // a bit.
3917 unsignaled = std::move(found_it->second);
3918 if (!prev_) {
3919 // No parent, not need to keep the entry
3920 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3921 signaled_.erase(found_it);
3922 }
3923 } else if (prev_) {
3924 // We can't unsignal prev_ because it's const * by design.
3925 // We put in an empty placeholder
3926 signaled_.emplace(sem, std::shared_ptr<Signal>());
3927 unsignaled = GetPrev(sem);
3928 }
3929 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3930 // but CoreChecks should have reported it
3931
3932 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003933 return unsignaled;
3934}
3935
John Zulaufcb7e1672022-05-04 13:46:08 -06003936void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3937 // Overwrite the s tate with the last state from this
3938 if (from) {
3939 assert(sem == from->sem_state->semaphore());
3940 signaled_[sem] = std::move(from);
3941 } else {
3942 signaled_.erase(sem);
3943 }
3944}
3945
3946void SignaledSemaphores::Reset() {
3947 signaled_.clear();
3948 prev_ = nullptr;
3949}
3950
John Zulaufea943c52022-02-22 11:05:17 -07003951std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3952 // If we don't have one, make it.
3953 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3954 assert(cb_state.get());
3955 auto queue_flags = cb_state->GetQueueFlags();
3956 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3957}
3958
John Zulaufcb7e1672022-05-04 13:46:08 -06003959std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003960 return GetMappedInsert(cb_access_state, command_buffer,
3961 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3962}
3963
3964std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3965 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3966}
3967
3968const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3969 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3970}
3971
3972CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3973 return GetAccessContextShared(command_buffer).get();
3974}
3975
3976CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3977 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3978}
3979
John Zulaufd1f85d42020-04-15 12:23:15 -06003980void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003981 auto *access_context = GetAccessContextNoInsert(command_buffer);
3982 if (access_context) {
3983 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003984 }
3985}
3986
John Zulaufd1f85d42020-04-15 12:23:15 -06003987void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3988 auto access_found = cb_access_state.find(command_buffer);
3989 if (access_found != cb_access_state.end()) {
3990 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003991 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003992 cb_access_state.erase(access_found);
3993 }
3994}
3995
John Zulauf9cb530d2019-09-30 14:14:10 -06003996bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3997 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3998 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003999 const auto *cb_context = GetAccessContext(commandBuffer);
4000 assert(cb_context);
4001 if (!cb_context) return skip;
4002 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06004003
John Zulauf3d84f1b2020-03-09 13:33:25 -06004004 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004005 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4006 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004007
4008 for (uint32_t region = 0; region < regionCount; region++) {
4009 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004010 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004011 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004012 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004013 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004014 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004015 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004016 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004017 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06004018 }
John Zulauf9cb530d2019-09-30 14:14:10 -06004019 }
John Zulauf16adfc92020-04-08 10:28:33 -06004020 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004021 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004022 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004023 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004024 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004025 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004026 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004027 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06004028 }
4029 }
4030 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06004031 }
4032 return skip;
4033}
4034
4035void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4036 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004037 auto *cb_context = GetAccessContext(commandBuffer);
4038 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004039 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004040 auto *context = cb_context->GetCurrentAccessContext();
4041
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004042 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4043 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004044
4045 for (uint32_t region = 0; region < regionCount; region++) {
4046 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004047 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004048 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004049 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004050 }
John Zulauf16adfc92020-04-08 10:28:33 -06004051 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004052 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004053 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004054 }
4055 }
4056}
4057
John Zulauf4a6105a2020-11-17 15:11:05 -07004058void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4059 // Clear out events from the command buffer contexts
4060 for (auto &cb_context : cb_access_state) {
4061 cb_context.second->RecordDestroyEvent(event);
4062 }
4063}
4064
Tony-LunarGef035472021-11-02 10:23:33 -06004065bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4066 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004067 bool skip = false;
4068 const auto *cb_context = GetAccessContext(commandBuffer);
4069 assert(cb_context);
4070 if (!cb_context) return skip;
4071 const auto *context = cb_context->GetCurrentAccessContext();
4072
4073 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004074 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4075 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004076
4077 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4078 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4079 if (src_buffer) {
4080 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004081 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004082 if (hazard.hazard) {
4083 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004084 skip |=
4085 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4086 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4087 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4088 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004089 }
4090 }
4091 if (dst_buffer && !skip) {
4092 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004093 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004094 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004095 skip |=
4096 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4097 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4098 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4099 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004100 }
4101 }
4102 if (skip) break;
4103 }
4104 return skip;
4105}
4106
Tony-LunarGef035472021-11-02 10:23:33 -06004107bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4108 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4109 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4110}
4111
4112bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4113 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4114}
4115
4116void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004117 auto *cb_context = GetAccessContext(commandBuffer);
4118 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004119 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004120 auto *context = cb_context->GetCurrentAccessContext();
4121
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004122 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4123 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004124
4125 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4126 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4127 if (src_buffer) {
4128 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004129 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004130 }
4131 if (dst_buffer) {
4132 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004133 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004134 }
4135 }
4136}
4137
Tony-LunarGef035472021-11-02 10:23:33 -06004138void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4139 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4140}
4141
4142void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4143 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4144}
4145
John Zulauf5c5e88d2019-12-26 11:22:02 -07004146bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4147 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4148 const VkImageCopy *pRegions) const {
4149 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004150 const auto *cb_access_context = GetAccessContext(commandBuffer);
4151 assert(cb_access_context);
4152 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004153
John Zulauf3d84f1b2020-03-09 13:33:25 -06004154 const auto *context = cb_access_context->GetCurrentAccessContext();
4155 assert(context);
4156 if (!context) return skip;
4157
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004158 auto src_image = Get<IMAGE_STATE>(srcImage);
4159 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004160 for (uint32_t region = 0; region < regionCount; region++) {
4161 const auto &copy_region = pRegions[region];
4162 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004163 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004164 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004165 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004166 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004167 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004168 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004169 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004170 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004171 }
4172
4173 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004174 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004175 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004176 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004177 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004178 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004179 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004180 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004181 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004182 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004183 }
4184 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004185
John Zulauf5c5e88d2019-12-26 11:22:02 -07004186 return skip;
4187}
4188
4189void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4190 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4191 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004192 auto *cb_access_context = GetAccessContext(commandBuffer);
4193 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004194 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004195 auto *context = cb_access_context->GetCurrentAccessContext();
4196 assert(context);
4197
Jeremy Gebben9f537102021-10-05 16:37:12 -06004198 auto src_image = Get<IMAGE_STATE>(srcImage);
4199 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004200
4201 for (uint32_t region = 0; region < regionCount; region++) {
4202 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004203 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004204 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004205 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004206 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004207 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004208 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004209 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004210 }
4211 }
4212}
4213
Tony-LunarGb61514a2021-11-02 12:36:51 -06004214bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4215 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004216 bool skip = false;
4217 const auto *cb_access_context = GetAccessContext(commandBuffer);
4218 assert(cb_access_context);
4219 if (!cb_access_context) return skip;
4220
4221 const auto *context = cb_access_context->GetCurrentAccessContext();
4222 assert(context);
4223 if (!context) return skip;
4224
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004225 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4226 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004227
Jeff Leger178b1e52020-10-05 12:22:23 -04004228 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4229 const auto &copy_region = pCopyImageInfo->pRegions[region];
4230 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004231 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004232 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004233 if (hazard.hazard) {
4234 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004235 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004236 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004237 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004238 }
4239 }
4240
4241 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004242 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004243 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004244 if (hazard.hazard) {
4245 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004246 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004247 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004248 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004249 }
4250 if (skip) break;
4251 }
4252 }
4253
4254 return skip;
4255}
4256
Tony-LunarGb61514a2021-11-02 12:36:51 -06004257bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4258 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4259 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4260}
4261
4262bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4263 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4264}
4265
4266void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004267 auto *cb_access_context = GetAccessContext(commandBuffer);
4268 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004269 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004270 auto *context = cb_access_context->GetCurrentAccessContext();
4271 assert(context);
4272
Jeremy Gebben9f537102021-10-05 16:37:12 -06004273 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4274 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004275
4276 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4277 const auto &copy_region = pCopyImageInfo->pRegions[region];
4278 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004279 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004280 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004281 }
4282 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004283 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004284 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004285 }
4286 }
4287}
4288
Tony-LunarGb61514a2021-11-02 12:36:51 -06004289void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4290 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4291}
4292
4293void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4294 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4295}
4296
John Zulauf9cb530d2019-09-30 14:14:10 -06004297bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4298 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4299 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4300 uint32_t bufferMemoryBarrierCount,
4301 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4302 uint32_t imageMemoryBarrierCount,
4303 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4304 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004305 const auto *cb_access_context = GetAccessContext(commandBuffer);
4306 assert(cb_access_context);
4307 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004308
John Zulauf36ef9282021-02-02 11:47:24 -07004309 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4310 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4311 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4312 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004313 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004314 return skip;
4315}
4316
4317void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4318 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4319 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4320 uint32_t bufferMemoryBarrierCount,
4321 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4322 uint32_t imageMemoryBarrierCount,
4323 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004324 auto *cb_access_context = GetAccessContext(commandBuffer);
4325 assert(cb_access_context);
4326 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004327
John Zulauf1bf30522021-09-03 15:39:06 -06004328 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4329 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4330 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4331 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004332}
4333
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004334bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4335 const VkDependencyInfoKHR *pDependencyInfo) const {
4336 bool skip = false;
4337 const auto *cb_access_context = GetAccessContext(commandBuffer);
4338 assert(cb_access_context);
4339 if (!cb_access_context) return skip;
4340
4341 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4342 skip = pipeline_barrier.Validate(*cb_access_context);
4343 return skip;
4344}
4345
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004346bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4347 const VkDependencyInfo *pDependencyInfo) const {
4348 bool skip = false;
4349 const auto *cb_access_context = GetAccessContext(commandBuffer);
4350 assert(cb_access_context);
4351 if (!cb_access_context) return skip;
4352
4353 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4354 skip = pipeline_barrier.Validate(*cb_access_context);
4355 return skip;
4356}
4357
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004358void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4359 auto *cb_access_context = GetAccessContext(commandBuffer);
4360 assert(cb_access_context);
4361 if (!cb_access_context) return;
4362
John Zulauf1bf30522021-09-03 15:39:06 -06004363 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4364 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004365}
4366
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004367void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4368 auto *cb_access_context = GetAccessContext(commandBuffer);
4369 assert(cb_access_context);
4370 if (!cb_access_context) return;
4371
4372 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4373 *pDependencyInfo);
4374}
4375
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004376void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004377 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004378 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004379
John Zulauf5f13a792020-03-10 07:31:21 -06004380 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4381 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004382 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004383 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4384 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004385
John Zulauf1d5f9c12022-05-13 14:51:08 -06004386 QueueId queue_id = QueueSyncState::kQueueIdBase;
4387 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004388 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004389 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004390 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4391 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004392}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004393
John Zulauf355e49b2020-04-24 15:11:15 -06004394bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004395 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004396 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004397 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004398 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004399 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004400 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004401 }
John Zulauf355e49b2020-04-24 15:11:15 -06004402 return skip;
4403}
4404
4405bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4406 VkSubpassContents contents) const {
4407 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004408 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004409 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004410 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004411 return skip;
4412}
4413
4414bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004415 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004416 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004417 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004418 return skip;
4419}
4420
4421bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4422 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004423 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004424 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004425 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004426 return skip;
4427}
4428
John Zulauf3d84f1b2020-03-09 13:33:25 -06004429void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4430 VkResult result) {
4431 // The state tracker sets up the command buffer state
4432 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4433
4434 // Create/initialize the structure that trackers accesses at the command buffer scope.
4435 auto cb_access_context = GetAccessContext(commandBuffer);
4436 assert(cb_access_context);
4437 cb_access_context->Reset();
4438}
4439
4440void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004441 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004442 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004443 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004444 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004445 }
4446}
4447
4448void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4449 VkSubpassContents contents) {
4450 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004451 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004452 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004453 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004454}
4455
4456void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4457 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4458 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004459 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004460}
4461
4462void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4463 const VkRenderPassBeginInfo *pRenderPassBegin,
4464 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4465 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004466 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004467}
4468
Mike Schuchardt2df08912020-12-15 16:28:09 -08004469bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004470 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004471 bool skip = false;
4472
4473 auto cb_context = GetAccessContext(commandBuffer);
4474 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004475 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004476 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004477 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004478}
4479
4480bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4481 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004482 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004483 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004484 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004485 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4486 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004487 return skip;
4488}
4489
Mike Schuchardt2df08912020-12-15 16:28:09 -08004490bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4491 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004492 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004493 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004494 return skip;
4495}
4496
4497bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4498 const VkSubpassEndInfo *pSubpassEndInfo) const {
4499 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004500 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004501 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004502}
4503
4504void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004505 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004506 auto cb_context = GetAccessContext(commandBuffer);
4507 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004508 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004509
sjfricke0bea06e2022-06-05 09:22:26 +09004510 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004511}
4512
4513void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4514 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004515 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004516 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004517 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004518}
4519
4520void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4521 const VkSubpassEndInfo *pSubpassEndInfo) {
4522 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004523 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004524}
4525
4526void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4527 const VkSubpassEndInfo *pSubpassEndInfo) {
4528 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004529 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004530}
4531
sfricke-samsung85584a72021-09-30 21:43:38 -07004532bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004533 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004534 bool skip = false;
4535
4536 auto cb_context = GetAccessContext(commandBuffer);
4537 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004538 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004539
sjfricke0bea06e2022-06-05 09:22:26 +09004540 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004541 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004542 return skip;
4543}
4544
4545bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4546 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004547 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004548 return skip;
4549}
4550
Mike Schuchardt2df08912020-12-15 16:28:09 -08004551bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004552 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004553 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004554 return skip;
4555}
4556
4557bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004558 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004559 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004560 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004561 return skip;
4562}
4563
sjfricke0bea06e2022-06-05 09:22:26 +09004564void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4565 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004566 // Resolve the all subpass contexts to the command buffer contexts
4567 auto cb_context = GetAccessContext(commandBuffer);
4568 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004569 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004570
sjfricke0bea06e2022-06-05 09:22:26 +09004571 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004572}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004573
John Zulauf33fc1d52020-07-17 11:01:10 -06004574// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4575// updates to a resource which do not conflict at the byte level.
4576// TODO: Revisit this rule to see if it needs to be tighter or looser
4577// TODO: Add programatic control over suppression heuristics
4578bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4579 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4580}
4581
John Zulauf3d84f1b2020-03-09 13:33:25 -06004582void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004583 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004584 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004585}
4586
4587void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004588 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004589 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004590}
4591
4592void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004593 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004594 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004595}
locke-lunarga19c71d2020-03-02 18:17:04 -07004596
sfricke-samsung71f04e32022-03-16 01:21:21 -05004597template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004598bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004599 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4600 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004601 bool skip = false;
4602 const auto *cb_access_context = GetAccessContext(commandBuffer);
4603 assert(cb_access_context);
4604 if (!cb_access_context) return skip;
4605
4606 const auto *context = cb_access_context->GetCurrentAccessContext();
4607 assert(context);
4608 if (!context) return skip;
4609
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004610 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4611 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004612
4613 for (uint32_t region = 0; region < regionCount; region++) {
4614 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004615 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004616 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004617 if (src_buffer) {
4618 ResourceAccessRange src_range =
4619 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004620 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004621 if (hazard.hazard) {
4622 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004623 skip |=
4624 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4625 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4626 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4627 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004628 }
4629 }
4630
Jeremy Gebben40a22942020-12-22 14:22:06 -07004631 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004632 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004633 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004634 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004635 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004636 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004637 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004638 }
4639 if (skip) break;
4640 }
4641 if (skip) break;
4642 }
4643 return skip;
4644}
4645
Jeff Leger178b1e52020-10-05 12:22:23 -04004646bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4647 VkImageLayout dstImageLayout, uint32_t regionCount,
4648 const VkBufferImageCopy *pRegions) const {
4649 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004650 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004651}
4652
4653bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4654 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4655 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4656 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004657 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4658}
4659
4660bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4661 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4662 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4663 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4664 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004665}
4666
sfricke-samsung71f04e32022-03-16 01:21:21 -05004667template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004668void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004669 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4670 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004671 auto *cb_access_context = GetAccessContext(commandBuffer);
4672 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004673
Jeff Leger178b1e52020-10-05 12:22:23 -04004674 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004675 auto *context = cb_access_context->GetCurrentAccessContext();
4676 assert(context);
4677
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004678 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4679 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004680
4681 for (uint32_t region = 0; region < regionCount; region++) {
4682 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004683 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004684 if (src_buffer) {
4685 ResourceAccessRange src_range =
4686 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004687 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004688 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004689 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004690 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004691 }
4692 }
4693}
4694
Jeff Leger178b1e52020-10-05 12:22:23 -04004695void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4696 VkImageLayout dstImageLayout, uint32_t regionCount,
4697 const VkBufferImageCopy *pRegions) {
4698 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004699 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004700}
4701
4702void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4703 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4704 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4705 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4706 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004707 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4708}
4709
4710void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4711 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4712 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4713 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4714 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4715 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004716}
4717
sfricke-samsung71f04e32022-03-16 01:21:21 -05004718template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004719bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004720 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4721 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004722 bool skip = false;
4723 const auto *cb_access_context = GetAccessContext(commandBuffer);
4724 assert(cb_access_context);
4725 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004726
locke-lunarga19c71d2020-03-02 18:17:04 -07004727 const auto *context = cb_access_context->GetCurrentAccessContext();
4728 assert(context);
4729 if (!context) return skip;
4730
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004731 auto src_image = Get<IMAGE_STATE>(srcImage);
4732 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004733 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004734 for (uint32_t region = 0; region < regionCount; region++) {
4735 const auto &copy_region = pRegions[region];
4736 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004737 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004738 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004739 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004740 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004741 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004742 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004743 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004744 }
John Zulauf477700e2021-01-06 11:41:49 -07004745 if (dst_mem) {
4746 ResourceAccessRange dst_range =
4747 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004748 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004749 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004750 skip |=
4751 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4752 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4753 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4754 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004755 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004756 }
4757 }
4758 if (skip) break;
4759 }
4760 return skip;
4761}
4762
Jeff Leger178b1e52020-10-05 12:22:23 -04004763bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4764 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4765 const VkBufferImageCopy *pRegions) const {
4766 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004767 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004768}
4769
4770bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4771 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4772 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4773 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004774 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4775}
4776
4777bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4778 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4779 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4780 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4781 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004782}
4783
sfricke-samsung71f04e32022-03-16 01:21:21 -05004784template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004785void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004786 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004787 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004788 auto *cb_access_context = GetAccessContext(commandBuffer);
4789 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004790
Jeff Leger178b1e52020-10-05 12:22:23 -04004791 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004792 auto *context = cb_access_context->GetCurrentAccessContext();
4793 assert(context);
4794
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004795 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004796 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004797 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004798 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004799
4800 for (uint32_t region = 0; region < regionCount; region++) {
4801 const auto &copy_region = pRegions[region];
4802 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004803 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004804 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004805 if (dst_buffer) {
4806 ResourceAccessRange dst_range =
4807 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004808 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004809 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004810 }
4811 }
4812}
4813
Jeff Leger178b1e52020-10-05 12:22:23 -04004814void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4815 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4816 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004817 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004818}
4819
4820void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4821 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4822 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4823 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4824 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004825 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4826}
4827
4828void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4829 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4830 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4831 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4832 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4833 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004834}
4835
4836template <typename RegionType>
4837bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4838 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004839 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004840 bool skip = false;
4841 const auto *cb_access_context = GetAccessContext(commandBuffer);
4842 assert(cb_access_context);
4843 if (!cb_access_context) return skip;
4844
4845 const auto *context = cb_access_context->GetCurrentAccessContext();
4846 assert(context);
4847 if (!context) return skip;
4848
sjfricke0bea06e2022-06-05 09:22:26 +09004849 const char *caller_name = CommandTypeString(cmd_type);
4850
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004851 auto src_image = Get<IMAGE_STATE>(srcImage);
4852 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004853
4854 for (uint32_t region = 0; region < regionCount; region++) {
4855 const auto &blit_region = pRegions[region];
4856 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004857 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4858 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4859 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4860 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4861 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4862 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004863 auto hazard =
4864 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004865 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004866 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004867 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004868 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004869 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004870 }
4871 }
4872
4873 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004874 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4875 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4876 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4877 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4878 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4879 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004880 auto hazard =
4881 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004882 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004883 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004884 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004885 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004886 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004887 }
4888 if (skip) break;
4889 }
4890 }
4891
4892 return skip;
4893}
4894
Jeff Leger178b1e52020-10-05 12:22:23 -04004895bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4896 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4897 const VkImageBlit *pRegions, VkFilter filter) const {
4898 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004899 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004900}
4901
4902bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4903 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4904 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4905 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004906 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004907}
4908
Tony-LunarG542ae912021-11-04 16:06:44 -06004909bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4910 const VkBlitImageInfo2 *pBlitImageInfo) const {
4911 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004912 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4913 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004914}
4915
Jeff Leger178b1e52020-10-05 12:22:23 -04004916template <typename RegionType>
4917void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4918 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4919 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004920 auto *cb_access_context = GetAccessContext(commandBuffer);
4921 assert(cb_access_context);
4922 auto *context = cb_access_context->GetCurrentAccessContext();
4923 assert(context);
4924
Jeremy Gebben9f537102021-10-05 16:37:12 -06004925 auto src_image = Get<IMAGE_STATE>(srcImage);
4926 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004927
4928 for (uint32_t region = 0; region < regionCount; region++) {
4929 const auto &blit_region = pRegions[region];
4930 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004931 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4932 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4933 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4934 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4935 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4936 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004937 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004938 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004939 }
4940 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004941 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4942 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4943 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4944 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4945 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4946 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004947 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004948 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004949 }
4950 }
4951}
locke-lunarg36ba2592020-04-03 09:42:04 -06004952
Jeff Leger178b1e52020-10-05 12:22:23 -04004953void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4954 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4955 const VkImageBlit *pRegions, VkFilter filter) {
4956 auto *cb_access_context = GetAccessContext(commandBuffer);
4957 assert(cb_access_context);
4958 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4959 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4960 pRegions, filter);
4961 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4962}
4963
4964void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4965 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4966 auto *cb_access_context = GetAccessContext(commandBuffer);
4967 assert(cb_access_context);
4968 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4969 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4970 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4971 pBlitImageInfo->filter, tag);
4972}
4973
Tony-LunarG542ae912021-11-04 16:06:44 -06004974void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4975 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4976 auto *cb_access_context = GetAccessContext(commandBuffer);
4977 assert(cb_access_context);
4978 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4979 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4980 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4981 pBlitImageInfo->filter, tag);
4982}
4983
John Zulauffaea0ee2021-01-14 14:01:32 -07004984bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4985 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4986 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004987 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004988 bool skip = false;
4989 if (drawCount == 0) return skip;
4990
sjfricke0bea06e2022-06-05 09:22:26 +09004991 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004992 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004993 VkDeviceSize size = struct_size;
4994 if (drawCount == 1 || stride == size) {
4995 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004996 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004997 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4998 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004999 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005000 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06005001 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005002 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005003 }
5004 } else {
5005 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005006 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06005007 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5008 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005009 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005010 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
5011 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5012 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005013 break;
5014 }
5015 }
5016 }
5017 return skip;
5018}
5019
John Zulauf14940722021-04-12 15:19:02 -06005020void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06005021 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
5022 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005023 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005024 VkDeviceSize size = struct_size;
5025 if (drawCount == 1 || stride == size) {
5026 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005027 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005028 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005029 } else {
5030 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005031 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005032 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
5033 tag);
locke-lunargff255f92020-05-13 18:53:52 -06005034 }
5035 }
5036}
5037
John Zulauffaea0ee2021-01-14 14:01:32 -07005038bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5039 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005040 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005041 bool skip = false;
5042
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005043 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005044 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005045 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5046 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005047 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005048 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5049 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5050 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005051 }
5052 return skip;
5053}
5054
John Zulauf14940722021-04-12 15:19:02 -06005055void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005056 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005057 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005058 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005059}
5060
locke-lunarg36ba2592020-04-03 09:42:04 -06005061bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005062 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005063 const auto *cb_access_context = GetAccessContext(commandBuffer);
5064 assert(cb_access_context);
5065 if (!cb_access_context) return skip;
5066
sjfricke0bea06e2022-06-05 09:22:26 +09005067 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005068 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005069}
5070
5071void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005072 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005073 auto *cb_access_context = GetAccessContext(commandBuffer);
5074 assert(cb_access_context);
5075 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005076
locke-lunarg61870c22020-06-09 14:51:50 -06005077 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005078}
locke-lunarge1a67022020-04-29 00:15:36 -06005079
5080bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005081 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005082 const auto *cb_access_context = GetAccessContext(commandBuffer);
5083 assert(cb_access_context);
5084 if (!cb_access_context) return skip;
5085
5086 const auto *context = cb_access_context->GetCurrentAccessContext();
5087 assert(context);
5088 if (!context) return skip;
5089
sjfricke0bea06e2022-06-05 09:22:26 +09005090 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005091 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005092 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005093 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005094}
5095
5096void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005097 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005098 auto *cb_access_context = GetAccessContext(commandBuffer);
5099 assert(cb_access_context);
5100 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5101 auto *context = cb_access_context->GetCurrentAccessContext();
5102 assert(context);
5103
locke-lunarg61870c22020-06-09 14:51:50 -06005104 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5105 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005106}
5107
5108bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5109 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005110 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005111 const auto *cb_access_context = GetAccessContext(commandBuffer);
5112 assert(cb_access_context);
5113 if (!cb_access_context) return skip;
5114
sjfricke0bea06e2022-06-05 09:22:26 +09005115 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5116 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5117 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005118 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005119}
5120
5121void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5122 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005123 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005124 auto *cb_access_context = GetAccessContext(commandBuffer);
5125 assert(cb_access_context);
5126 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005127
locke-lunarg61870c22020-06-09 14:51:50 -06005128 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5129 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5130 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005131}
5132
5133bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5134 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005135 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005136 const auto *cb_access_context = GetAccessContext(commandBuffer);
5137 assert(cb_access_context);
5138 if (!cb_access_context) return skip;
5139
sjfricke0bea06e2022-06-05 09:22:26 +09005140 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5141 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5142 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005143 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005144}
5145
5146void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5147 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005148 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005149 auto *cb_access_context = GetAccessContext(commandBuffer);
5150 assert(cb_access_context);
5151 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005152
locke-lunarg61870c22020-06-09 14:51:50 -06005153 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5154 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5155 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005156}
5157
5158bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5159 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005160 bool skip = false;
5161 if (drawCount == 0) return skip;
5162
locke-lunargff255f92020-05-13 18:53:52 -06005163 const auto *cb_access_context = GetAccessContext(commandBuffer);
5164 assert(cb_access_context);
5165 if (!cb_access_context) return skip;
5166
5167 const auto *context = cb_access_context->GetCurrentAccessContext();
5168 assert(context);
5169 if (!context) return skip;
5170
sjfricke0bea06e2022-06-05 09:22:26 +09005171 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5172 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005173 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005174 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005175
5176 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5177 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5178 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005179 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005180 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005181}
5182
5183void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5184 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005185 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005186 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005187 auto *cb_access_context = GetAccessContext(commandBuffer);
5188 assert(cb_access_context);
5189 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5190 auto *context = cb_access_context->GetCurrentAccessContext();
5191 assert(context);
5192
locke-lunarg61870c22020-06-09 14:51:50 -06005193 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5194 cb_access_context->RecordDrawSubpassAttachment(tag);
5195 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005196
5197 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5198 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5199 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005200 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005201}
5202
5203bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5204 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005205 bool skip = false;
5206 if (drawCount == 0) return skip;
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_DRAWINDEXEDINDIRECT);
5216 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005217 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005218 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005219
5220 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5221 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5222 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005223 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005224 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005225}
5226
5227void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5228 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005229 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005230 auto *cb_access_context = GetAccessContext(commandBuffer);
5231 assert(cb_access_context);
5232 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5233 auto *context = cb_access_context->GetCurrentAccessContext();
5234 assert(context);
5235
locke-lunarg61870c22020-06-09 14:51:50 -06005236 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5237 cb_access_context->RecordDrawSubpassAttachment(tag);
5238 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005239
5240 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5241 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5242 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005243 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005244}
5245
5246bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5247 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005248 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005249 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005250 const auto *cb_access_context = GetAccessContext(commandBuffer);
5251 assert(cb_access_context);
5252 if (!cb_access_context) return skip;
5253
5254 const auto *context = cb_access_context->GetCurrentAccessContext();
5255 assert(context);
5256 if (!context) return skip;
5257
sjfricke0bea06e2022-06-05 09:22:26 +09005258 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5259 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005260 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005261 maxDrawCount, stride, cmd_type);
5262 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005263
5264 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5265 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5266 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005267 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005268 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005269}
5270
5271bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5272 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5273 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005274 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005275 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005276}
5277
sfricke-samsung85584a72021-09-30 21:43:38 -07005278void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5279 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5280 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005281 auto *cb_access_context = GetAccessContext(commandBuffer);
5282 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005283 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005284 auto *context = cb_access_context->GetCurrentAccessContext();
5285 assert(context);
5286
locke-lunarg61870c22020-06-09 14:51:50 -06005287 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5288 cb_access_context->RecordDrawSubpassAttachment(tag);
5289 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5290 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005291
5292 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5293 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5294 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005295 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005296}
5297
sfricke-samsung85584a72021-09-30 21:43:38 -07005298void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5299 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5300 uint32_t stride) {
5301 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5302 stride);
5303 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5304 CMD_DRAWINDIRECTCOUNT);
5305}
locke-lunarge1a67022020-04-29 00:15:36 -06005306bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5307 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5308 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005309 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005310 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005311}
5312
5313void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5314 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5315 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005316 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5317 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005318 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5319 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005320}
5321
5322bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5323 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5324 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005325 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005326 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005327}
5328
5329void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5330 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5331 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005332 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5333 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005334 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5335 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005336}
5337
5338bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5339 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005340 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005341 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005342 const auto *cb_access_context = GetAccessContext(commandBuffer);
5343 assert(cb_access_context);
5344 if (!cb_access_context) return skip;
5345
5346 const auto *context = cb_access_context->GetCurrentAccessContext();
5347 assert(context);
5348 if (!context) return skip;
5349
sjfricke0bea06e2022-06-05 09:22:26 +09005350 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5351 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005352 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005353 offset, maxDrawCount, stride, cmd_type);
5354 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005355
5356 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5357 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5358 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005359 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005360 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005361}
5362
5363bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5364 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5365 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005366 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005367 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005368}
5369
sfricke-samsung85584a72021-09-30 21:43:38 -07005370void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5371 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5372 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005373 auto *cb_access_context = GetAccessContext(commandBuffer);
5374 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005375 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005376 auto *context = cb_access_context->GetCurrentAccessContext();
5377 assert(context);
5378
locke-lunarg61870c22020-06-09 14:51:50 -06005379 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5380 cb_access_context->RecordDrawSubpassAttachment(tag);
5381 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5382 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005383
5384 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5385 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005386 // We will update the index and vertex buffer in SubmitQueue in the future.
5387 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005388}
5389
sfricke-samsung85584a72021-09-30 21:43:38 -07005390void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5391 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5392 uint32_t maxDrawCount, uint32_t stride) {
5393 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5394 maxDrawCount, stride);
5395 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5396 CMD_DRAWINDEXEDINDIRECTCOUNT);
5397}
5398
locke-lunarge1a67022020-04-29 00:15:36 -06005399bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5400 VkDeviceSize offset, VkBuffer countBuffer,
5401 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5402 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005403 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005404 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005405}
5406
5407void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5408 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5409 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005410 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5411 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005412 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5413 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005414}
5415
5416bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5417 VkDeviceSize offset, VkBuffer countBuffer,
5418 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5419 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005420 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005421 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005422}
5423
5424void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5425 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5426 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005427 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5428 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005429 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5430 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005431}
5432
5433bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5434 const VkClearColorValue *pColor, uint32_t rangeCount,
5435 const VkImageSubresourceRange *pRanges) const {
5436 bool skip = false;
5437 const auto *cb_access_context = GetAccessContext(commandBuffer);
5438 assert(cb_access_context);
5439 if (!cb_access_context) return skip;
5440
5441 const auto *context = cb_access_context->GetCurrentAccessContext();
5442 assert(context);
5443 if (!context) return skip;
5444
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005445 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005446
5447 for (uint32_t index = 0; index < rangeCount; index++) {
5448 const auto &range = pRanges[index];
5449 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005450 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005451 if (hazard.hazard) {
5452 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005453 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005454 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005455 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005456 }
5457 }
5458 }
5459 return skip;
5460}
5461
5462void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5463 const VkClearColorValue *pColor, uint32_t rangeCount,
5464 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005465 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005466 auto *cb_access_context = GetAccessContext(commandBuffer);
5467 assert(cb_access_context);
5468 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5469 auto *context = cb_access_context->GetCurrentAccessContext();
5470 assert(context);
5471
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005472 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005473
5474 for (uint32_t index = 0; index < rangeCount; index++) {
5475 const auto &range = pRanges[index];
5476 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005477 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005478 }
5479 }
5480}
5481
5482bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5483 VkImageLayout imageLayout,
5484 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5485 const VkImageSubresourceRange *pRanges) const {
5486 bool skip = false;
5487 const auto *cb_access_context = GetAccessContext(commandBuffer);
5488 assert(cb_access_context);
5489 if (!cb_access_context) return skip;
5490
5491 const auto *context = cb_access_context->GetCurrentAccessContext();
5492 assert(context);
5493 if (!context) return skip;
5494
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005495 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005496
5497 for (uint32_t index = 0; index < rangeCount; index++) {
5498 const auto &range = pRanges[index];
5499 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005500 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005501 if (hazard.hazard) {
5502 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005503 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005504 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005505 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005506 }
5507 }
5508 }
5509 return skip;
5510}
5511
5512void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5513 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5514 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005515 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005516 auto *cb_access_context = GetAccessContext(commandBuffer);
5517 assert(cb_access_context);
5518 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5519 auto *context = cb_access_context->GetCurrentAccessContext();
5520 assert(context);
5521
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005522 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005523
5524 for (uint32_t index = 0; index < rangeCount; index++) {
5525 const auto &range = pRanges[index];
5526 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005527 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005528 }
5529 }
5530}
5531
5532bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5533 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5534 VkDeviceSize dstOffset, VkDeviceSize stride,
5535 VkQueryResultFlags flags) const {
5536 bool skip = false;
5537 const auto *cb_access_context = GetAccessContext(commandBuffer);
5538 assert(cb_access_context);
5539 if (!cb_access_context) return skip;
5540
5541 const auto *context = cb_access_context->GetCurrentAccessContext();
5542 assert(context);
5543 if (!context) return skip;
5544
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005545 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005546
5547 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005548 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005549 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005550 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005551 skip |=
5552 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5553 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005554 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005555 }
5556 }
locke-lunargff255f92020-05-13 18:53:52 -06005557
5558 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005559 return skip;
5560}
5561
5562void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5563 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5564 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005565 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5566 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005567 auto *cb_access_context = GetAccessContext(commandBuffer);
5568 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005569 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005570 auto *context = cb_access_context->GetCurrentAccessContext();
5571 assert(context);
5572
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005573 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005574
5575 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005576 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005577 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005578 }
locke-lunargff255f92020-05-13 18:53:52 -06005579
5580 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005581}
5582
5583bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5584 VkDeviceSize size, uint32_t data) const {
5585 bool skip = false;
5586 const auto *cb_access_context = GetAccessContext(commandBuffer);
5587 assert(cb_access_context);
5588 if (!cb_access_context) return skip;
5589
5590 const auto *context = cb_access_context->GetCurrentAccessContext();
5591 assert(context);
5592 if (!context) return skip;
5593
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005594 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005595
5596 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005597 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005598 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005599 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005600 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005601 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005602 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005603 }
5604 }
5605 return skip;
5606}
5607
5608void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5609 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005610 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005611 auto *cb_access_context = GetAccessContext(commandBuffer);
5612 assert(cb_access_context);
5613 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5614 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(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005621 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005622 }
5623}
5624
5625bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5626 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5627 const VkImageResolve *pRegions) const {
5628 bool skip = false;
5629 const auto *cb_access_context = GetAccessContext(commandBuffer);
5630 assert(cb_access_context);
5631 if (!cb_access_context) return skip;
5632
5633 const auto *context = cb_access_context->GetCurrentAccessContext();
5634 assert(context);
5635 if (!context) return skip;
5636
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005637 auto src_image = Get<IMAGE_STATE>(srcImage);
5638 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005639
5640 for (uint32_t region = 0; region < regionCount; region++) {
5641 const auto &resolve_region = pRegions[region];
5642 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005643 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005644 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005645 if (hazard.hazard) {
5646 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005647 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005648 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005649 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005650 }
5651 }
5652
5653 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005654 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005655 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005656 if (hazard.hazard) {
5657 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005658 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005659 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005660 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005661 }
5662 if (skip) break;
5663 }
5664 }
5665
5666 return skip;
5667}
5668
5669void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5670 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5671 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005672 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5673 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005674 auto *cb_access_context = GetAccessContext(commandBuffer);
5675 assert(cb_access_context);
5676 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5677 auto *context = cb_access_context->GetCurrentAccessContext();
5678 assert(context);
5679
Jeremy Gebben9f537102021-10-05 16:37:12 -06005680 auto src_image = Get<IMAGE_STATE>(srcImage);
5681 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005682
5683 for (uint32_t region = 0; region < regionCount; region++) {
5684 const auto &resolve_region = pRegions[region];
5685 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005686 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005687 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005688 }
5689 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005690 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005691 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005692 }
5693 }
5694}
5695
Tony-LunarG562fc102021-11-12 13:58:35 -07005696bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5697 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005698 bool skip = false;
5699 const auto *cb_access_context = GetAccessContext(commandBuffer);
5700 assert(cb_access_context);
5701 if (!cb_access_context) return skip;
5702
5703 const auto *context = cb_access_context->GetCurrentAccessContext();
5704 assert(context);
5705 if (!context) return skip;
5706
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005707 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5708 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005709
5710 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5711 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5712 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005713 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005714 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005715 if (hazard.hazard) {
5716 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005717 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005718 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005719 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005720 }
5721 }
5722
5723 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005724 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005725 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005726 if (hazard.hazard) {
5727 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005728 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005729 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005730 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005731 }
5732 if (skip) break;
5733 }
5734 }
5735
5736 return skip;
5737}
5738
Tony-LunarG562fc102021-11-12 13:58:35 -07005739bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5740 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5741 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5742}
5743
5744bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5745 const VkResolveImageInfo2 *pResolveImageInfo) const {
5746 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5747}
5748
5749void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5750 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005751 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5752 auto *cb_access_context = GetAccessContext(commandBuffer);
5753 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005754 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005755 auto *context = cb_access_context->GetCurrentAccessContext();
5756 assert(context);
5757
Jeremy Gebben9f537102021-10-05 16:37:12 -06005758 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5759 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005760
5761 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5762 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5763 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005764 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005765 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005766 }
5767 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005768 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005769 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005770 }
5771 }
5772}
5773
Tony-LunarG562fc102021-11-12 13:58:35 -07005774void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5775 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5776 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5777}
5778
5779void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5780 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5781}
5782
locke-lunarge1a67022020-04-29 00:15:36 -06005783bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5784 VkDeviceSize dataSize, const void *pData) const {
5785 bool skip = false;
5786 const auto *cb_access_context = GetAccessContext(commandBuffer);
5787 assert(cb_access_context);
5788 if (!cb_access_context) return skip;
5789
5790 const auto *context = cb_access_context->GetCurrentAccessContext();
5791 assert(context);
5792 if (!context) return skip;
5793
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005794 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005795
5796 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005797 // VK_WHOLE_SIZE not allowed
5798 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005799 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005800 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005801 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005802 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005803 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005804 }
5805 }
5806 return skip;
5807}
5808
5809void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5810 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005811 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005812 auto *cb_access_context = GetAccessContext(commandBuffer);
5813 assert(cb_access_context);
5814 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5815 auto *context = cb_access_context->GetCurrentAccessContext();
5816 assert(context);
5817
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005818 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005819
5820 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005821 // VK_WHOLE_SIZE not allowed
5822 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005823 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005824 }
5825}
locke-lunargff255f92020-05-13 18:53:52 -06005826
5827bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5828 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) 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-lunargff255f92020-05-13 18:53:52 -06005839
5840 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005841 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005842 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005843 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005844 skip |=
5845 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5846 "vkCmdWriteBufferMarkerAMD: 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-lunargff255f92020-05-13 18:53:52 -06005848 }
5849 }
5850 return skip;
5851}
5852
5853void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5854 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005855 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005856 auto *cb_access_context = GetAccessContext(commandBuffer);
5857 assert(cb_access_context);
5858 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
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-lunargff255f92020-05-13 18:53:52 -06005863
5864 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005865 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005866 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005867 }
5868}
John Zulauf49beb112020-11-04 16:06:31 -07005869
5870bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5871 bool skip = false;
5872 const auto *cb_context = GetAccessContext(commandBuffer);
5873 assert(cb_context);
5874 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005875 const auto *access_context = cb_context->GetCurrentAccessContext();
5876 assert(access_context);
5877 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005878
John Zulaufe0757ba2022-06-10 16:51:45 -06005879 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005880 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005881}
5882
5883void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5884 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5885 auto *cb_context = GetAccessContext(commandBuffer);
5886 assert(cb_context);
5887 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005888
5889 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5890 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005891}
5892
John Zulauf4edde622021-02-15 08:54:50 -07005893bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5894 const VkDependencyInfoKHR *pDependencyInfo) const {
5895 bool skip = false;
5896 const auto *cb_context = GetAccessContext(commandBuffer);
5897 assert(cb_context);
5898 if (!cb_context || !pDependencyInfo) return skip;
5899
John Zulaufe0757ba2022-06-10 16:51:45 -06005900 const auto *access_context = cb_context->GetCurrentAccessContext();
5901 assert(access_context);
5902 if (!access_context) return skip;
5903
5904 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005905 return set_event_op.Validate(*cb_context);
5906}
5907
Tony-LunarGc43525f2021-11-15 16:12:38 -07005908bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5909 const VkDependencyInfo *pDependencyInfo) const {
5910 bool skip = false;
5911 const auto *cb_context = GetAccessContext(commandBuffer);
5912 assert(cb_context);
5913 if (!cb_context || !pDependencyInfo) return skip;
5914
John Zulaufe0757ba2022-06-10 16:51:45 -06005915 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005916 return set_event_op.Validate(*cb_context);
5917}
5918
John Zulauf4edde622021-02-15 08:54:50 -07005919void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5920 const VkDependencyInfoKHR *pDependencyInfo) {
5921 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5922 auto *cb_context = GetAccessContext(commandBuffer);
5923 assert(cb_context);
5924 if (!cb_context || !pDependencyInfo) return;
5925
John Zulaufe0757ba2022-06-10 16:51:45 -06005926 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5927 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005928}
5929
Tony-LunarGc43525f2021-11-15 16:12:38 -07005930void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5931 const VkDependencyInfo *pDependencyInfo) {
5932 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5933 auto *cb_context = GetAccessContext(commandBuffer);
5934 assert(cb_context);
5935 if (!cb_context || !pDependencyInfo) return;
5936
John Zulaufe0757ba2022-06-10 16:51:45 -06005937 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5938 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005939}
5940
John Zulauf49beb112020-11-04 16:06:31 -07005941bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5942 VkPipelineStageFlags stageMask) const {
5943 bool skip = false;
5944 const auto *cb_context = GetAccessContext(commandBuffer);
5945 assert(cb_context);
5946 if (!cb_context) return skip;
5947
John Zulauf36ef9282021-02-02 11:47:24 -07005948 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005949 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005950}
5951
5952void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5953 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5954 auto *cb_context = GetAccessContext(commandBuffer);
5955 assert(cb_context);
5956 if (!cb_context) return;
5957
John Zulauf1bf30522021-09-03 15:39:06 -06005958 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005959}
5960
John Zulauf4edde622021-02-15 08:54:50 -07005961bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5962 VkPipelineStageFlags2KHR stageMask) const {
5963 bool skip = false;
5964 const auto *cb_context = GetAccessContext(commandBuffer);
5965 assert(cb_context);
5966 if (!cb_context) return skip;
5967
5968 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5969 return reset_event_op.Validate(*cb_context);
5970}
5971
Tony-LunarGa2662db2021-11-16 07:26:24 -07005972bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5973 VkPipelineStageFlags2 stageMask) const {
5974 bool skip = false;
5975 const auto *cb_context = GetAccessContext(commandBuffer);
5976 assert(cb_context);
5977 if (!cb_context) return skip;
5978
5979 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5980 return reset_event_op.Validate(*cb_context);
5981}
5982
John Zulauf4edde622021-02-15 08:54:50 -07005983void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5984 VkPipelineStageFlags2KHR stageMask) {
5985 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5986 auto *cb_context = GetAccessContext(commandBuffer);
5987 assert(cb_context);
5988 if (!cb_context) return;
5989
John Zulauf1bf30522021-09-03 15:39:06 -06005990 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005991}
5992
Tony-LunarGa2662db2021-11-16 07:26:24 -07005993void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5994 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5995 auto *cb_context = GetAccessContext(commandBuffer);
5996 assert(cb_context);
5997 if (!cb_context) return;
5998
5999 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
6000}
6001
John Zulauf49beb112020-11-04 16:06:31 -07006002bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6003 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6004 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6005 uint32_t bufferMemoryBarrierCount,
6006 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6007 uint32_t imageMemoryBarrierCount,
6008 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
6009 bool skip = false;
6010 const auto *cb_context = GetAccessContext(commandBuffer);
6011 assert(cb_context);
6012 if (!cb_context) return skip;
6013
John Zulauf36ef9282021-02-02 11:47:24 -07006014 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
6015 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
6016 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07006017 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07006018}
6019
6020void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6021 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6022 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6023 uint32_t bufferMemoryBarrierCount,
6024 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6025 uint32_t imageMemoryBarrierCount,
6026 const VkImageMemoryBarrier *pImageMemoryBarriers) {
6027 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
6028 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
6029 imageMemoryBarrierCount, pImageMemoryBarriers);
6030
6031 auto *cb_context = GetAccessContext(commandBuffer);
6032 assert(cb_context);
6033 if (!cb_context) return;
6034
John Zulauf1bf30522021-09-03 15:39:06 -06006035 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06006036 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06006037 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07006038}
6039
John Zulauf4edde622021-02-15 08:54:50 -07006040bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6041 const VkDependencyInfoKHR *pDependencyInfos) const {
6042 bool skip = false;
6043 const auto *cb_context = GetAccessContext(commandBuffer);
6044 assert(cb_context);
6045 if (!cb_context) return skip;
6046
6047 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6048 skip |= wait_events_op.Validate(*cb_context);
6049 return skip;
6050}
6051
6052void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6053 const VkDependencyInfoKHR *pDependencyInfos) {
6054 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6055
6056 auto *cb_context = GetAccessContext(commandBuffer);
6057 assert(cb_context);
6058 if (!cb_context) return;
6059
John Zulauf1bf30522021-09-03 15:39:06 -06006060 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6061 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006062}
6063
Tony-LunarG1364cf52021-11-17 16:10:11 -07006064bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6065 const VkDependencyInfo *pDependencyInfos) const {
6066 bool skip = false;
6067 const auto *cb_context = GetAccessContext(commandBuffer);
6068 assert(cb_context);
6069 if (!cb_context) return skip;
6070
6071 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6072 skip |= wait_events_op.Validate(*cb_context);
6073 return skip;
6074}
6075
6076void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6077 const VkDependencyInfo *pDependencyInfos) {
6078 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6079
6080 auto *cb_context = GetAccessContext(commandBuffer);
6081 assert(cb_context);
6082 if (!cb_context) return;
6083
6084 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6085 pDependencyInfos);
6086}
6087
John Zulauf4a6105a2020-11-17 15:11:05 -07006088void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006089 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006090 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006091 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006092}
6093
6094// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006095SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006096 IgnoreReason reason = NotIgnored;
6097
sjfricke0bea06e2022-06-05 09:22:26 +09006098 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006099 reason = SetVsWait2;
6100 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6101 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006102 } else if (unsynchronized_set) {
6103 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006104 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006105 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006106 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006107 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006108 } else {
6109 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006110 }
6111
6112 return reason;
6113}
6114
Jeremy Gebben40a22942020-12-22 14:22:06 -07006115bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006116 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6117 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6118 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006119}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006120
sjfricke0bea06e2022-06-05 09:22:26 +09006121SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006122 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6123 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006124 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6125 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6126 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006127 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006128 auto &barrier_set = barriers_[0];
6129 barrier_set.dependency_flags = dependencyFlags;
6130 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6131 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006132 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006133 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6134 pMemoryBarriers);
6135 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6136 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6137 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6138 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006139}
6140
sjfricke0bea06e2022-06-05 09:22:26 +09006141SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006142 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006143 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006144 for (uint32_t i = 0; i < event_count; i++) {
6145 const auto &dep_info = dep_infos[i];
6146 auto &barrier_set = barriers_[i];
6147 barrier_set.dependency_flags = dep_info.dependencyFlags;
6148 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6149 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6150 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6151 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6152 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6153 dep_info.pMemoryBarriers);
6154 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6155 dep_info.pBufferMemoryBarriers);
6156 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6157 dep_info.pImageMemoryBarriers);
6158 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006159}
6160
sjfricke0bea06e2022-06-05 09:22:26 +09006161SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006162 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6163 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6164 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6165 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6166 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006167 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6168 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6169 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006170
sjfricke0bea06e2022-06-05 09:22:26 +09006171SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006172 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006173 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006174
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006175bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6176 bool skip = false;
6177 const auto *context = cb_context.GetCurrentAccessContext();
6178 assert(context);
6179 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006180 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6181
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006182 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006183 const auto &barrier_set = barriers_[0];
6184 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6185 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6186 const auto *image_state = image_barrier.image.get();
6187 if (!image_state) continue;
6188 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6189 if (hazard.hazard) {
6190 // PHASE1 TODO -- add tag information to log msg when useful.
6191 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006192 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006193 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6194 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6195 string_SyncHazard(hazard.hazard), image_barrier.index,
6196 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006197 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006198 }
6199 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006200 return skip;
6201}
6202
John Zulaufd5115702021-01-18 12:34:33 -07006203struct SyncOpPipelineBarrierFunctorFactory {
6204 using BarrierOpFunctor = PipelineBarrierOp;
6205 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6206 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6207 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6208 using BufferRange = ResourceAccessRange;
6209 using ImageRange = subresource_adapter::ImageRangeGenerator;
6210 using GlobalRange = ResourceAccessRange;
6211
John Zulauf00119522022-05-23 19:07:42 -06006212 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6213 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006214 }
John Zulauf14940722021-04-12 15:19:02 -06006215 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006216 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6217 }
John Zulauf00119522022-05-23 19:07:42 -06006218 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6219 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006220 }
6221
6222 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6223 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6224 const auto base_address = ResourceBaseAddress(buffer);
6225 return (range + base_address);
6226 }
John Zulauf110413c2021-03-20 05:38:38 -06006227 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006228 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006229
6230 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006231 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006232 return range_gen;
6233 }
6234 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6235};
6236
6237template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006238void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6239 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006240 for (const auto &barrier : barriers) {
6241 const auto *state = barrier.GetState();
6242 if (state) {
6243 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006244 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006245 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6246 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6247 }
6248 }
6249}
6250
6251template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006252void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6253 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006254 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6255 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006256 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006257 }
6258 for (const auto address_type : kAddressTypes) {
6259 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6260 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6261 }
6262}
6263
John Zulaufdab327f2022-07-08 12:02:05 -06006264ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006265 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006266 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006267 return tag;
6268}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006269
John Zulauf0223f142022-07-06 09:05:39 -06006270void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006271 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006272 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6273 assert(barriers_.size() == 1);
6274 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006275 if (!exec_context.ValidForSyncOps()) return;
6276
6277 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6278 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6279 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006280 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6281 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6282 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006283 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006284 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006285 } else {
6286 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006287 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006288 }
6289 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006290}
6291
John Zulauf8eda1562021-04-13 17:06:41 -06006292bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006293 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006294 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6295 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006296 return false;
6297}
6298
John Zulauf4edde622021-02-15 08:54:50 -07006299void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6300 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6301 const VkMemoryBarrier *barriers) {
6302 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006303 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006304 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006305 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006306 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006307 }
6308 if (0 == memory_barrier_count) {
6309 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006310 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006311 }
John Zulauf4edde622021-02-15 08:54:50 -07006312 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006313}
6314
John Zulauf4edde622021-02-15 08:54:50 -07006315void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6316 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6317 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6318 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006319 for (uint32_t index = 0; index < barrier_count; index++) {
6320 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006321 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006322 if (buffer) {
6323 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6324 const auto range = MakeRange(barrier.offset, barrier_size);
6325 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006326 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006327 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006328 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006329 }
6330 }
6331}
6332
John Zulauf4edde622021-02-15 08:54:50 -07006333void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006334 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006335 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006336 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006337 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006338 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6339 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6340 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006341 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006342 }
John Zulauf4edde622021-02-15 08:54:50 -07006343 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006344}
6345
John Zulauf4edde622021-02-15 08:54:50 -07006346void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6347 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006348 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006349 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006350 for (uint32_t index = 0; index < barrier_count; index++) {
6351 const auto &barrier = barriers[index];
6352 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6353 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006354 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006355 if (buffer) {
6356 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6357 const auto range = MakeRange(barrier.offset, barrier_size);
6358 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006359 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006360 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006361 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006362 }
6363 }
6364}
6365
John Zulauf4edde622021-02-15 08:54:50 -07006366void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6367 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6368 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6369 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006370 for (uint32_t index = 0; index < barrier_count; index++) {
6371 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006372 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006373 if (image) {
6374 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6375 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006376 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006377 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006378 image_memory_barriers.emplace_back();
6379 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006380 }
6381 }
6382}
John Zulaufd5115702021-01-18 12:34:33 -07006383
John Zulauf4edde622021-02-15 08:54:50 -07006384void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6385 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006386 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006387 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006388 for (uint32_t index = 0; index < barrier_count; index++) {
6389 const auto &barrier = barriers[index];
6390 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6391 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006392 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006393 if (image) {
6394 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6395 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006396 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006397 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006398 image_memory_barriers.emplace_back();
6399 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006400 }
6401 }
6402}
6403
sjfricke0bea06e2022-06-05 09:22:26 +09006404SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6405 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6406 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6407 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6408 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6409 const VkImageMemoryBarrier *pImageMemoryBarriers)
6410 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006411 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6412 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006413 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006414}
6415
sjfricke0bea06e2022-06-05 09:22:26 +09006416SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6417 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6418 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006419 MakeEventsList(sync_state, eventCount, pEvents);
6420 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6421}
6422
John Zulauf610e28c2021-08-03 17:46:23 -06006423const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6424
John Zulaufd5115702021-01-18 12:34:33 -07006425bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006426 bool skip = false;
6427 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006428 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006429
John Zulauf610e28c2021-08-03 17:46:23 -06006430 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006431 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6432 const auto &barrier_set = barriers_[barrier_set_index];
6433 if (barrier_set.single_exec_scope) {
6434 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6435 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6436 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6437 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6438 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6439 } else {
6440 const auto &barriers = barrier_set.memory_barriers;
6441 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6442 const auto &barrier = barriers[barrier_index];
6443 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6444 const std::string vuid =
6445 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6446 skip =
6447 sync_state.LogInfo(command_buffer_handle, vuid,
6448 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6449 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6450 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6451 }
6452 }
6453 }
6454 }
John Zulaufd5115702021-01-18 12:34:33 -07006455 }
6456
John Zulauf610e28c2021-08-03 17:46:23 -06006457 // The rest is common to record time and replay time.
6458 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6459 return skip;
6460}
6461
John Zulaufbb890452021-12-14 11:30:18 -07006462bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006463 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006464 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006465 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006466
Jeremy Gebben40a22942020-12-22 14:22:06 -07006467 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006468 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006469 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006470 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006471 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006472 size_t barrier_set_index = 0;
6473 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006474 for (const auto &event : events_) {
6475 const auto *sync_event = events_context->Get(event.get());
6476 const auto &barrier_set = barriers_[barrier_set_index];
6477 if (!sync_event) {
6478 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6479 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6480 // new validation error... wait without previously submitted set event...
6481 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 -07006482 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006483 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006484 }
John Zulauf610e28c2021-08-03 17:46:23 -06006485
6486 // For replay calls, don't revalidate "same command buffer" events
6487 if (sync_event->last_command_tag > base_tag) continue;
6488
John Zulauf78394fc2021-07-12 15:41:40 -06006489 const auto event_handle = sync_event->event->event();
6490 // TODO add "destroyed" checks
6491
John Zulaufe0757ba2022-06-10 16:51:45 -06006492 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006493 // Only accumulate barrier and event stages if there is a pending set in the current context
6494 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6495 event_stage_masks |= sync_event->scope.mask_param;
6496 }
6497
John Zulauf78394fc2021-07-12 15:41:40 -06006498 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006499
sjfricke0bea06e2022-06-05 09:22:26 +09006500 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006501 if (ignore_reason) {
6502 switch (ignore_reason) {
6503 case SyncEventState::ResetWaitRace:
6504 case SyncEventState::Reset2WaitRace: {
6505 // Four permuations of Reset and Wait calls...
6506 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006507 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006508 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006509 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6510 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006511 }
6512 const char *const message =
6513 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6514 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6515 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006516 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006517 break;
6518 }
6519 case SyncEventState::SetRace: {
6520 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6521 // this event
6522 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6523 const char *const message =
6524 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6525 const char *const reason = "First synchronization scope is undefined.";
6526 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6527 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006528 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006529 break;
6530 }
6531 case SyncEventState::MissingStageBits: {
6532 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6533 // Issue error message that event waited for is not in wait events scope
6534 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6535 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6536 ". Bits missing from srcStageMask %s. %s";
6537 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6538 sync_state.report_data->FormatHandle(event_handle).c_str(),
6539 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006540 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006541 break;
6542 }
6543 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006544 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006545 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6546 sync_state.report_data->FormatHandle(event_handle).c_str(),
6547 CommandTypeString(sync_event->last_command));
6548 break;
6549 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006550 case SyncEventState::MissingSetEvent: {
6551 // TODO: There are conditions at queue submit time where we can definitively say that
6552 // a missing set event is an error. Add those if not captured in CoreChecks
6553 break;
6554 }
John Zulauf78394fc2021-07-12 15:41:40 -06006555 default:
6556 assert(ignore_reason == SyncEventState::NotIgnored);
6557 }
6558 } else if (barrier_set.image_memory_barriers.size()) {
6559 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006560 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006561 assert(context);
6562 for (const auto &image_memory_barrier : image_memory_barriers) {
6563 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6564 const auto *image_state = image_memory_barrier.image.get();
6565 if (!image_state) continue;
6566 const auto &subresource_range = image_memory_barrier.range;
6567 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006568 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6569 src_access_scope, queue_id, *sync_event,
6570 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006571 if (hazard.hazard) {
6572 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6573 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6574 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6575 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006576 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006577 break;
6578 }
6579 }
6580 }
6581 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6582 // 03839
6583 barrier_set_index += barrier_set_incr;
6584 }
John Zulaufd5115702021-01-18 12:34:33 -07006585
6586 // 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 -07006587 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 -07006588 if (extra_stage_bits) {
6589 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006590 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6591 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006592 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006593 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006594 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006595 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006596 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006597 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006598 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006599 " vkCmdSetEvent may be in previously submitted command buffer.");
6600 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006601 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006602 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006603 }
6604 }
6605 return skip;
6606}
6607
6608struct SyncOpWaitEventsFunctorFactory {
6609 using BarrierOpFunctor = WaitEventBarrierOp;
6610 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6611 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6612 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6613 using BufferRange = EventSimpleRangeGenerator;
6614 using ImageRange = EventImageRangeGenerator;
6615 using GlobalRange = EventSimpleRangeGenerator;
6616
6617 // Need to restrict to only valid exec and access scope for this event
6618 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6619 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006620 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006621 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6622 return barrier;
6623 }
John Zulauf00119522022-05-23 19:07:42 -06006624 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006625 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006626 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006627 }
John Zulauf14940722021-04-12 15:19:02 -06006628 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006629 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6630 }
John Zulauf00119522022-05-23 19:07:42 -06006631 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006632 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006633 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006634 }
6635
6636 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6637 const AccessAddressType address_type = GetAccessAddressType(buffer);
6638 const auto base_address = ResourceBaseAddress(buffer);
6639 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6640 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6641 return filtered_range_gen;
6642 }
John Zulauf110413c2021-03-20 05:38:38 -06006643 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006644 if (!SimpleBinding(image)) return ImageRange();
6645 const auto address_type = GetAccessAddressType(image);
6646 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006647 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6648 false);
John Zulaufd5115702021-01-18 12:34:33 -07006649 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6650
6651 return filtered_range_gen;
6652 }
6653 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6654 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6655 }
6656 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6657 SyncEventState *sync_event;
6658};
6659
John Zulaufdab327f2022-07-08 12:02:05 -06006660ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006661 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006662
John Zulauf0223f142022-07-06 09:05:39 -06006663 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006664 return tag;
6665}
6666
John Zulauf0223f142022-07-06 09:05:39 -06006667void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006668 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6669 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6670 // 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 -06006671 if (!exec_context.ValidForSyncOps()) return;
6672 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6673 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6674 const QueueId queue_id = exec_context.GetQueueId();
6675
John Zulaufd5115702021-01-18 12:34:33 -07006676 access_context->ResolvePreviousAccesses();
6677
John Zulauf4edde622021-02-15 08:54:50 -07006678 size_t barrier_set_index = 0;
6679 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6680 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006681 for (auto &event_shared : events_) {
6682 if (!event_shared.get()) continue;
6683 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006684
sjfricke0bea06e2022-06-05 09:22:26 +09006685 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006686 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006687
John Zulauf4edde622021-02-15 08:54:50 -07006688 const auto &barrier_set = barriers_[barrier_set_index];
6689 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006690 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006691 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6692 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6693 // of the barriers is maintained.
6694 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006695 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6696 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6697 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006698
6699 // Apply the global barrier to the event itself (for race condition tracking)
6700 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6701 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6702 sync_event->barriers |= dst.exec_scope;
6703 } else {
6704 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6705 sync_event->barriers = 0U;
6706 }
John Zulauf4edde622021-02-15 08:54:50 -07006707 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006708 }
6709
6710 // Apply the pending barriers
6711 ResolvePendingBarrierFunctor apply_pending_action(tag);
6712 access_context->ApplyToContext(apply_pending_action);
6713}
6714
John Zulauf8eda1562021-04-13 17:06:41 -06006715bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006716 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6717 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006718}
6719
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006720bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6721 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6722 bool skip = false;
6723 const auto *cb_access_context = GetAccessContext(commandBuffer);
6724 assert(cb_access_context);
6725 if (!cb_access_context) return skip;
6726
6727 const auto *context = cb_access_context->GetCurrentAccessContext();
6728 assert(context);
6729 if (!context) return skip;
6730
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006731 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006732
6733 if (dst_buffer) {
6734 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6735 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6736 if (hazard.hazard) {
6737 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6738 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6739 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006740 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006741 }
6742 }
6743 return skip;
6744}
6745
John Zulauf669dfd52021-01-27 17:15:28 -07006746void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006747 events_.reserve(event_count);
6748 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006749 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006750 }
6751}
John Zulauf6ce24372021-01-30 05:56:25 -07006752
sjfricke0bea06e2022-06-05 09:22:26 +09006753SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006754 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006755 : SyncOpBase(cmd_type),
6756 event_(sync_state.Get<EVENT_STATE>(event)),
6757 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006758
John Zulauf1bf30522021-09-03 15:39:06 -06006759bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6760 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6761}
6762
John Zulaufbb890452021-12-14 11:30:18 -07006763bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6764 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006765 assert(events_context);
6766 bool skip = false;
6767 if (!events_context) return skip;
6768
John Zulaufbb890452021-12-14 11:30:18 -07006769 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006770 const auto *sync_event = events_context->Get(event_);
6771 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6772
John Zulauf1bf30522021-09-03 15:39:06 -06006773 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6774
John Zulauf6ce24372021-01-30 05:56:25 -07006775 const char *const set_wait =
6776 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6777 "hazards.";
6778 const char *message = set_wait; // Only one message this call.
6779 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6780 const char *vuid = nullptr;
6781 switch (sync_event->last_command) {
6782 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006783 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006784 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006785 // Needs a barrier between set and reset
6786 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6787 break;
John Zulauf4edde622021-02-15 08:54:50 -07006788 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006789 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006790 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006791 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6792 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6793 break;
6794 }
6795 default:
6796 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006797 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6798 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006799 break;
6800 }
6801 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006802 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6803 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006804 CommandTypeString(sync_event->last_command));
6805 }
6806 }
6807 return skip;
6808}
6809
John Zulaufdab327f2022-07-08 12:02:05 -06006810ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006811 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006812 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006813 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006814}
6815
John Zulauf8eda1562021-04-13 17:06:41 -06006816bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006817 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6818 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006819}
6820
John Zulauf0223f142022-07-06 09:05:39 -06006821void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6822 if (!exec_context.ValidForSyncOps()) return;
6823 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6824
John Zulaufe0757ba2022-06-10 16:51:45 -06006825 auto *sync_event = events_context->GetFromShared(event_);
6826 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6827
6828 // Update the event state
6829 sync_event->last_command = cmd_type_;
6830 sync_event->last_command_tag = tag;
6831 sync_event->unsynchronized_set = CMD_NONE;
6832 sync_event->ResetFirstScope();
6833 sync_event->barriers = 0U;
6834}
John Zulauf8eda1562021-04-13 17:06:41 -06006835
sjfricke0bea06e2022-06-05 09:22:26 +09006836SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006837 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006838 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006839 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006840 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006841 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006842 dep_info_() {
6843 // Snapshot the current access_context for later inspection at wait time.
6844 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6845 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6846 // or Submit time reference.
6847 if (access_context) {
6848 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6849 }
6850}
John Zulauf4edde622021-02-15 08:54:50 -07006851
sjfricke0bea06e2022-06-05 09:22:26 +09006852SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006853 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006854 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006855 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006856 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006857 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006858 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6859 if (access_context) {
6860 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6861 }
6862}
John Zulauf6ce24372021-01-30 05:56:25 -07006863
6864bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006865 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6866}
6867bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006868 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6869 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006870}
6871
John Zulaufbb890452021-12-14 11:30:18 -07006872bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006873 bool skip = false;
6874
John Zulaufbb890452021-12-14 11:30:18 -07006875 const auto &sync_state = exec_context.GetSyncState();
6876 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006877 assert(events_context);
6878 if (!events_context) return skip;
6879
6880 const auto *sync_event = events_context->Get(event_);
6881 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6882
John Zulauf610e28c2021-08-03 17:46:23 -06006883 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6884
John Zulauf6ce24372021-01-30 05:56:25 -07006885 const char *const reset_set =
6886 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6887 "hazards.";
6888 const char *const wait =
6889 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6890
6891 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006892 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006893 const char *message = nullptr;
6894 switch (sync_event->last_command) {
6895 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006896 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006897 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006898 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006899 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006900 message = reset_set;
6901 break;
6902 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006903 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006904 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006905 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006906 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006907 message = reset_set;
6908 break;
6909 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006910 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006911 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006912 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006913 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006914 message = wait;
6915 break;
6916 default:
6917 // The only other valid last command that wasn't one.
6918 assert(sync_event->last_command == CMD_NONE);
6919 break;
6920 }
John Zulauf4edde622021-02-15 08:54:50 -07006921 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006922 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006923 std::string vuid("SYNC-");
6924 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006925 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6926 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006927 CommandTypeString(sync_event->last_command));
6928 }
6929 }
6930
6931 return skip;
6932}
6933
John Zulaufdab327f2022-07-08 12:02:05 -06006934ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006935 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006936 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006937 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006938 assert(recorded_context_);
6939 if (recorded_context_ && events_context) {
6940 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006941 }
6942 return tag;
6943}
John Zulauf6ce24372021-01-30 05:56:25 -07006944
John Zulauf0223f142022-07-06 09:05:39 -06006945void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006946 // Create a copy of the current context, and merge in the state snapshot at record set event time
6947 // 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 -06006948 if (!exec_context.ValidForSyncOps()) return;
6949 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6950 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6951 const QueueId queue_id = exec_context.GetQueueId();
6952
John Zulaufe0757ba2022-06-10 16:51:45 -06006953 auto merged_context = std::make_shared<AccessContext>(*access_context);
6954 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6955 DoRecord(queue_id, tag, merged_context, events_context);
6956}
6957
6958void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6959 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006960 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006961 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006962
6963 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6964 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6965 // any issues caused by naive scope setting here.
6966
6967 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6968 // Given:
6969 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6970 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6971
6972 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6973 sync_event->unsynchronized_set = sync_event->last_command;
6974 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006975 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006976 // We only set the scope if there isn't one
6977 sync_event->scope = src_exec_scope_;
6978
John Zulaufe0757ba2022-06-10 16:51:45 -06006979 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6980 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006981 sync_event->unsynchronized_set = CMD_NONE;
6982 sync_event->first_scope_tag = tag;
6983 }
John Zulauf4edde622021-02-15 08:54:50 -07006984 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006985 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006986 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006987 sync_event->barriers = 0U;
6988}
John Zulauf64ffe552021-02-06 10:25:07 -07006989
sjfricke0bea06e2022-06-05 09:22:26 +09006990SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006991 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006992 const VkSubpassBeginInfo *pSubpassBeginInfo)
John Zulaufdab327f2022-07-08 12:02:05 -06006993 : SyncOpBase(cmd_type), rp_context_(nullptr) {
John Zulauf64ffe552021-02-06 10:25:07 -07006994 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006995 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006996 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006997 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006998 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006999 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07007000 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
7001 // Note that this a safe to presist as long as shared_attachments is not cleared
7002 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08007003 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07007004 attachments_.emplace_back(attachment.get());
7005 }
7006 }
7007 if (pSubpassBeginInfo) {
7008 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
7009 }
7010 }
7011}
7012
7013bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7014 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
7015 bool skip = false;
7016
7017 assert(rp_state_.get());
7018 if (nullptr == rp_state_.get()) return skip;
7019 auto &rp_state = *rp_state_.get();
7020
7021 const uint32_t subpass = 0;
7022
7023 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
7024 // hasn't happened yet)
7025 const std::vector<AccessContext> empty_context_vector;
7026 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
7027 cb_context.GetCurrentAccessContext());
7028
7029 // Validate attachment operations
7030 if (attachments_.size() == 0) return skip;
7031 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007032
7033 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7034 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7035 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7036 // operations (though it's currently a messy approach)
7037 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007038 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007039
7040 // Validate load operations if there were no layout transition hazards
7041 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007042 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007043 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007044 }
7045
7046 return skip;
7047}
7048
John Zulaufdab327f2022-07-08 12:02:05 -06007049ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) {
John Zulauf64ffe552021-02-06 10:25:07 -07007050 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007051 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
John Zulaufdab327f2022-07-08 12:02:05 -06007052 const ResourceUsageTag begin_tag =
7053 cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
7054
7055 // Note: this state update must be after RecordBeginRenderPass as there is no current render pass until that function runs
7056 rp_context_ = cb_context->GetCurrentRenderPassContext();
7057
7058 return begin_tag;
John Zulauf64ffe552021-02-06 10:25:07 -07007059}
7060
John Zulauf8eda1562021-04-13 17:06:41 -06007061bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007062 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007063 return false;
7064}
7065
John Zulaufdab327f2022-07-08 12:02:05 -06007066void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7067 // Need to update the exec_contexts state (which for RenderPass operations *must* be a QueueBatchContext, as
7068 // render pass operations are not allowed in secondary command buffers.
7069 const QueueId queue_id = exec_context.GetQueueId();
7070 assert(queue_id != QueueSyncState::kQueueIdInvalid); // Renderpass replay only valid at submit (not exec) time
7071 if (queue_id == QueueSyncState::kQueueIdInvalid) return;
7072
7073 exec_context.BeginRenderPassReplay(*this, tag);
7074}
John Zulauf8eda1562021-04-13 17:06:41 -06007075
sjfricke0bea06e2022-06-05 09:22:26 +09007076SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7077 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7078 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007079 if (pSubpassBeginInfo) {
7080 subpass_begin_info_.initialize(pSubpassBeginInfo);
7081 }
7082 if (pSubpassEndInfo) {
7083 subpass_end_info_.initialize(pSubpassEndInfo);
7084 }
7085}
7086
7087bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7088 bool skip = false;
7089 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7090 if (!renderpass_context) return skip;
7091
sjfricke0bea06e2022-06-05 09:22:26 +09007092 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007093 return skip;
7094}
7095
John Zulaufdab327f2022-07-08 12:02:05 -06007096ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007097 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007098}
7099
7100bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007101 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007102 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007103}
7104
sjfricke0bea06e2022-06-05 09:22:26 +09007105SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7106 const VkSubpassEndInfo *pSubpassEndInfo)
7107 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007108 if (pSubpassEndInfo) {
7109 subpass_end_info_.initialize(pSubpassEndInfo);
7110 }
7111}
7112
John Zulaufdab327f2022-07-08 12:02:05 -06007113void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7114 exec_context.NextSubpassReplay();
7115}
John Zulauf8eda1562021-04-13 17:06:41 -06007116
John Zulauf64ffe552021-02-06 10:25:07 -07007117bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7118 bool skip = false;
7119 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7120
7121 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007122 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007123 return skip;
7124}
7125
John Zulaufdab327f2022-07-08 12:02:05 -06007126ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007127 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007128}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007129
John Zulauf8eda1562021-04-13 17:06:41 -06007130bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007131 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007132 return false;
7133}
7134
John Zulaufdab327f2022-07-08 12:02:05 -06007135void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7136 exec_context.EndRenderPassReplay();
7137}
John Zulauf8eda1562021-04-13 17:06:41 -06007138
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007139void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7140 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7141 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7142 auto *cb_access_context = GetAccessContext(commandBuffer);
7143 assert(cb_access_context);
7144 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7145 auto *context = cb_access_context->GetCurrentAccessContext();
7146 assert(context);
7147
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007148 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007149
7150 if (dst_buffer) {
7151 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7152 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7153 }
7154}
John Zulaufd05c5842021-03-26 11:32:16 -06007155
John Zulaufae842002021-04-15 18:20:55 -06007156bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7157 const VkCommandBuffer *pCommandBuffers) const {
7158 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007159 const auto *cb_context = GetAccessContext(commandBuffer);
7160 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007161
7162 // Heavyweight, but we need a proxy copy of the active command buffer access context
7163 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007164
7165 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007166 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007167 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7168
John Zulaufae842002021-04-15 18:20:55 -06007169 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7170 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007171
7172 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7173 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007174 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007175
7176 // The barriers have already been applied in ValidatFirstUse
7177 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007178 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007179 }
7180
John Zulaufae842002021-04-15 18:20:55 -06007181 return skip;
7182}
7183
7184void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7185 const VkCommandBuffer *pCommandBuffers) {
7186 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007187 auto *cb_context = GetAccessContext(commandBuffer);
7188 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007189 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007190 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007191 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7192 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007193 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007194 }
John Zulaufae842002021-04-15 18:20:55 -06007195}
7196
John Zulauf1d5f9c12022-05-13 14:51:08 -06007197void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7198 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7199 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7200
7201 const auto queue_state = GetQueueSyncStateShared(queue);
7202 if (!queue_state) return; // Invalid queue
7203 QueueId waited_queue = queue_state->GetQueueId();
John Zulauf3da08bb2022-08-01 17:56:56 -06007204 ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007205
John Zulauf3da08bb2022-08-01 17:56:56 -06007206 // Eliminate waitable fences from the current queue.
7207 layer_data::EraseIf(waitable_fences_, [waited_queue](const SignaledFence &sf) { return sf.second.queue_id == waited_queue; });
John Zulauf1d5f9c12022-05-13 14:51:08 -06007208}
7209
7210void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7211 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007212
7213 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7214 for (auto &batch : queue_batch_contexts) {
7215 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007216 }
7217
John Zulauf3da08bb2022-08-01 17:56:56 -06007218 // As we we've waited for everything on device, any waits are mooted.
7219 waitable_fences_.clear();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007220}
7221
John Zulauf697c0e12022-04-19 16:31:12 -06007222struct QueueSubmitCmdState {
7223 std::shared_ptr<const QueueSyncState> queue;
7224 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007225 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007226 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007227 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7228 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007229};
7230
7231template <>
7232thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7233
John Zulaufbbda4572022-04-19 16:20:45 -06007234bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7235 VkFence fence) const {
7236 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007237
7238 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007239 if (!enabled[sync_validation_queue_submit]) return skip;
7240
John Zulauf00119522022-05-23 19:07:42 -06007241 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007242 const auto fence_state = Get<FENCE_STATE>(fence);
7243 cmd_state->queue = GetQueueSyncStateShared(queue);
7244 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007245
John Zulauf697c0e12022-04-19 16:31:12 -06007246 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7247 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7248
7249 // verify each submit batch
7250 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7251 // most recently created batch
7252 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7253 std::shared_ptr<QueueBatchContext> batch;
7254 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7255 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007256 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7257 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007258
John Zulaufe0757ba2022-06-10 16:51:45 -06007259 // Skip import and validation of empty batches
7260 if (batch->GetTagRange().size()) {
7261 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007262
John Zulaufe0757ba2022-06-10 16:51:45 -06007263 // For each submit in the batch...
7264 for (const auto &cb : *batch) {
7265 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
John Zulauf0223f142022-07-06 09:05:39 -06007266 skip |= cb.cb->ValidateFirstUse(*batch.get(), "vkQueueSubmit", cb.index);
John Zulaufe0757ba2022-06-10 16:51:45 -06007267
7268 // The barriers have already been applied in ValidatFirstUse
7269 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7270 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7271 }
John Zulauf697c0e12022-04-19 16:31:12 -06007272 }
7273
John Zulaufe0757ba2022-06-10 16:51:45 -06007274 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007275 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7276 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007277 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007278 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007279 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7280 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7281 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007282 }
7283 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7284 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7285 last_batch = batch;
7286 }
7287 // The most recently created batch will become the queue's "last batch" in the record phase
7288 if (batch) {
7289 cmd_state->last_batch = std::move(batch);
7290 }
7291
7292 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007293 return skip;
7294}
7295
7296void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7297 VkResult result) {
7298 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007299
John Zulaufcb7e1672022-05-04 13:46:08 -06007300 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007301 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7302
John Zulaufcb7e1672022-05-04 13:46:08 -06007303 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7304 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007305 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007306
7307 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007308 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7309
John Zulauf697c0e12022-04-19 16:31:12 -06007310 // Don't need to look up the queue state again, but we need a non-const version
7311 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007312
John Zulaufcb7e1672022-05-04 13:46:08 -06007313 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7314 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7315 // QBC's are those referenced by unwaited signals and the last batch.
7316 for (auto &sig_sem : cmd_state->signaled) {
7317 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007318 auto &sig_batch = sig_sem.second->batch;
7319 sig_batch->ResetAccessLog();
7320 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7321 if (sig_batch != cmd_state->last_batch) {
7322 sig_batch->ResetEventsContext();
7323 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007324 }
7325 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007326 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007327 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007328
John Zulaufcb7e1672022-05-04 13:46:08 -06007329 // Update the queue to point to the last batch from the submit
7330 if (cmd_state->last_batch) {
7331 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007332
7333 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7334 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7335 auto last_batch = queue_state->LastBatch();
7336 if (last_batch) {
7337 last_batch->ResetEventsContext();
7338 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007339 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007340 }
7341
7342 // Update the global access log from the one built during validation
7343 global_access_log_.MergeMove(std::move(cmd_state->logger));
7344
John Zulauf3da08bb2022-08-01 17:56:56 -06007345 ResourceUsageRange fence_tag_range = ReserveGlobalTagRange(1U);
7346 UpdateFenceWaitInfo(fence, queue_state->GetQueueId(), fence_tag_range.begin);
John Zulaufbbda4572022-04-19 16:20:45 -06007347}
7348
7349bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7350 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007351 bool skip = false;
7352 if (!enabled[sync_validation_queue_submit]) return skip;
7353
John Zulauf697c0e12022-04-19 16:31:12 -06007354 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007355 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007356}
7357
7358void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7359 VkFence fence, VkResult result) {
7360 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007361 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7362
7363 if (!enabled[sync_validation_queue_submit]) return;
7364
John Zulauf697c0e12022-04-19 16:31:12 -06007365 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007366}
7367
John Zulauf3da08bb2022-08-01 17:56:56 -06007368void SyncValidator::PostCallRecordGetFenceStatus(VkDevice device, VkFence fence, VkResult result) {
7369 StateTracker::PostCallRecordGetFenceStatus(device, fence, result);
7370 if (!enabled[sync_validation_queue_submit]) return;
7371 if (result == VK_SUCCESS) {
7372 // fence is signalled, mark it as waited for
7373 WaitForFence(fence);
7374 }
7375}
7376
7377void SyncValidator::PostCallRecordWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
7378 uint64_t timeout, VkResult result) {
7379 StateTracker::PostCallRecordWaitForFences(device, fenceCount, pFences, waitAll, timeout, result);
7380 if (!enabled[sync_validation_queue_submit]) return;
7381 if ((result == VK_SUCCESS) && ((VK_TRUE == waitAll) || (1 == fenceCount))) {
7382 // We can only know the pFences have signal if we waited for all of them, or there was only one of them
7383 for (uint32_t i = 0; i < fenceCount; i++) {
7384 WaitForFence(pFences[i]);
7385 }
7386 }
7387}
7388
John Zulaufd0ec59f2021-03-13 14:25:08 -07007389AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7390 : view_(view), view_mask_(), gen_store_() {
7391 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7392 const IMAGE_STATE &image_state = *view_->image_state.get();
7393 const auto base_address = ResourceBaseAddress(image_state);
7394 const auto *encoder = image_state.fragment_encoder.get();
7395 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007396 // Get offset and extent for the view, accounting for possible depth slicing
7397 const VkOffset3D zero_offset = view->GetOffset();
7398 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007399 // Intentional copy
7400 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7401 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007402 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7403 view->IsDepthSliced());
7404 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007405
7406 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7407 if (depth && (depth != view_mask_)) {
7408 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007409 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007410 }
7411 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7412 if (stencil && (stencil != view_mask_)) {
7413 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007414 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7415 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007416 }
7417}
7418
7419const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7420 const ImageRangeGen *got = nullptr;
7421 switch (gen_type) {
7422 case kViewSubresource:
7423 got = &gen_store_[kViewSubresource];
7424 break;
7425 case kRenderArea:
7426 got = &gen_store_[kRenderArea];
7427 break;
7428 case kDepthOnlyRenderArea:
7429 got =
7430 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7431 break;
7432 case kStencilOnlyRenderArea:
7433 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7434 : &gen_store_[Gen::kStencilOnlyRenderArea];
7435 break;
7436 default:
7437 assert(got);
7438 }
7439 return got;
7440}
7441
7442AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7443 assert(IsValid());
7444 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7445 if (depth_op) {
7446 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7447 if (stencil_op) {
7448 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7449 return kRenderArea;
7450 }
7451 return kDepthOnlyRenderArea;
7452 }
7453 if (stencil_op) {
7454 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7455 return kStencilOnlyRenderArea;
7456 }
7457
7458 assert(depth_op || stencil_op);
7459 return kRenderArea;
7460}
7461
7462AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007463
John Zulaufe0757ba2022-06-10 16:51:45 -06007464void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007465 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7466 for (auto &event_pair : map_) {
7467 assert(event_pair.second); // Shouldn't be storing empty
7468 auto &sync_event = *event_pair.second;
7469 // 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 -06007470 // But only if occuring before the tag
7471 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007472 sync_event.barriers |= dst.exec_scope;
7473 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7474 }
7475 }
7476}
John Zulaufbb890452021-12-14 11:30:18 -07007477
John Zulaufe0757ba2022-06-10 16:51:45 -06007478void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7479 const SyncExecScope src_scope =
7480 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7481 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7482 ApplyBarrier(src_scope, dst_scope, tag);
7483}
7484
7485SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7486 // We need a deep copy of the const context to update during validation phase
7487 for (const auto &event : from.map_) {
7488 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7489 }
7490 return *this;
7491}
7492
John Zulaufcb7e1672022-05-04 13:46:08 -06007493QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
John Zulaufdab327f2022-07-08 12:02:05 -06007494 : CommandExecutionContext(&sync_state),
7495 queue_state_(&queue_state),
7496 tag_range_(0, 0),
7497 current_access_context_(&access_context_),
7498 batch_log_(nullptr) {}
John Zulaufcb7e1672022-05-04 13:46:08 -06007499
John Zulauf697c0e12022-04-19 16:31:12 -06007500template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007501void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7502 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007503 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007504 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007505}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007506void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007507 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007508}
John Zulauf697c0e12022-04-19 16:31:12 -06007509
7510VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7511
John Zulauf1d5f9c12022-05-13 14:51:08 -06007512void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
John Zulauf3da08bb2022-08-01 17:56:56 -06007513 ResourceAccessState::QueueTagPredicate predicate{queue_id, tag};
7514 access_context_.EraseIf([&predicate](ResourceAccessRangeMap::value_type &access) {
7515 // Apply..Wait returns true if the waited access is empty...
7516 return access.second.ApplyQueueTagWait(predicate);
7517 });
John Zulaufe0757ba2022-06-10 16:51:45 -06007518
7519 if (queue_id == GetQueueId()) {
7520 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7521 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007522}
7523
7524// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007525void QueueBatchContext::ApplyDeviceWait() {
7526 access_context_.Reset();
7527 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7528}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007529
John Zulaufdab327f2022-07-08 12:02:05 -06007530HazardResult QueueBatchContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
7531 // Queue batch handling requires dealing with renderpass state and picking the correct access context
7532 if (rp_replay_) {
7533 return rp_replay_.replay_context->DetectFirstUseHazard(GetQueueId(), tag_range, *current_access_context_);
7534 }
7535 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, access_context_);
7536}
7537
7538void QueueBatchContext::BeginRenderPassReplay(const SyncOpBeginRenderPass &begin_op, const ResourceUsageTag tag) {
7539 current_access_context_ = rp_replay_.Begin(GetQueueFlags(), begin_op, access_context_);
7540 current_access_context_->ResolvePreviousAccesses();
7541}
7542
7543void QueueBatchContext::NextSubpassReplay() {
7544 current_access_context_ = rp_replay_.Next();
7545 current_access_context_->ResolvePreviousAccesses();
7546}
7547
7548void QueueBatchContext::EndRenderPassReplay() {
7549 rp_replay_.End(access_context_);
7550 current_access_context_ = &access_context_;
7551}
7552
7553AccessContext *QueueBatchContext::RenderPassReplayState::Begin(VkQueueFlags queue_flags, const SyncOpBeginRenderPass &begin_op_,
7554 const AccessContext &external_context) {
7555 Reset();
7556
7557 begin_op = &begin_op_;
7558 subpass = 0;
7559
7560 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7561 assert(rp_context);
7562 replay_context = &rp_context->GetContexts()[0];
7563
7564 InitSubpassContexts(queue_flags, *rp_context->GetRenderPassState(), &external_context, subpass_contexts);
7565 return &subpass_contexts[0];
7566}
7567
7568AccessContext *QueueBatchContext::RenderPassReplayState::Next() {
7569 subpass++;
7570
7571 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7572
7573 replay_context = &rp_context->GetContexts()[subpass];
7574 return &subpass_contexts[subpass];
7575}
7576
7577void QueueBatchContext::RenderPassReplayState::End(AccessContext &external_context) {
7578 external_context.ResolveChildContexts(subpass_contexts);
7579 Reset();
7580}
7581
John Zulaufecf4ac52022-06-06 10:08:42 -06007582class ApplySemaphoreBarrierAction {
7583 public:
7584 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7585 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7586
7587 private:
7588 const SemaphoreScope &signal_;
7589 const SemaphoreScope wait_;
7590};
7591
7592std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7593 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007594 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007595 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007596
John Zulaufcb7e1672022-05-04 13:46:08 -06007597 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7598 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007599 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007600
John Zulaufecf4ac52022-06-06 10:08:42 -06007601 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007602
John Zulaufecf4ac52022-06-06 10:08:42 -06007603 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007604 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007605 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7606 if (signal_scope.queue == wait_scope.queue) {
7607 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7608 // valid accesses for the sync scope.
7609 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7610 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7611 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007612 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007613 } else {
7614 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7615 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007616 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007617 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7618 // enforce deep constness.
7619 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007620}
7621
7622// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7623template <>
7624class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7625 public:
7626 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7627 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7628 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7629 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7630 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7631 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7632
7633 private:
7634 const VkSubmitInfo &info_;
7635};
7636template <typename BatchInfo, typename Fn>
7637void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7638 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7639 Accessor batch(batch_info);
7640 const uint32_t wait_count = batch.WaitSemaphoreCount();
7641 for (uint32_t i = 0; i < wait_count; ++i) {
7642 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7643 }
7644}
7645
7646template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007647void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7648 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007649 // Copy in the event state from the previous batch (on this queue)
7650 if (prev) {
7651 events_context_.DeepCopy(prev->events_context_);
7652 }
7653
John Zulaufecf4ac52022-06-06 10:08:42 -06007654 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7655 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7656 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7657 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7658 if (resolved) {
7659 batches_resolved.emplace(std::move(resolved));
7660 }
John Zulauf697c0e12022-04-19 16:31:12 -06007661 });
7662
John Zulaufecf4ac52022-06-06 10:08:42 -06007663 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7664 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7665 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007666 }
7667
John Zulauf697c0e12022-04-19 16:31:12 -06007668 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007669 async_batches_ =
7670 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7671 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007672 });
7673 for (const auto &async_batch : async_batches_) {
7674 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7675 }
7676}
7677
7678template <typename BatchInfo>
7679void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7680 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7681 Accessor batch(batch_info);
7682
7683 // Create the list of command buffers to submit
7684 const uint32_t cb_count = batch.CommandBufferCount();
7685 command_buffers_.reserve(cb_count);
7686 for (uint32_t index = 0; index < cb_count; ++index) {
7687 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7688 if (cb_context) {
7689 tag_range_.end += cb_context->GetTagLimit();
7690 command_buffers_.emplace_back(index, std::move(cb_context));
7691 }
7692 }
7693}
7694
7695// Look up the usage informaiton from the local or global logger
7696std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7697 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7698 std::stringstream out;
7699 AccessLogger::AccessRecord access = use_logger[tag];
7700 if (access.IsValid()) {
7701 const AccessLogger::BatchRecord &batch = *access.batch;
7702 const ResourceUsageRecord &record = *access.record;
7703 // Queue and Batch information
7704 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7705 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7706
7707 // Commandbuffer Usages Information
7708 out << record;
7709 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7710 out << ", reset_no: " << std::to_string(record.reset_count);
7711 }
7712 return out.str();
7713}
7714
7715VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7716
John Zulauf00119522022-05-23 19:07:42 -06007717QueueId QueueBatchContext::GetQueueId() const {
7718 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7719 return id;
7720}
7721
John Zulauf697c0e12022-04-19 16:31:12 -06007722void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7723 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7724 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7725 SetTagBias(global_tags.begin);
7726 // Add an access log for the batches range and point the batch at it.
7727 logger_ = &logger;
7728 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7729}
7730
7731void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7732 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7733 batch_log_->Append(submitted_cb.GetAccessLog());
7734}
7735
7736void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7737 const auto size = tag_range_.size();
7738 tag_range_.begin = bias;
7739 tag_range_.end = bias + size;
7740 access_context_.SetStartTag(bias);
7741}
7742
John Zulauf697c0e12022-04-19 16:31:12 -06007743AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7744 const ResourceUsageRange &range) {
7745 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7746 assert(inserted.second);
7747 return &inserted.first->second;
7748}
7749
7750void AccessLogger::MergeMove(AccessLogger &&child) {
7751 for (auto &range : child.access_log_map_) {
7752 BatchLog &child_batch = range.second;
7753 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7754 insert_pair.first->second = std::move(child_batch);
7755 assert(insert_pair.second);
7756 }
7757 child.Reset();
7758}
7759
7760void AccessLogger::Reset() {
7761 prev_ = nullptr;
7762 access_log_map_.clear();
7763}
7764
7765// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7766// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7767// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7768// the contexts Resolve all history from previous all contexts when created
7769void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7770 last_batch_ = std::move(last);
7771 last_batch_->ResetAccessLog();
7772}
7773
7774// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7775// scope state.
7776// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7777// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7778uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7779
7780void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7781 log_.insert(log_.end(), other.cbegin(), other.cend());
7782 for (const auto &record : other) {
7783 assert(record.cb_state);
7784 cbs_referenced_.insert(record.cb_state->shared_from_this());
7785 }
7786}
7787
7788AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7789 assert(index < log_.size());
7790 return AccessRecord{&batch_, &log_[index]};
7791}
7792
7793AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7794 AccessRecord access_record = {nullptr, nullptr};
7795
7796 auto found_range = access_log_map_.find(tag);
7797 if (found_range != access_log_map_.cend()) {
7798 const ResourceUsageTag bias = found_range->first.begin;
7799 assert(tag >= bias);
7800 access_record = found_range->second[tag - bias];
7801 } else if (prev_) {
7802 access_record = (*prev_)[tag];
7803 }
7804
7805 return access_record;
7806}
John Zulaufcb7e1672022-05-04 13:46:08 -06007807
John Zulaufecf4ac52022-06-06 10:08:42 -06007808// This is a const method, force the returned value to be const
7809std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007810 std::shared_ptr<Signal> prev_state;
7811 if (prev_) {
7812 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7813 }
7814 return prev_state;
7815}
John Zulaufecf4ac52022-06-06 10:08:42 -06007816
7817SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7818 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7819 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7820 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7821 assert(batch);
7822 assert(sem_state);
7823}
John Zulauf3da08bb2022-08-01 17:56:56 -06007824
7825FenceSyncState::FenceSyncState() : fence(), tag(kInvalidTag), queue_id(QueueSyncState::kQueueIdInvalid) {}