blob: 7748d578c5fc63d6292352e94e6eab93bc012e85 [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 Zulauff26fca92022-08-15 11:53:34 -0600863template <typename Action>
864void AccessContext::ConstForAll(Action &&action) const {
865 for (const auto address_type : kAddressTypes) {
866 auto &accesses = GetAccessStateMap(address_type);
867 for (auto &access : accesses) {
868 action(address_type, access);
869 }
870 }
871}
872
John Zulauf3da08bb2022-08-01 17:56:56 -0600873template <typename Predicate>
874void AccessContext::EraseIf(Predicate &&pred) {
875 for (const auto address_type : kAddressTypes) {
876 auto &accesses = GetAccessStateMap(address_type);
877 // Note: Don't forward, we don't want r-values moved, since we're going to make multiple calls.
878 layer_data::EraseIf(accesses, pred);
879 }
880}
881
John Zulauf3d84f1b2020-03-09 13:33:25 -0600882// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
883// the DAG of the contexts (for example subpasses)
884template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600885HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600886 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600887 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600888
John Zulauf1a224292020-06-30 14:52:13 -0600889 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600890 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
891 // so we'll check these first
892 for (const auto &async_context : async_) {
893 hazard = async_context->DetectAsyncHazard(type, detector, range);
894 if (hazard.hazard) return hazard;
895 }
John Zulauf5f13a792020-03-10 07:31:21 -0600896 }
897
John Zulauf1a224292020-06-30 14:52:13 -0600898 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600899
John Zulauf69133422020-05-20 14:55:53 -0600900 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600901 const auto the_end = accesses.cend(); // End is not invalidated
902 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600903 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600904
John Zulauf3cafbf72021-03-26 16:55:19 -0600905 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600906 // Cover any leading gap, or gap between entries
907 if (detect_prev) {
908 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
909 // Cover any leading gap, or gap between entries
910 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600911 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600912 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600913 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600914 if (hazard.hazard) return hazard;
915 }
John Zulauf69133422020-05-20 14:55:53 -0600916 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
917 gap.begin = pos->first.end;
918 }
919
920 hazard = detector.Detect(pos);
921 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600922 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600923 }
924
925 if (detect_prev) {
926 // Detect in the trailing empty as needed
927 gap.end = range.end;
928 if (gap.non_empty()) {
929 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600930 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600931 }
932
933 return hazard;
934}
935
936// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
937template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700938HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
939 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600940 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600941 auto pos = accesses.lower_bound(range);
942 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600943
John Zulauf3d84f1b2020-03-09 13:33:25 -0600944 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600945 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700946 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600947 if (hazard.hazard) break;
948 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600949 }
John Zulauf16adfc92020-04-08 10:28:33 -0600950
John Zulauf3d84f1b2020-03-09 13:33:25 -0600951 return hazard;
952}
953
John Zulaufb02c1eb2020-10-06 16:33:36 -0600954struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700955 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600956 void operator()(ResourceAccessState *access) const {
957 assert(access);
958 access->ApplyBarriers(barriers, true);
959 }
960 const std::vector<SyncBarrier> &barriers;
961};
962
John Zulaufe0757ba2022-06-10 16:51:45 -0600963struct QueueTagOffsetBarrierAction {
964 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
965 void operator()(ResourceAccessState *access) const {
966 access->OffsetTag(tag_offset);
967 access->SetQueueId(queue_id);
968 };
969 QueueId queue_id;
970 ResourceUsageTag tag_offset;
971};
972
John Zulauf22aefed2021-03-11 18:14:35 -0700973struct ApplyTrackbackStackAction {
974 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
975 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
976 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977 void operator()(ResourceAccessState *access) const {
978 assert(access);
979 assert(!access->HasPendingState());
980 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600981 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
982 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700983 if (previous_barrier) {
984 assert(bool(*previous_barrier));
985 (*previous_barrier)(access);
986 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600987 }
988 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700989 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600990};
991
992// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
993// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
994// *different* map from dest.
995// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
996// range [first, last)
997template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600998static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
999 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -06001000 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -06001001 auto at = entry;
1002 for (auto pos = first; pos != last; ++pos) {
1003 // Every member of the input iterator range must fit within the remaining portion of entry
1004 assert(at->first.includes(pos->first));
1005 assert(at != dest->end());
1006 // Trim up at to the same size as the entry to resolve
1007 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001008 auto access = pos->second; // intentional copy
1009 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -06001010 at->second.Resolve(access);
1011 ++at; // Go to the remaining unused section of entry
1012 }
1013}
1014
John Zulaufa0a98292020-09-18 09:30:10 -06001015static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
1016 SyncBarrier merged = {};
1017 for (const auto &barrier : barriers) {
1018 merged.Merge(barrier);
1019 }
1020 return merged;
1021}
John Zulaufb02c1eb2020-10-06 16:33:36 -06001022template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -07001023void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -06001024 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
1025 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001026 if (!range.non_empty()) return;
1027
John Zulauf355e49b2020-04-24 15:11:15 -06001028 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
1029 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001030 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001031 if (current->pos_B->valid) {
1032 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001033 auto access = src_pos->second; // intentional copy
1034 barrier_action(&access);
John Zulauf16adfc92020-04-08 10:28:33 -06001035 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001036 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1037 trimmed->second.Resolve(access);
1038 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001039 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001040 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001041 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001042 }
John Zulauf16adfc92020-04-08 10:28:33 -06001043 } else {
1044 // we have to descend to fill this gap
1045 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001046 ResourceAccessRange recurrence_range = current_range;
1047 // The current context is empty for the current range, so recur to fill the gap.
1048 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1049 // is not valid, to minimize that recurrence
1050 if (current->pos_B.at_end()) {
1051 // Do the remainder here....
1052 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001053 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001054 // Recur only over the range until B becomes valid (within the limits of range).
1055 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001056 }
John Zulauf22aefed2021-03-11 18:14:35 -07001057 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1058
John Zulauf355e49b2020-04-24 15:11:15 -06001059 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1060 // iterator of the outer while.
1061
1062 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1063 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1064 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001065 const auto seek_to = recurrence_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
locke-lunarg88dbb542020-06-23 22:05:42 -06001066 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001067 current.seek(seek_to);
1068 } else if (!current->pos_A->valid && infill_state) {
1069 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1070 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1071 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001072 }
John Zulauf5f13a792020-03-10 07:31:21 -06001073 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001074 if (current->range.non_empty()) {
1075 ++current;
1076 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001077 }
John Zulauf1a224292020-06-30 14:52:13 -06001078
1079 // Infill if range goes passed both the current and resolve map prior contents
1080 if (recur_to_infill && (current->range.end < range.end)) {
1081 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001082 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001083 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001084}
1085
John Zulauf22aefed2021-03-11 18:14:35 -07001086template <typename BarrierAction>
1087void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1088 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1089 const BarrierAction &previous_barrier) const {
1090 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1091 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1092}
1093
John Zulauf43cc7462020-12-03 12:33:12 -07001094void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001095 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1096 const ResourceAccessStateFunction *previous_barrier) const {
1097 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001098 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001099 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1100 ResourceAccessState state_copy;
1101 if (previous_barrier) {
1102 assert(bool(*previous_barrier));
1103 state_copy = *infill_state;
1104 (*previous_barrier)(&state_copy);
1105 infill_state = &state_copy;
1106 }
1107 sparse_container::update_range_value(*descent_map, range, *infill_state,
1108 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001109 }
1110 } else {
1111 // Look for something to fill the gap further along.
1112 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001113 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001114 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001115 }
John Zulauf5f13a792020-03-10 07:31:21 -06001116 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001117}
1118
John Zulauf4a6105a2020-11-17 15:11:05 -07001119// Non-lazy import of all accesses, WaitEvents needs this.
1120void AccessContext::ResolvePreviousAccesses() {
1121 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001122 if (!prev_.size()) return; // If no previous contexts, nothing to do
1123
John Zulauf4a6105a2020-11-17 15:11:05 -07001124 for (const auto address_type : kAddressTypes) {
1125 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1126 }
1127}
1128
John Zulauf43cc7462020-12-03 12:33:12 -07001129AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1130 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001131}
1132
John Zulauf1507ee42020-05-18 11:33:09 -06001133static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001134 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1135 ? SYNC_ACCESS_INDEX_NONE
1136 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1137 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001138 return stage_access;
1139}
1140static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001141 const auto stage_access =
1142 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1143 ? SYNC_ACCESS_INDEX_NONE
1144 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1145 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001146 return stage_access;
1147}
1148
John Zulauf7635de32020-05-29 17:14:15 -06001149// Caller must manage returned pointer
1150static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001151 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001152 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001153 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1154 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001155 return proxy;
1156}
1157
John Zulaufb02c1eb2020-10-06 16:33:36 -06001158template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001159void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1160 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1161 const ResourceAccessState *infill_state) const {
1162 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1163 if (!attachment_gen) return;
1164
1165 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1166 const AccessAddressType address_type = view_gen.GetAddressType();
1167 for (; range_gen->non_empty(); ++range_gen) {
1168 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001169 }
John Zulauf62f10592020-04-03 12:20:02 -06001170}
1171
John Zulauf1d5f9c12022-05-13 14:51:08 -06001172template <typename ResolveOp>
1173void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1174 const ResourceAccessState *infill_state, bool recur_to_infill) {
1175 for (auto address_type : kAddressTypes) {
1176 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1177 recur_to_infill);
1178 }
1179}
1180
John Zulauf7635de32020-05-29 17:14:15 -06001181// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001182bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001183 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001184 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001185 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001186 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1187 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1188 // those affects have not been recorded yet.
1189 //
1190 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1191 // to apply and only copy then, if this proves a hot spot.
1192 std::unique_ptr<AccessContext> proxy_for_prev;
1193 TrackBack proxy_track_back;
1194
John Zulauf355e49b2020-04-24 15:11:15 -06001195 const auto &transitions = rp_state.subpass_transitions[subpass];
1196 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001197 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1198
1199 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001200 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001201 if (prev_needs_proxy) {
1202 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001203 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001204 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001205 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001206 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001207 }
1208 track_back = &proxy_track_back;
1209 }
1210 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001211 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001212 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001213 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001214 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001215 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1216 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1217 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1218 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1219 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1220 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001221 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001222 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1223 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1224 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1225 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1226 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001227 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001228 }
John Zulauf355e49b2020-04-24 15:11:15 -06001229 }
1230 }
1231 return skip;
1232}
1233
John Zulaufbb890452021-12-14 11:30:18 -07001234bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001235 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001236 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001237 bool skip = false;
1238 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001239
John Zulauf1507ee42020-05-18 11:33:09 -06001240 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1241 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001242 const auto &view_gen = attachment_views[i];
1243 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001244 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001245
1246 // Need check in the following way
1247 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1248 // vs. transition
1249 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1250 // for each aspect loaded.
1251
1252 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001253 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001254 const bool is_color = !(has_depth || has_stencil);
1255
1256 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001257 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001258
John Zulaufaff20662020-06-01 14:07:58 -06001259 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001260 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001261
John Zulaufb02c1eb2020-10-06 16:33:36 -06001262 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001263 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001264 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001265 aspect = "color";
1266 } else {
John Zulauf57261402021-08-13 11:32:06 -06001267 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001268 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1269 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001270 aspect = "depth";
1271 }
John Zulauf57261402021-08-13 11:32:06 -06001272 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001273 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1274 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001275 aspect = "stencil";
1276 checked_stencil = true;
1277 }
1278 }
1279
1280 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001281 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001282 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001283 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001284 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001285 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001286 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001287 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1288 " aspect %s during load with loadOp %s.",
1289 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1290 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001291 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001292 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001293 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001294 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001295 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001296 }
1297 }
1298 }
1299 }
1300 return skip;
1301}
1302
John Zulaufaff20662020-06-01 14:07:58 -06001303// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1304// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1305// store is part of the same Next/End operation.
1306// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001307bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001308 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001309 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001310 bool skip = false;
1311 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001312
1313 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1314 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001315 const AttachmentViewGen &view_gen = attachment_views[i];
1316 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001317 const auto &ci = attachment_ci[i];
1318
1319 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1320 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1321 // sake, we treat DONT_CARE as writing.
1322 const bool has_depth = FormatHasDepth(ci.format);
1323 const bool has_stencil = FormatHasStencil(ci.format);
1324 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001325 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001326 if (!has_stencil && !store_op_stores) continue;
1327
1328 HazardResult hazard;
1329 const char *aspect = nullptr;
1330 bool checked_stencil = false;
1331 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001332 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1333 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001334 aspect = "color";
1335 } else {
John Zulauf57261402021-08-13 11:32:06 -06001336 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001337 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001338 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1339 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001340 aspect = "depth";
1341 }
1342 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001343 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1344 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001345 aspect = "stencil";
1346 checked_stencil = true;
1347 }
1348 }
1349
1350 if (hazard.hazard) {
1351 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1352 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001353 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1354 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1355 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001356 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1357 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001358 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001359 }
1360 }
1361 }
1362 return skip;
1363}
1364
John Zulaufbb890452021-12-14 11:30:18 -07001365bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001366 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001367 CMD_TYPE cmd_type, uint32_t subpass) const {
1368 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001369 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001370 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001371}
1372
John Zulauf06f6f1e2022-04-19 15:28:11 -06001373void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1374
John Zulauf3d84f1b2020-03-09 13:33:25 -06001375class HazardDetector {
1376 SyncStageAccessIndex usage_index_;
1377
1378 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001379 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001380 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001381 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001382 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001383 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001384};
1385
John Zulauf69133422020-05-20 14:55:53 -06001386class HazardDetectorWithOrdering {
1387 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001388 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001389
1390 public:
1391 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001392 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001393 }
John Zulauf14940722021-04-12 15:19:02 -06001394 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001395 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001396 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001397 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001398};
1399
John Zulauf16adfc92020-04-08 10:28:33 -06001400HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001401 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001402 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001403 const auto base_address = ResourceBaseAddress(buffer);
1404 HazardDetector detector(usage_index);
1405 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001406}
1407
John Zulauf69133422020-05-20 14:55:53 -06001408template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001409HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1410 DetectOptions options) const {
1411 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1412 if (!attachment_gen) return HazardResult();
1413
1414 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1415 const auto address_type = view_gen.GetAddressType();
1416 for (; range_gen->non_empty(); ++range_gen) {
1417 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1418 if (hazard.hazard) return hazard;
1419 }
1420
1421 return HazardResult();
1422}
1423
1424template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001425HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1426 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001427 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001428 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001429 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001430 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001431 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001432 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001433 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001434 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001435 if (hazard.hazard) return hazard;
1436 }
1437 return HazardResult();
1438}
John Zulauf110413c2021-03-20 05:38:38 -06001439template <typename Detector>
1440HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001441 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1442 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001443 if (!SimpleBinding(image)) return HazardResult();
1444 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001445 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1446 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001447 const auto address_type = ImageAddressType(image);
1448 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001449 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1450 if (hazard.hazard) return hazard;
1451 }
1452 return HazardResult();
1453}
John Zulauf69133422020-05-20 14:55:53 -06001454
John Zulauf540266b2020-04-06 18:54:53 -06001455HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1456 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001457 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001458 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1459 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001460 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001461 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001462}
1463
1464HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001465 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001466 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001467 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001468}
1469
John Zulaufd0ec59f2021-03-13 14:25:08 -07001470HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1471 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1472 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1473 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1474}
1475
John Zulauf69133422020-05-20 14:55:53 -06001476HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001477 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001478 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001479 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001480 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001481}
1482
John Zulauf3d84f1b2020-03-09 13:33:25 -06001483class BarrierHazardDetector {
1484 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001485 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001486 SyncStageAccessFlags src_access_scope)
1487 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1488
John Zulauf5f13a792020-03-10 07:31:21 -06001489 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001490 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001491 }
John Zulauf14940722021-04-12 15:19:02 -06001492 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001493 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001494 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001495 }
1496
1497 private:
1498 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001499 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001500 SyncStageAccessFlags src_access_scope_;
1501};
1502
John Zulauf4a6105a2020-11-17 15:11:05 -07001503class EventBarrierHazardDetector {
1504 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001505 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001506 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001507 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001508 : usage_index_(usage_index),
1509 src_exec_scope_(src_exec_scope),
1510 src_access_scope_(src_access_scope),
1511 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001512 scope_queue_id_(queue_id),
1513 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001514 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001515 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001516
John Zulaufe0757ba2022-06-10 16:51:45 -06001517 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1518 // Need to piece together coverage of pos->first range:
1519 // Copy the range as we'll be chopping it up as needed
1520 ResourceAccessRange range = pos->first;
1521 const ResourceAccessState &access = pos->second;
1522 HazardResult hazard;
1523
1524 bool in_scope = AdvanceScope(range);
1525 bool unscoped_tested = false;
1526 while (in_scope && !hazard.IsHazard()) {
1527 if (range.begin < ScopeBegin()) {
1528 if (!unscoped_tested) {
1529 unscoped_tested = true;
1530 hazard = access.DetectHazard(usage_index_);
1531 }
1532 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1533 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1534 range.begin = ScopeBegin();
1535 } else { // in_scope implied that ScopeRange and range intersect
1536 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1537 scope_tag_);
1538 if (!hazard.IsHazard()) {
1539 range.begin = ScopeEnd();
1540 in_scope = AdvanceScope(range); // contains a non_empty check
1541 }
1542 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001543 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001544 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1545 hazard = access.DetectHazard(usage_index_);
1546 }
1547 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001548 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001549
John Zulauf14940722021-04-12 15:19:02 -06001550 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001551 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1552 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1553 }
1554
1555 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001556 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1557 bool ScopeValid() const { return !ScopeInvalid(); }
1558 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1559
1560 // Hiding away the std::pair grunge...
1561 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1562 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1563 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1564 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1565
1566 bool AdvanceScope(const ResourceAccessRange &range) {
1567 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1568 if (!range.non_empty()) return false;
1569 if (ScopeInvalid()) return false;
1570
1571 if (ScopeRange().strictly_less(range)) {
1572 ScopeSeek(range);
1573 }
1574
1575 return ScopeValid() && ScopeRange().intersects(range);
1576 }
1577
John Zulauf4a6105a2020-11-17 15:11:05 -07001578 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001579 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001580 SyncStageAccessFlags src_access_scope_;
1581 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001582 QueueId scope_queue_id_;
1583 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001584 SyncEventState::ScopeMap::const_iterator scope_pos_;
1585 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001586};
1587
John Zulaufe0757ba2022-06-10 16:51:45 -06001588HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1589 VkPipelineStageFlags2KHR src_exec_scope,
1590 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1591 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001592 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1593 // first access scope map to use, and there's no easy way to plumb it in below.
1594 const auto address_type = ImageAddressType(image);
1595 const auto &event_scope = sync_event.FirstScope(address_type);
1596
1597 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001598 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001599 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001600}
1601
John Zulaufd0ec59f2021-03-13 14:25:08 -07001602HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1603 DetectOptions options) const {
1604 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1605 barrier.src_access_scope);
1606 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1607}
1608
Jeremy Gebben40a22942020-12-22 14:22:06 -07001609HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001610 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001611 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001612 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001613 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001614 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001615}
1616
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001617HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001618 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001619 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001620}
John Zulauf355e49b2020-04-24 15:11:15 -06001621
John Zulauf9cb530d2019-09-30 14:14:10 -06001622template <typename Flags, typename Map>
1623SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1624 SyncStageAccessFlags scope = 0;
1625 for (const auto &bit_scope : map) {
1626 if (flag_mask < bit_scope.first) break;
1627
1628 if (flag_mask & bit_scope.first) {
1629 scope |= bit_scope.second;
1630 }
1631 }
1632 return scope;
1633}
1634
Jeremy Gebben40a22942020-12-22 14:22:06 -07001635SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001636 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1637}
1638
Jeremy Gebben40a22942020-12-22 14:22:06 -07001639SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1640 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001641}
1642
Jeremy Gebben40a22942020-12-22 14:22:06 -07001643// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1644SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001645 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1646 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1647 // of the union of all stage/access types for all the stages and the same unions for the access mask...
John Zulauf9cb530d2019-09-30 14:14:10 -06001648 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1649}
1650
1651template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001652void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001653 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1654 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001655 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001656 auto pos = accesses->lower_bound(range);
1657 if (pos == accesses->end() || !pos->first.intersects(range)) {
1658 // The range is empty, fill it with a default value.
1659 pos = action.Infill(accesses, pos, range);
1660 } else if (range.begin < pos->first.begin) {
1661 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001662 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001663 } else if (pos->first.begin < range.begin) {
1664 // Trim the beginning if needed
1665 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1666 ++pos;
1667 }
1668
1669 const auto the_end = accesses->end();
1670 while ((pos != the_end) && pos->first.intersects(range)) {
1671 if (pos->first.end > range.end) {
1672 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1673 }
1674
1675 pos = action(accesses, pos);
1676 if (pos == the_end) break;
1677
1678 auto next = pos;
1679 ++next;
1680 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1681 // Need to infill if next is disjoint
1682 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001683 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001684 next = action.Infill(accesses, next, new_range);
1685 }
1686 pos = next;
1687 }
1688}
John Zulaufd5115702021-01-18 12:34:33 -07001689
1690// Give a comparable interface for range generators and ranges
1691template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001692void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001693 assert(range);
1694 UpdateMemoryAccessState(accesses, *range, action);
1695}
1696
John Zulauf4a6105a2020-11-17 15:11:05 -07001697template <typename Action, typename RangeGen>
1698void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1699 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001700 RangeGen &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
John Zulauf4a6105a2020-11-17 15:11:05 -07001701 for (; range_gen->non_empty(); ++range_gen) {
1702 UpdateMemoryAccessState(accesses, *range_gen, action);
1703 }
1704}
John Zulauf9cb530d2019-09-30 14:14:10 -06001705
John Zulaufd0ec59f2021-03-13 14:25:08 -07001706template <typename Action, typename RangeGen>
1707void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1708 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1709 for (; range_gen->non_empty(); ++range_gen) {
1710 UpdateMemoryAccessState(accesses, *range_gen, action);
1711 }
1712}
John Zulauf9cb530d2019-09-30 14:14:10 -06001713struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001714 using Iterator = ResourceAccessRangeMap::iterator;
1715 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001716 // this is only called on gaps, and never returns a gap.
1717 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001718 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001719 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001720 }
John Zulauf5f13a792020-03-10 07:31:21 -06001721
John Zulauf5c5e88d2019-12-26 11:22:02 -07001722 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001723 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001724 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001725 return pos;
1726 }
1727
John Zulauf43cc7462020-12-03 12:33:12 -07001728 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001729 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001730 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001731 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001732 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001733 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001734 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001735 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001736};
1737
John Zulauf4a6105a2020-11-17 15:11:05 -07001738// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001739struct PipelineBarrierOp {
1740 SyncBarrier barrier;
1741 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001742 ResourceAccessState::QueueScopeOps scope;
1743 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
John Zulauff26fca92022-08-15 11:53:34 -06001744 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {
1745 if (queue_id != QueueSyncState::kQueueIdInvalid) {
1746 // This is a submit time application... supress layout transitions to not taint the QueueBatchContext write state
1747 layout_transition = false;
1748 }
1749 }
John Zulaufd5115702021-01-18 12:34:33 -07001750 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001751 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001752};
John Zulauf00119522022-05-23 19:07:42 -06001753
John Zulaufecf4ac52022-06-06 10:08:42 -06001754// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1755struct BatchBarrierOp : public PipelineBarrierOp {
1756 void operator()(ResourceAccessState *access_state) const {
1757 access_state->ApplyBarrier(scope, barrier, layout_transition);
1758 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1759 }
1760 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1761};
1762
John Zulauf4a6105a2020-11-17 15:11:05 -07001763// The barrier operation for wait events
1764struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001765 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001766 SyncBarrier barrier;
1767 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001768
1769 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001770 bool layout_transition_)
John Zulauff26fca92022-08-15 11:53:34 -06001771 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {
1772 if (scope_queue_ != QueueSyncState::kQueueIdInvalid) {
1773 // This is a submit time application... supress layout transitions to not taint the QueueBatchContext write state
1774 layout_transition = false;
1775 }
1776 }
John Zulaufb7578302022-05-19 13:50:18 -06001777 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001778};
John Zulauf1e331ec2020-12-04 18:29:38 -07001779
John Zulauf4a6105a2020-11-17 15:11:05 -07001780// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1781// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1782// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001783template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001784class ApplyBarrierOpsFunctor {
1785 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001786 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001787 // Only called with a gap, and pos at the lower_bound(range)
1788 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1789 if (!infill_default_) {
1790 return pos;
1791 }
1792 ResourceAccessState default_state;
1793 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1794 return inserted;
1795 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001796
John Zulauf5c628d02021-05-04 15:46:36 -06001797 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001798 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001799 for (const auto &op : barrier_ops_) {
1800 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001801 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001802
John Zulauf89311b42020-09-29 16:28:47 -06001803 if (resolve_) {
1804 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1805 // another walk
1806 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001807 }
1808 return pos;
1809 }
1810
John Zulauf89311b42020-09-29 16:28:47 -06001811 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001812 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1813 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001814 barrier_ops_.reserve(size_hint);
1815 }
John Zulauf5c628d02021-05-04 15:46:36 -06001816 void EmplaceBack(const BarrierOp &op) {
1817 barrier_ops_.emplace_back(op);
1818 infill_default_ |= op.layout_transition;
1819 }
John Zulauf89311b42020-09-29 16:28:47 -06001820
1821 private:
1822 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001823 bool infill_default_;
1824 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001825 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001826};
1827
John Zulauf4a6105a2020-11-17 15:11:05 -07001828// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1829// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1830template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001831class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1832 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1833
John Zulauf4a6105a2020-11-17 15:11:05 -07001834 public:
John Zulaufee984022022-04-13 16:39:50 -06001835 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001836};
1837
John Zulauf1e331ec2020-12-04 18:29:38 -07001838// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001839class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1840 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1841
John Zulauf1e331ec2020-12-04 18:29:38 -07001842 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001843 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001844};
1845
John Zulauf8e3c3e92021-01-06 11:19:36 -07001846void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001847 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001848 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001849 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001850}
1851
John Zulauf8e3c3e92021-01-06 11:19:36 -07001852void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001853 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001854 if (!SimpleBinding(buffer)) return;
1855 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001856 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001857}
John Zulauf355e49b2020-04-24 15:11:15 -06001858
John Zulauf8e3c3e92021-01-06 11:19:36 -07001859void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001860 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1861 if (!SimpleBinding(image)) return;
1862 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001863 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001864 const auto address_type = ImageAddressType(image);
1865 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1866 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1867}
1868void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001869 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001870 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001871 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001872 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001873 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001874 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001875 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001876 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001877 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001878}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001879
1880void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001881 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001882 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1883 if (!gen) return;
1884 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1885 const auto address_type = view_gen.GetAddressType();
1886 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1887 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001888}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001889
John Zulauf8e3c3e92021-01-06 11:19:36 -07001890void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001891 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001892 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001893 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1894 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001895 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001896}
1897
John Zulaufd0ec59f2021-03-13 14:25:08 -07001898template <typename Action, typename RangeGen>
1899void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1900 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1901 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001902}
1903
1904template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001905void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1906 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1907 if (!gen) return;
1908 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001909}
1910
John Zulaufd0ec59f2021-03-13 14:25:08 -07001911void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1912 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001913 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001914 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001915 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001916}
1917
John Zulaufd0ec59f2021-03-13 14:25:08 -07001918void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001919 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001920 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001921
1922 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1923 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001924 const auto &view_gen = attachment_views[i];
1925 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001926
1927 const auto &ci = attachment_ci[i];
1928 const bool has_depth = FormatHasDepth(ci.format);
1929 const bool has_stencil = FormatHasStencil(ci.format);
1930 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001931 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001932
1933 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001934 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1935 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001936 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001937 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001938 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1939 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001940 }
John Zulauf57261402021-08-13 11:32:06 -06001941 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001942 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001943 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1944 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001945 }
1946 }
1947 }
1948 }
1949}
1950
John Zulauf540266b2020-04-06 18:54:53 -06001951template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001952void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001953 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001954 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001955 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001956 }
1957}
1958
1959void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001960 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1961 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001962 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001963 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001964 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001965 }
1966 }
1967}
1968
John Zulauf4fa68462021-04-26 21:04:22 -06001969// Caller must ensure that lifespan of this is less than from
1970void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1971
John Zulauf355e49b2020-04-24 15:11:15 -06001972// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001973HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1974 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001975
John Zulauf355e49b2020-04-24 15:11:15 -06001976 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001977 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001978
1979 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001980 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1981 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001982 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001983 if (!hazard.hazard) {
1984 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001985 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001986 }
John Zulaufa0a98292020-09-18 09:30:10 -06001987
John Zulauf355e49b2020-04-24 15:11:15 -06001988 return hazard;
1989}
1990
John Zulaufb02c1eb2020-10-06 16:33:36 -06001991void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001992 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001993 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001994 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001995 for (const auto &transition : transitions) {
1996 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001997 const auto &view_gen = attachment_views[transition.attachment];
1998 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001999
2000 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
2001 assert(trackback);
2002
2003 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07002004 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002005 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002006 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06002007 auto &target_map = GetAccessStateMap(address_type);
2008 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002009 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
2010 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002011 }
2012
John Zulauf86356ca2020-10-19 11:46:41 -06002013 // If there were no transitions skip this global map walk
2014 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07002015 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07002016 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06002017 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06002018}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002019
sjfricke0bea06e2022-06-05 09:22:26 +09002020bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002021 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002022 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002023 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002024 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002025 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002026 return skip;
2027 }
sjfricke0bea06e2022-06-05 09:22:26 +09002028 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002029
2030 using DescriptorClass = cvdescriptorset::DescriptorClass;
2031 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2032 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002033 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2034
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002035 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002036 const auto raster_state = pipe->RasterizationState();
2037 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002038 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002039 }
locke-lunarg61870c22020-06-09 14:51:50 -06002040 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002041 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002042 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2043 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002044 SyncStageAccessIndex sync_index =
2045 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2046
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002047 for (uint32_t index = 0; index < binding->count; index++) {
2048 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002049 switch (descriptor->GetClass()) {
2050 case DescriptorClass::ImageSampler:
2051 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002052 if (descriptor->Invalid()) {
2053 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002054 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002055
2056 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2057 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2058 const auto *img_view_state = image_descriptor->GetImageViewState();
2059 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2060
John Zulauf361fb532020-07-22 10:45:39 -06002061 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002062 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2063 // Descriptors, so we do not have to worry about depth slicing here.
2064 // See: VUID 00343
2065 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002066 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002067 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002068
2069 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2070 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2071 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002072 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002073 hazard =
2074 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2075 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002076 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002077 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2078 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002079 }
John Zulauf110413c2021-03-20 05:38:38 -06002080
John Zulauf33fc1d52020-07-17 11:01:10 -06002081 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002082 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002083 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002084 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2085 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002086 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002087 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2088 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2089 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002090 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2091 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002092 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002093 }
2094 break;
2095 }
2096 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002097 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2098 if (texel_descriptor->Invalid()) {
2099 continue;
2100 }
2101 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2102 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002103 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002104 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002105 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002106 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002107 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002108 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002109 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002110 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2111 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2112 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002113 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002114 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002115 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002116 }
2117 break;
2118 }
2119 case DescriptorClass::GeneralBuffer: {
2120 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002121 if (buffer_descriptor->Invalid()) {
2122 continue;
2123 }
2124 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002125 const ResourceAccessRange range =
2126 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002127 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002128 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002129 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002130 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002131 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002132 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002133 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2134 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2135 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002136 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002137 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002138 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002139 }
2140 break;
2141 }
2142 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2143 default:
2144 break;
2145 }
2146 }
2147 }
2148 }
2149 return skip;
2150}
2151
2152void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002153 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002154 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002155 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002156 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002157 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002158 return;
2159 }
2160
2161 using DescriptorClass = cvdescriptorset::DescriptorClass;
2162 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2163 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002164 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2165
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002166 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002167 const auto raster_state = pipe->RasterizationState();
2168 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002169 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002170 }
locke-lunarg61870c22020-06-09 14:51:50 -06002171 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002172 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002173 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2174 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002175 SyncStageAccessIndex sync_index =
2176 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2177
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002178 for (uint32_t i = 0; i < binding->count; i++) {
2179 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002180 switch (descriptor->GetClass()) {
2181 case DescriptorClass::ImageSampler:
2182 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002183 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2184 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2185 if (image_descriptor->Invalid()) {
2186 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002187 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002188 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002189 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2190 // Descriptors, so we do not have to worry about depth slicing here.
2191 // See: VUID 00343
2192 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002193 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002194 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002195 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2196 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2197 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2198 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002199 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002200 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2201 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002202 }
locke-lunarg61870c22020-06-09 14:51:50 -06002203 break;
2204 }
2205 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002206 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2207 if (texel_descriptor->Invalid()) {
2208 continue;
2209 }
2210 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2211 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002212 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002213 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002214 break;
2215 }
2216 case DescriptorClass::GeneralBuffer: {
2217 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002218 if (buffer_descriptor->Invalid()) {
2219 continue;
2220 }
2221 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002222 const ResourceAccessRange range =
2223 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002224 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002225 break;
2226 }
2227 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2228 default:
2229 break;
2230 }
2231 }
2232 }
2233 }
2234}
2235
sjfricke0bea06e2022-06-05 09:22:26 +09002236bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002237 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002238 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002239 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002240 return skip;
2241 }
2242
2243 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2244 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002245 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002246
2247 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002248 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002249 if (binding_description.binding < binding_buffers_size) {
2250 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002251 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002252
locke-lunarg1ae57d62020-11-18 10:49:19 -07002253 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002254 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2255 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002256 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002257 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002258 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002259 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002260 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002261 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2262 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002263 }
2264 }
2265 }
2266 return skip;
2267}
2268
John Zulauf14940722021-04-12 15:19:02 -06002269void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002270 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002271 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002272 return;
2273 }
2274 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2275 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002276 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002277
2278 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002279 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002280 if (binding_description.binding < binding_buffers_size) {
2281 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002282 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002283
locke-lunarg1ae57d62020-11-18 10:49:19 -07002284 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002285 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2286 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002287 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2288 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002289 }
2290 }
2291}
2292
sjfricke0bea06e2022-06-05 09:22:26 +09002293bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002294 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002295 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002296 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002297 }
locke-lunarg61870c22020-06-09 14:51:50 -06002298
locke-lunarg1ae57d62020-11-18 10:49:19 -07002299 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002300 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002301 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2302 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002303 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002304 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002305 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002306 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002307 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2308 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002309 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002310 }
2311
2312 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2313 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002314 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002315 return skip;
2316}
2317
John Zulauf14940722021-04-12 15:19:02 -06002318void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002319 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) return;
locke-lunarg61870c22020-06-09 14:51:50 -06002320
locke-lunarg1ae57d62020-11-18 10:49:19 -07002321 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002322 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002323 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2324 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002325 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002326
2327 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2328 // We will detect more accurate range in the future.
2329 RecordDrawVertex(UINT32_MAX, 0, tag);
2330}
2331
sjfricke0bea06e2022-06-05 09:22:26 +09002332bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002333 bool skip = false;
2334 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002335 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002336 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002337}
2338
John Zulauf14940722021-04-12 15:19:02 -06002339void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002340 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002341 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002342 }
locke-lunarg61870c22020-06-09 14:51:50 -06002343}
2344
John Zulauf00119522022-05-23 19:07:42 -06002345QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2346
sjfricke0bea06e2022-06-05 09:22:26 +09002347ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002348 const VkRect2D &render_area,
2349 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002350 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002351 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2352 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulaufab84f242022-08-04 18:38:40 -06002353 render_pass_contexts_.emplace_back(layer_data::make_unique<RenderPassAccessContext>(rp_state, render_area, GetQueueFlags(),
2354 attachment_views, &cb_access_context_));
2355 current_renderpass_context_ = render_pass_contexts_.back().get();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002356 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002357 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002358 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002359}
2360
sjfricke0bea06e2022-06-05 09:22:26 +09002361ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002362 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002363 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002364
sjfricke0bea06e2022-06-05 09:22:26 +09002365 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2366 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2367 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002368
2369 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002370 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002371 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002372}
2373
sjfricke0bea06e2022-06-05 09:22:26 +09002374ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002375 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002376 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002377
sjfricke0bea06e2022-06-05 09:22:26 +09002378 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2379 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002380
2381 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002382 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002383 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002384 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002385}
2386
John Zulauf4a6105a2020-11-17 15:11:05 -07002387void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2388 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002389 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002390 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002391 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002392 }
2393}
2394
John Zulaufae842002021-04-15 18:20:55 -06002395// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002396bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002397 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002398 if (!exec_context.ValidForSyncOps()) return false;
2399
2400 const QueueId queue_id = exec_context.GetQueueId();
2401 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002402 bool skip = false;
2403 ResourceUsageRange tag_range = {0, 0};
2404 const AccessContext *recorded_context = GetCurrentAccessContext();
2405 assert(recorded_context);
2406 HazardResult hazard;
John Zulaufdab327f2022-07-08 12:02:05 -06002407 ReplayGuard replay_guard(exec_context, *this);
2408
John Zulaufbb890452021-12-14 11:30:18 -07002409 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002410 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002411 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002412 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002413 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002414 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002415 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2416 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002417 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002418 };
2419 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002420 // we update the range to any include layout transition first use writes,
2421 // as they are stored along with the source scope (as effective barrier) when recorded
2422 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002423 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002424
John Zulauf0223f142022-07-06 09:05:39 -06002425 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2426 // we need to fetch the current access context each time
John Zulaufdab327f2022-07-08 12:02:05 -06002427 hazard = exec_context.DetectFirstUseHazard(tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002428 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002429 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002430 }
2431 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002432 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002433 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002434 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002435 }
2436
2437 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002438 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002439 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002440 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002441 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002442 }
2443
2444 return skip;
2445}
2446
sjfricke0bea06e2022-06-05 09:22:26 +09002447void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002448 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2449 assert(recorded_context);
2450
2451 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2452 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002453 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002454 // we update the range to any include layout transition first use writes,
2455 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002456 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002457 }
2458
2459 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2460 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002461 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002462}
2463
John Zulauf1d5f9c12022-05-13 14:51:08 -06002464void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002465 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002466 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002467}
2468
John Zulaufdab327f2022-07-08 12:02:05 -06002469HazardResult CommandBufferAccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
2470 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, *GetCurrentAccessContext());
2471}
2472
John Zulauf3c788ef2022-02-22 12:12:30 -07002473ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002474 // The execution references ensure lifespan for the referenced child CB's...
2475 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002476 InsertRecordedAccessLogEntries(recorded_context);
2477 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002478 return tag_range;
2479}
2480
John Zulauf3c788ef2022-02-22 12:12:30 -07002481void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2482 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2483 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2484}
2485
John Zulauf41a9c7c2021-12-07 15:59:53 -07002486ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2487 ResourceUsageTag next = access_log_.size();
2488 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2489 return next;
2490}
2491
2492ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2493 command_number_++;
2494 subcommand_number_ = 0;
2495 ResourceUsageTag next = access_log_.size();
2496 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2497 return next;
2498}
2499
2500ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2501 if (index == 0) {
2502 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2503 }
2504 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2505}
2506
John Zulaufbb890452021-12-14 11:30:18 -07002507void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2508 auto tag = sync_op->Record(this);
2509 // As renderpass operations can have side effects on the command buffer access context,
2510 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002511 sync_ops_.emplace_back(tag, std::move(sync_op));
2512}
2513
John Zulaufae842002021-04-15 18:20:55 -06002514class HazardDetectFirstUse {
2515 public:
John Zulauf0223f142022-07-06 09:05:39 -06002516 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2517 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002518 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002519 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002520 }
2521 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2522 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2523 }
2524
2525 private:
2526 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002527 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002528 const ResourceUsageRange &tag_range_;
2529};
2530
2531// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2532// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002533HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002534 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002535 HazardResult hazard;
2536 for (const auto address_type : kAddressTypes) {
2537 const auto &recorded_access_map = GetAccessStateMap(address_type);
2538 for (const auto &recorded_access : recorded_access_map) {
2539 // Cull any entries not in the current tag range
2540 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002541 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002542 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2543 if (hazard.hazard) break;
2544 }
2545 }
2546
2547 return hazard;
2548}
2549
John Zulaufbb890452021-12-14 11:30:18 -07002550bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002551 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002552 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002553 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002554 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002555 if (!pipe) {
2556 return skip;
2557 }
2558
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002559 const auto raster_state = pipe->RasterizationState();
2560 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002561 return skip;
2562 }
sjfricke0bea06e2022-06-05 09:22:26 +09002563 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002564 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002565 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002566
John Zulauf1a224292020-06-30 14:52:13 -06002567 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002568 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002569 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2570 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002571 if (location >= subpass.colorAttachmentCount ||
2572 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002573 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002574 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002575 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2576 if (!view_gen.IsValid()) continue;
2577 HazardResult hazard =
2578 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2579 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002580 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002581 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002582 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002583 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002584 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002585 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002586 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2587 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002588 }
2589 }
2590 }
locke-lunarg37047832020-06-12 13:44:45 -06002591
2592 // PHASE1 TODO: Add layout based read/vs. write selection.
2593 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002594 const auto ds_state = pipe->DepthStencilState();
2595 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002596
2597 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2598 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2599 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002600 bool depth_write = false, stencil_write = false;
2601
2602 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002603 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002604 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2605 depth_write = true;
2606 }
2607 // PHASE1 TODO: It needs to check if stencil is writable.
2608 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2609 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2610 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002611 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002612 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2613 stencil_write = true;
2614 }
2615
2616 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2617 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002618 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2619 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2620 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002621 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002622 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002623 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002624 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002625 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002626 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002627 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002628 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002629 }
2630 }
2631 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002632 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2633 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2634 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002635 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002636 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002637 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002638 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002639 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002640 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002641 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002642 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002643 }
locke-lunarg61870c22020-06-09 14:51:50 -06002644 }
2645 }
2646 return skip;
2647}
2648
sjfricke0bea06e2022-06-05 09:22:26 +09002649void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2650 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002651 if (!pipe) {
2652 return;
2653 }
2654
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002655 const auto *raster_state = pipe->RasterizationState();
2656 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002657 return;
2658 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002659 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002660 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002661
John Zulauf1a224292020-06-30 14:52:13 -06002662 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002663 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002664 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2665 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002666 if (location >= subpass.colorAttachmentCount ||
2667 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002668 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002669 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002670 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2671 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2672 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2673 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002674 }
2675 }
locke-lunarg37047832020-06-12 13:44:45 -06002676
2677 // PHASE1 TODO: Add layout based read/vs. write selection.
2678 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002679 const auto *ds_state = pipe->DepthStencilState();
2680 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002681 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2682 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2683 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002684 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002685 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2686 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002687
2688 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002689 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2690 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002691 depth_write = true;
2692 }
2693 // PHASE1 TODO: It needs to check if stencil is writable.
2694 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2695 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2696 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002697 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002698 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2699 stencil_write = true;
2700 }
2701
John Zulaufd0ec59f2021-03-13 14:25:08 -07002702 if (depth_write || stencil_write) {
2703 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2704 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2705 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2706 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002707 }
locke-lunarg61870c22020-06-09 14:51:50 -06002708 }
2709}
2710
sjfricke0bea06e2022-06-05 09:22:26 +09002711bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002712 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002713 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002714 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002715 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002716 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002717 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002718
John Zulauf355e49b2020-04-24 15:11:15 -06002719 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002720 if (next_subpass >= subpass_contexts_.size()) {
2721 return skip;
2722 }
John Zulauf1507ee42020-05-18 11:33:09 -06002723 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002724 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002725 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002726 if (!skip) {
2727 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2728 // on a copy of the (empty) next context.
2729 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2730 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002731 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002732 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002733 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002734 }
John Zulauf7635de32020-05-29 17:14:15 -06002735 return skip;
2736}
sjfricke0bea06e2022-06-05 09:22:26 +09002737bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002738 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002739 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002740 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002741 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002742 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2743 cmd_type);
2744 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002745 return skip;
2746}
2747
John Zulauf64ffe552021-02-06 10:25:07 -07002748AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002749 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002750}
2751
John Zulaufbb890452021-12-14 11:30:18 -07002752bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002753 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002754 bool skip = false;
2755
John Zulauf7635de32020-05-29 17:14:15 -06002756 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2757 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2758 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2759 // to apply and only copy then, if this proves a hot spot.
2760 std::unique_ptr<AccessContext> proxy_for_current;
2761
John Zulauf355e49b2020-04-24 15:11:15 -06002762 // Validate the "finalLayout" transitions to external
2763 // Get them from where there we're hidding in the extra entry.
2764 const auto &final_transitions = rp_state_->subpass_transitions.back();
2765 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002766 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002767 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002768 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2769 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002770
2771 if (transition.prev_pass == current_subpass_) {
2772 if (!proxy_for_current) {
2773 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
John Zulauf64ffe552021-02-06 10:25:07 -07002774 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002775 }
2776 context = proxy_for_current.get();
2777 }
2778
John Zulaufa0a98292020-09-18 09:30:10 -06002779 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2780 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002781 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002782 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002783 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002784 if (hazard.tag == kInvalidTag) {
2785 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002786 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002787 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2788 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2789 " final image layout transition (old_layout: %s, new_layout: %s).",
2790 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2791 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2792 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002793 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002794 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2795 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2796 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2797 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2798 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002799 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002800 }
John Zulauf355e49b2020-04-24 15:11:15 -06002801 }
2802 }
2803 return skip;
2804}
2805
John Zulauf14940722021-04-12 15:19:02 -06002806void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002807 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002808 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002809}
2810
John Zulauf14940722021-04-12 15:19:02 -06002811void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002812 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2813 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002814
2815 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2816 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002817 const AttachmentViewGen &view_gen = attachment_views_[i];
2818 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002819
2820 const auto &ci = attachment_ci[i];
2821 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002822 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002823 const bool is_color = !(has_depth || has_stencil);
2824
2825 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002826 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2827 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2828 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2829 SyncOrdering::kColorAttachment, tag);
2830 }
John Zulauf1507ee42020-05-18 11:33:09 -06002831 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002832 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002833 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2834 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2835 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2836 SyncOrdering::kDepthStencilAttachment, tag);
2837 }
John Zulauf1507ee42020-05-18 11:33:09 -06002838 }
2839 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002840 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2841 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2842 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2843 SyncOrdering::kDepthStencilAttachment, tag);
2844 }
John Zulauf1507ee42020-05-18 11:33:09 -06002845 }
2846 }
2847 }
2848 }
2849}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002850AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2851 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2852 AttachmentViewGenVector view_gens;
2853 VkExtent3D extent = CastTo3D(render_area.extent);
2854 VkOffset3D offset = CastTo3D(render_area.offset);
2855 view_gens.reserve(attachment_views.size());
2856 for (const auto *view : attachment_views) {
2857 view_gens.emplace_back(view, offset, extent);
2858 }
2859 return view_gens;
2860}
John Zulauf64ffe552021-02-06 10:25:07 -07002861RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2862 VkQueueFlags queue_flags,
2863 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2864 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002865 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulaufdab327f2022-07-08 12:02:05 -06002866 // Add this for all subpasses here so that they exist during next subpass validation
2867 InitSubpassContexts(queue_flags, rp_state, external_context, subpass_contexts_);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002868 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002869}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002870void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002871 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002872 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2873 RecordLayoutTransitions(barrier_tag);
2874 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002875}
John Zulauf1507ee42020-05-18 11:33:09 -06002876
John Zulauf41a9c7c2021-12-07 15:59:53 -07002877void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2878 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002879 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002880 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2881 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002882
ziga-lunarg31a3e772022-03-22 11:48:46 +01002883 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2884 return;
2885 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002886 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2887 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002888 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002889 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2890 RecordLayoutTransitions(barrier_tag);
2891 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002892}
2893
John Zulauf41a9c7c2021-12-07 15:59:53 -07002894void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2895 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002896 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002897 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2898 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002899
John Zulauf355e49b2020-04-24 15:11:15 -06002900 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002901 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002902
2903 // Add the "finalLayout" transitions to external
2904 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002905 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2906 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2907 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002908 const auto &final_transitions = rp_state_->subpass_transitions.back();
2909 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002910 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002911 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002912 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002913 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002914 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002915 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002916 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002917 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002918 }
2919}
2920
John Zulauf06f6f1e2022-04-19 15:28:11 -06002921SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2922 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002923 SyncExecScope result;
2924 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002925 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002926 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002927 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002928 return result;
2929}
2930
Jeremy Gebben40a22942020-12-22 14:22:06 -07002931SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002932 SyncExecScope result;
2933 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002934 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2935 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002936 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002937 return result;
2938}
2939
John Zulaufecf4ac52022-06-06 10:08:42 -06002940SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2941 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2942
2943SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2944 : src_exec_scope(src), src_access_scope(src.valid_accesses), dst_exec_scope(dst), dst_access_scope(src.valid_accesses) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002945
2946template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002947SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2948 : src_exec_scope(src),
2949 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2950 dst_exec_scope(dst),
2951 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002952
2953SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002954 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2955 if (barrier) {
2956 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002957 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002958 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002959
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002960 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002961 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002962 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2963
2964 } else {
2965 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002966 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002967 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2968
2969 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002970 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002971 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2972 }
2973}
2974
2975template <typename Barrier>
2976SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2977 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2978 src_exec_scope = src.exec_scope;
2979 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2980
2981 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002982 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002983 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002984}
2985
John Zulaufb02c1eb2020-10-06 16:33:36 -06002986// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2987void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002988 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002989 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002990 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002991 }
2992}
2993
John Zulauf89311b42020-09-29 16:28:47 -06002994// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2995// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2996// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002997void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002998 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002999 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06003000 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06003001 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003002 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06003003 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06003004 }
John Zulaufbb890452021-12-14 11:30:18 -07003005 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06003006}
John Zulauf9cb530d2019-09-30 14:14:10 -06003007HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
3008 HazardResult hazard;
3009 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003010 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06003011 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003012 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06003013 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003014 }
3015 } else {
John Zulauf361fb532020-07-22 10:45:39 -06003016 // Write operation:
3017 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
3018 // If reads exists -- test only against them because either:
3019 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
3020 // * the read weren't hazards, and thus if the write is safe w.r.t. the reads, no hazard vs. last_write is possible if
3021 // the current write happens after the reads, so just test the write against the reades
3022 // Otherwise test against last_write
3023 //
3024 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07003025 if (last_reads.size()) {
3026 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06003027 if (IsReadHazard(usage_stage, read_access)) {
3028 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3029 break;
3030 }
3031 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003032 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06003033 // Write-After-Write check -- if we have a previous write to test against
3034 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003035 }
3036 }
3037 return hazard;
3038}
3039
John Zulaufec943ec2022-06-29 07:52:56 -06003040HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
3041 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07003042 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003043 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003044}
3045
John Zulaufec943ec2022-06-29 07:52:56 -06003046HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3047 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003048 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3049 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003050 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003051 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003052 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003053 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003054 if (IsRead(usage_bit)) {
3055 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3056 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3057 if (is_raw_hazard) {
3058 // NOTE: we know last_write is non-zero
3059 // See if the ordering rules save us from the simple RAW check above
3060 // First check to see if the current usage is covered by the ordering rules
3061 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3062 const bool usage_is_ordered =
3063 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3064 if (usage_is_ordered) {
3065 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003066 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003067 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003068 }
3069 }
John Zulauf4285ee92020-09-23 10:20:52 -06003070 if (is_raw_hazard) {
3071 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3072 }
John Zulauf5c628d02021-05-04 15:46:36 -06003073 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3074 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003075 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003076 } else {
3077 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003078 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003079 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003080 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003081 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003082 if (usage_write_is_ordered) {
3083 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003084 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003085 }
3086 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3087 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003088 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003089 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3090 if (IsReadHazard(usage_stage, read_access)) {
3091 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3092 break;
3093 }
John Zulaufd14743a2020-07-03 09:42:39 -06003094 }
3095 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003096 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3097 bool ilt_ilt_hazard = false;
3098 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3099 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3100 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3101 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3102 }
3103 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003104 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003105 }
John Zulauf69133422020-05-20 14:55:53 -06003106 }
3107 }
3108 return hazard;
3109}
3110
John Zulaufec943ec2022-06-29 07:52:56 -06003111HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3112 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003113 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003114 using Size = FirstAccesses::size_type;
3115 const auto &recorded_accesses = recorded_use.first_accesses_;
3116 Size count = recorded_accesses.size();
3117 if (count) {
3118 const auto &last_access = recorded_accesses.back();
3119 bool do_write_last = IsWrite(last_access.usage_index);
3120 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003121
John Zulauf4fa68462021-04-26 21:04:22 -06003122 for (Size i = 0; i < count; ++count) {
3123 const auto &first = recorded_accesses[i];
3124 // Skip and quit logic
3125 if (first.tag < tag_range.begin) continue;
3126 if (first.tag >= tag_range.end) {
3127 do_write_last = false; // ignore last since we know it can't be in tag_range
3128 break;
3129 }
3130
John Zulaufec943ec2022-06-29 07:52:56 -06003131 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003132 if (hazard.hazard) {
3133 hazard.AddRecordedAccess(first);
3134 break;
3135 }
3136 }
3137
3138 if (do_write_last && tag_range.includes(last_access.tag)) {
3139 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3140 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3141 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3142 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3143 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3144 // the barrier that applies them
3145 barrier |= recorded_use.first_write_layout_ordering_;
3146 }
3147 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3148 // the active context
3149 if (recorded_use.first_read_stages_) {
3150 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3151 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3152 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3153 // active context.
3154 barrier.exec_scope |= recorded_use.first_read_stages_;
3155 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3156 barrier.access_scope |= FlagBit(last_access.usage_index);
3157 }
John Zulaufec943ec2022-06-29 07:52:56 -06003158 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003159 if (hazard.hazard) {
3160 hazard.AddRecordedAccess(last_access);
3161 }
3162 }
John Zulaufae842002021-04-15 18:20:55 -06003163 }
3164 return hazard;
3165}
3166
John Zulauf2f952d22020-02-10 11:34:51 -07003167// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003168HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003169 HazardResult hazard;
3170 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003171 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3172 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3173 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003174 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003175 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003176 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003177 }
3178 } else {
John Zulauf14940722021-04-12 15:19:02 -06003179 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003180 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003181 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003182 // Any reads during the other subpass will conflict with this write, so we need to check them all.
John Zulaufab7756b2020-12-29 16:10:16 -07003183 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003184 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003185 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003186 break;
3187 }
3188 }
John Zulauf2f952d22020-02-10 11:34:51 -07003189 }
3190 }
3191 return hazard;
3192}
3193
John Zulaufae842002021-04-15 18:20:55 -06003194HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3195 ResourceUsageTag start_tag) const {
3196 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003197 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003198 // Skip and quit logic
3199 if (first.tag < tag_range.begin) continue;
3200 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003201
3202 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003203 if (hazard.hazard) {
3204 hazard.AddRecordedAccess(first);
3205 break;
3206 }
John Zulaufae842002021-04-15 18:20:55 -06003207 }
3208 return hazard;
3209}
3210
John Zulaufec943ec2022-06-29 07:52:56 -06003211HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3212 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003213 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003214 // Only supporting image layout transitions for now
3215 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3216 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003217 // only test for WAW if there no intervening read operations.
3218 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003219 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003220 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003221 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003222 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003223 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003224 break;
3225 }
3226 }
John Zulaufec943ec2022-06-29 07:52:56 -06003227 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003228 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3229 }
3230
3231 return hazard;
3232}
3233
John Zulaufe0757ba2022-06-10 16:51:45 -06003234HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3235 VkPipelineStageFlags2KHR src_exec_scope,
3236 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3237 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003238 // Only supporting image layout transitions for now
3239 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3240 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003241
John Zulaufe0757ba2022-06-10 16:51:45 -06003242 if ((write_tag >= event_tag) && last_write.any()) {
3243 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3244 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3245 } else {
3246 // only test for WAW if there no intervening read operations.
3247 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3248 if (last_reads.size()) {
3249 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3250 // first scope, or they are a hazard.
3251 const ReadStates &scope_reads = scope_state.last_reads;
3252 const ReadStates::size_type scope_read_count = scope_reads.size();
3253 // Since the hasn't been a write:
3254 // * The current read state is a superset of the scoped one
3255 // * The stage order is the same.
3256 assert(last_reads.size() >= scope_read_count);
3257 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3258 const ReadState &scope_read = scope_reads[read_idx];
3259 const ReadState &current_read = last_reads[read_idx];
3260 assert(scope_read.stage == current_read.stage);
3261 if (current_read.tag > event_tag) {
3262 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3263 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3264 } else {
3265 // The read is in the events first synchronization scope, so we use a barrier hazard check
3266 // If the read stage is not in the src sync scope
3267 // *AND* not execution chained with an existing sync barrier (that's the or)
3268 // then the barrier access is unsafe (R/W after R)
3269 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3270 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3271 break;
3272 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003273 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003274 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003275 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3276 const ReadState &current_read = last_reads[scope_read_count];
3277 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3278 }
3279 } else if (last_write.any()) {
3280 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
John Zulauf4a6105a2020-11-17 15:11:05 -07003281 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3282 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003283 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3284 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003285 }
John Zulauf361fb532020-07-22 10:45:39 -06003286 }
John Zulaufd14743a2020-07-03 09:42:39 -06003287 }
John Zulauf361fb532020-07-22 10:45:39 -06003288
John Zulauf0cb5be22020-01-23 12:18:22 -07003289 return hazard;
3290}
3291
John Zulauf5f13a792020-03-10 07:31:21 -06003292// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3293// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3294// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3295void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003296 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003297 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3298 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003299 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003300 } else if (other.write_tag == write_tag) {
3301 // In the *equals* case for write operations, we merged the write barriers and the read state (but without the
John Zulauf5f13a792020-03-10 07:31:21 -06003302 // dependency chaining logic or any stage expansion)
3303 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003304 pending_write_barriers |= other.pending_write_barriers;
3305 pending_layout_transition |= other.pending_layout_transition;
3306 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003307 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003308
John Zulaufd14743a2020-07-03 09:42:39 -06003309 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003310 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003311 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003312 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003313 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003314 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003315 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003316 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3317 // but we should wait on profiling data for that.
3318 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003319 auto &my_read = last_reads[my_read_index];
3320 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003321 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003322 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003323 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003324 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003325 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003326 my_read.pending_dep_chain = other_read.pending_dep_chain;
3327 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3328 // May require tracking more than one access per stage.
3329 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003330 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003331 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003332 // Since I'm overwriting the fragement stage read, also update the input attachment info
3333 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003334 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003335 }
John Zulauf14940722021-04-12 15:19:02 -06003336 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003337 // The read tags match so merge the barriers
3338 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003339 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003340 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003341 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003342
John Zulauf5f13a792020-03-10 07:31:21 -06003343 break;
3344 }
3345 }
3346 } else {
3347 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003348 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003349 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003350 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003351 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003352 }
John Zulauf5f13a792020-03-10 07:31:21 -06003353 }
3354 }
John Zulauf361fb532020-07-22 10:45:39 -06003355 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003356 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3357 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003358
3359 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3360 // of the copy and other into this using the update first logic.
3361 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3362 // of the other first_accesses... )
3363 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3364 FirstAccesses firsts(std::move(first_accesses_));
3365 first_accesses_.clear();
3366 first_read_stages_ = 0U;
3367 auto a = firsts.begin();
3368 auto a_end = firsts.end();
3369 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003370 // TODO: Determine whether some tag offset will be needed for PHASE II
3371 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003372 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3373 ++a;
3374 }
3375 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3376 }
3377 for (; a != a_end; ++a) {
3378 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3379 }
3380 }
John Zulauf5f13a792020-03-10 07:31:21 -06003381}
3382
John Zulauf14940722021-04-12 15:19:02 -06003383void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003384 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3385 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003386 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003387 // Mulitple outstanding reads may be of interest and do dependency chains independently
3388 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3389 const auto usage_stage = PipelineStageBit(usage_index);
3390 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003391 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003392 for (auto &read_access : last_reads) {
3393 if (read_access.stage == usage_stage) {
3394 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003395 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003396 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003397 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003398 } else {
3399 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3400 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3401 // that sync_stages is a subset of barriers may not apply.
3402 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003403 }
3404 }
3405 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003406 for (auto &read_access : last_reads) {
3407 if (read_access.barriers & usage_stage) {
3408 read_access.sync_stages |= usage_stage;
3409 }
3410 }
John Zulaufab7756b2020-12-29 16:10:16 -07003411 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003412 last_read_stages |= usage_stage;
3413 }
John Zulauf4285ee92020-09-23 10:20:52 -06003414
3415 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
Jeremy Gebben40a22942020-12-22 14:22:06 -07003416 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003417 // TODO Revisit re: multiple reads for a given stage
3418 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003419 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003420 } else {
3421 // Assume write
3422 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003423 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003424 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003425 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003426}
John Zulauf5f13a792020-03-10 07:31:21 -06003427
John Zulauf89311b42020-09-29 16:28:47 -06003428// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3429// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3430// We can overwrite them as *this* write is now after them.
3431//
3432// Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them.
John Zulauf14940722021-04-12 15:19:02 -06003433void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003434 ClearRead();
3435 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003436 write_tag = tag;
3437 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003438}
3439
John Zulauf1d5f9c12022-05-13 14:51:08 -06003440void ResourceAccessState::ClearWrite() {
3441 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3442 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3443 write_barriers.reset();
3444 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3445 last_write.reset();
3446
3447 write_tag = 0;
3448 write_queue = QueueSyncState::kQueueIdInvalid;
3449}
3450
3451void ResourceAccessState::ClearRead() {
3452 last_reads.clear();
3453 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3454}
3455
John Zulauf89311b42020-09-29 16:28:47 -06003456// Apply the memory barrier without updating the existing barriers. The execution barrier
3457// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3458// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3459// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003460template <typename ScopeOps>
3461void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003462 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3463 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003464 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
John Zulaufb7578302022-05-19 13:50:18 -06003465 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003466 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3467 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003468 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003469 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003470 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003471 if (layout_transition) {
3472 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3473 }
John Zulaufa0a98292020-09-18 09:30:10 -06003474 }
John Zulauf89311b42020-09-29 16:28:47 -06003475 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3476 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003477
John Zulauf89311b42020-09-29 16:28:47 -06003478 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003479 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3480 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003481 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3482
John Zulaufab7756b2020-12-29 16:10:16 -07003483 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003484 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
John Zulaufb7578302022-05-19 13:50:18 -06003485 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003486 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3487 stages_in_scope |= read_access.stage;
3488 }
3489 }
3490
3491 for (auto &read_access : last_reads) {
3492 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3493 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3494 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3495 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003496 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003497 }
3498 }
John Zulaufa0a98292020-09-18 09:30:10 -06003499 }
John Zulaufa0a98292020-09-18 09:30:10 -06003500}
3501
John Zulauf14940722021-04-12 15:19:02 -06003502void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003503 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003504 // SetWrite clobbers the last_reads array, and thus we don't have to clear the read_state out.
John Zulauf89311b42020-09-29 16:28:47 -06003505 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003506 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003507 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3508 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003509 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003510 }
John Zulauf89311b42020-09-29 16:28:47 -06003511
3512 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003513 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003514 for (auto &read_access : last_reads) {
3515 read_access.barriers |= read_access.pending_dep_chain;
3516 read_execution_barriers |= read_access.barriers;
3517 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003518 }
3519
3520 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3521 write_dependency_chain |= pending_write_dep_chain;
3522 write_barriers |= pending_write_barriers;
3523 pending_write_dep_chain = 0;
3524 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003525}
3526
John Zulaufecf4ac52022-06-06 10:08:42 -06003527// Assumes signal queue != wait queue
3528void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3529 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3530 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3531 assert(signal.queue != wait.queue);
3532 for (auto &read_access : last_reads) {
3533 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3534 // Deflects WAR on wait queue
3535 read_access.barriers = wait.exec_scope;
3536 } else {
3537 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3538 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3539 }
3540 }
3541 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3542 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3543 read_execution_barriers = wait.exec_scope;
3544 write_barriers = wait.valid_accesses;
3545 } else {
3546 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3547 write_barriers.reset();
3548 }
3549 write_dependency_chain = read_execution_barriers;
3550}
3551
John Zulauf3da08bb2022-08-01 17:56:56 -06003552bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) const {
3553 return (usage_queue == queue) && (usage_tag <= tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003554}
3555
John Zulauf3da08bb2022-08-01 17:56:56 -06003556bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) const { return queue == usage_queue; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003557
John Zulauf3da08bb2022-08-01 17:56:56 -06003558bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) const { return tag <= usage_tag; }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003559
3560// Return if the resulting state is "empty"
3561template <typename Pred>
3562bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3563 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3564
3565 // Use the predicate to build a mask of the read stages we are synchronizing
3566 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003567 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003568 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003569 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3570 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003571 }
3572 }
3573
John Zulauf434c4e62022-05-19 16:03:56 -06003574 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3575 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3576 uint32_t unsync_count = 0;
3577 for (auto &read_access : last_reads) {
3578 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3579 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3580 sync_reads |= read_access.stage;
3581 } else {
3582 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003583 }
3584 }
3585
3586 if (unsync_count) {
3587 if (sync_reads) {
3588 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3589 ReadStates unsync_reads;
3590 unsync_reads.reserve(unsync_count);
3591 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3592 for (auto &read_access : last_reads) {
3593 if (0 == (read_access.stage & sync_reads)) {
3594 unsync_reads.emplace_back(read_access);
3595 unsync_read_stages |= read_access.stage;
3596 }
3597 }
3598 last_read_stages = unsync_read_stages;
3599 last_reads = std::move(unsync_reads);
3600 }
3601 } else {
3602 // Nothing remains (or it was empty to begin with)
3603 ClearRead();
3604 }
3605
3606 bool all_clear = last_reads.size() == 0;
3607 if (last_write.any()) {
3608 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3609 // Clear any predicated write, or any the write from any any access with synchronized reads.
3610 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3611 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3612 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3613 ClearWrite();
3614 } else {
3615 all_clear = false;
3616 }
3617 }
3618 return all_clear;
3619}
3620
John Zulaufae842002021-04-15 18:20:55 -06003621bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3622 if (!first_accesses_.size()) return false;
3623 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3624 return tag_range.intersects(first_access_range);
3625}
3626
John Zulauf1d5f9c12022-05-13 14:51:08 -06003627void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3628 if (last_write.any()) write_tag += offset;
3629 for (auto &read_access : last_reads) {
3630 read_access.tag += offset;
3631 }
3632 for (auto &first : first_accesses_) {
3633 first.tag += offset;
3634 }
3635}
3636
3637ResourceAccessState::ResourceAccessState()
3638 : write_barriers(~SyncStageAccessFlags(0)),
3639 write_dependency_chain(0),
3640 write_tag(),
3641 write_queue(QueueSyncState::kQueueIdInvalid),
3642 last_write(0),
3643 input_attachment_read(false),
3644 last_read_stages(0),
3645 read_execution_barriers(0),
3646 pending_write_dep_chain(0),
3647 pending_layout_transition(false),
3648 pending_write_barriers(0),
3649 pending_layout_ordering_(),
3650 first_accesses_(),
3651 first_read_stages_(0U),
3652 first_write_layout_ordering_() {}
3653
John Zulauf59e25072020-07-17 10:55:21 -06003654// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003655VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3656 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003657
John Zulaufab7756b2020-12-29 16:10:16 -07003658 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003659 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003660 barriers = read_access.barriers;
3661 break;
John Zulauf59e25072020-07-17 10:55:21 -06003662 }
3663 }
John Zulauf4285ee92020-09-23 10:20:52 -06003664
John Zulauf59e25072020-07-17 10:55:21 -06003665 return barriers;
3666}
3667
John Zulauf1d5f9c12022-05-13 14:51:08 -06003668void ResourceAccessState::SetQueueId(QueueId id) {
3669 for (auto &read_access : last_reads) {
3670 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3671 read_access.queue = id;
3672 }
3673 }
3674 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3675 write_queue = id;
3676 }
3677}
3678
John Zulauf00119522022-05-23 19:07:42 -06003679bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3680 return 0 != (write_dependency_chain & src_exec_scope);
3681}
3682
3683bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3684 return (src_access_scope & last_write).any();
3685}
3686
John Zulaufec943ec2022-06-29 07:52:56 -06003687bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3688 return (write_barriers & src_access_scope).any();
3689}
3690
John Zulaufb7578302022-05-19 13:50:18 -06003691bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3692 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003693 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3694}
3695
3696bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3697 SyncStageAccessFlags src_access_scope) const {
3698 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003699}
3700
John Zulaufe0757ba2022-06-10 16:51:45 -06003701bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3702 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003703 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3704 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3705 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003706 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003707}
3708
John Zulaufec943ec2022-06-29 07:52:56 -06003709bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3710 const SyncStageAccessFlags &src_access_scope) const {
3711 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3712}
3713
John Zulaufcb7e1672022-05-04 13:46:08 -06003714bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003715 assert(IsRead(usage));
3716 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3717 // * the previous reads are not hazards, and thus last_write must be visible and available to
3718 // any reads that happen after.
3719 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3720 // the current read will be also not be a hazard, thus reporting a hazard here adds no needed information.
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003721 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003722}
3723
John Zulaufec943ec2022-06-29 07:52:56 -06003724VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3725 // At apply queue submission order limits on the effect of ordering
3726 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3727 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3728 for (const auto &read_access : last_reads) {
3729 if (read_access.queue != queue_id) {
3730 non_qso_stages |= read_access.stage;
3731 }
3732 }
3733 }
John Zulauf4285ee92020-09-23 10:20:52 -06003734 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003735 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3736 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003737 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003738 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003739 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003740 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
Jeremy Gebben40a22942020-12-22 14:22:06 -07003741 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003742 }
3743
3744 return ordered_stages;
3745}
3746
John Zulauf14940722021-04-12 15:19:02 -06003747void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003748 // Only record until we record a write.
3749 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003750 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003751 if (0 == (usage_stage & first_read_stages_)) {
3752 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003753 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003754 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003755 if (0 == (read_execution_barriers & usage_stage)) {
3756 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3757 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3758 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003759 }
3760 }
3761}
3762
John Zulauf4fa68462021-04-26 21:04:22 -06003763void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3764 // Only call this after recording an image layout transition
3765 assert(first_accesses_.size());
3766 if (first_accesses_.back().tag == tag) {
3767 // If this layout transition is the the first write, add the additional ordering rules that guard the ILT
Samuel Iglesias Gonsálvez9b4660b2021-10-21 08:50:39 +02003768 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003769 first_write_layout_ordering_ = layout_ordering;
3770 }
3771}
3772
John Zulauf1d5f9c12022-05-13 14:51:08 -06003773ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3774 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3775 : stage(stage_),
3776 access(access_),
3777 barriers(barriers_),
3778 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3779 tag(tag_),
3780 queue(QueueSyncState::kQueueIdInvalid),
3781 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3782
John Zulaufee984022022-04-13 16:39:50 -06003783void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3784 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3785 stage = stage_;
3786 access = access_;
3787 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003788 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003789 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003790 pending_dep_chain = VK_PIPELINE_STAGE_2_NONE; // If this is a new read, we aren't applying a barrier set.
John Zulaufee984022022-04-13 16:39:50 -06003791}
3792
John Zulauf00119522022-05-23 19:07:42 -06003793// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3794// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3795// that have bee applied (via semaphore) to those accesses can be chained off of.
3796bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3797 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3798 return (exec_scope & effective_stages) != 0;
3799}
3800
John Zulauf697c0e12022-04-19 16:31:12 -06003801ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3802 ResourceUsageRange reserve;
3803 reserve.begin = tag_limit_.fetch_add(tag_count);
3804 reserve.end = reserve.begin + tag_count;
3805 return reserve;
3806}
3807
John Zulauf3da08bb2022-08-01 17:56:56 -06003808void SyncValidator::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
3809 // We need to go through every queue batch context and clear all accesses this wait synchronizes
3810 // As usual -- two groups, the "last batch" and the signaled semaphores
3811 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
3812 // QueueBatchContext, track which we've done to avoid duplicate traversals
3813 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
3814 for (auto &batch : queue_batch_contexts) {
3815 batch->ApplyTaggedWait(queue_id, tag);
3816 }
3817}
3818
3819void SyncValidator::UpdateFenceWaitInfo(VkFence fence, QueueId queue_id, ResourceUsageTag tag) {
3820 if (fence != VK_NULL_HANDLE) {
3821 // Overwrite the current fence wait information
3822 // NOTE: Not doing fence usage validation here, leaving that in CoreChecks intentionally
3823 auto fence_state = Get<FENCE_STATE>(fence);
3824 waitable_fences_[fence] = {fence_state, tag, queue_id};
3825 }
3826}
3827
3828void SyncValidator::WaitForFence(VkFence fence) {
3829 auto fence_it = waitable_fences_.find(fence);
3830 if (fence_it != waitable_fences_.end()) {
3831 // The fence may no longer be waitable for several valid reasons.
3832 FenceSyncState &wait_for = fence_it->second;
3833 ApplyTaggedWait(wait_for.queue_id, wait_for.tag);
3834 waitable_fences_.erase(fence_it);
3835 }
3836}
3837
John Zulaufbbda4572022-04-19 16:20:45 -06003838const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3839 return GetMappedPlainFromShared(queue_sync_states_, queue);
3840}
3841
3842QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3843
3844std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3845 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3846}
3847
3848std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3849 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3850}
3851
John Zulaufe0757ba2022-06-10 16:51:45 -06003852template <typename T>
3853struct GetBatchTraits {};
3854template <>
3855struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3856 using Batch = std::shared_ptr<QueueBatchContext>;
3857 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3858};
3859
3860template <>
3861struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3862 using Batch = std::shared_ptr<QueueBatchContext>;
3863 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3864};
3865
3866template <typename BatchSet, typename Map, typename Predicate>
3867static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003868 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003869 for (auto &entry : map) {
3870 // Intentional copy
3871 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003872 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003873 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003874 return snapshot;
3875}
3876
3877template <typename Predicate>
3878QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003879 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003880}
3881
3882template <typename Predicate>
3883QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003884 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3885}
3886
3887QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3888 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3889 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3890 if (batch && !layer_data::Contains(snapshot, batch)) {
3891 snapshot.emplace(batch);
3892 }
3893 return false;
3894 };
3895 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3896 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003897}
3898
John Zulaufcb7e1672022-05-04 13:46:08 -06003899bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3900 const std::shared_ptr<QueueBatchContext> &batch,
3901 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003902 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003903 const SyncExecScope exec_scope =
3904 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3905 const VkSemaphore sem = sem_state->semaphore();
3906 auto signal_it = signaled_.find(sem);
3907 std::shared_ptr<Signal> insert_signal;
3908 if (signal_it == signaled_.end()) {
3909 if (prev_) {
3910 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3911 if (prev_sig) {
3912 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3913 insert_signal = std::make_shared<Signal>(*prev_sig);
3914 }
3915 }
3916 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3917 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003918 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003919
3920 bool success = false;
3921 if (!signal_it->second) {
3922 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3923 success = true;
3924 }
3925
3926 return success;
3927}
3928
John Zulaufecf4ac52022-06-06 10:08:42 -06003929std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3930 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003931 const auto found_it = signaled_.find(sem);
3932 if (found_it != signaled_.end()) {
3933 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3934 // a bit.
3935 unsignaled = std::move(found_it->second);
3936 if (!prev_) {
3937 // No parent, not need to keep the entry
3938 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3939 signaled_.erase(found_it);
3940 }
3941 } else if (prev_) {
3942 // We can't unsignal prev_ because it's const * by design.
3943 // We put in an empty placeholder
3944 signaled_.emplace(sem, std::shared_ptr<Signal>());
3945 unsignaled = GetPrev(sem);
3946 }
3947 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3948 // but CoreChecks should have reported it
3949
3950 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003951 return unsignaled;
3952}
3953
John Zulaufcb7e1672022-05-04 13:46:08 -06003954void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3955 // Overwrite the s tate with the last state from this
3956 if (from) {
3957 assert(sem == from->sem_state->semaphore());
3958 signaled_[sem] = std::move(from);
3959 } else {
3960 signaled_.erase(sem);
3961 }
3962}
3963
3964void SignaledSemaphores::Reset() {
3965 signaled_.clear();
3966 prev_ = nullptr;
3967}
3968
John Zulaufea943c52022-02-22 11:05:17 -07003969std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3970 // If we don't have one, make it.
3971 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3972 assert(cb_state.get());
3973 auto queue_flags = cb_state->GetQueueFlags();
3974 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3975}
3976
John Zulaufcb7e1672022-05-04 13:46:08 -06003977std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003978 return GetMappedInsert(cb_access_state, command_buffer,
3979 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3980}
3981
3982std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3983 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3984}
3985
3986const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3987 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3988}
3989
3990CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3991 return GetAccessContextShared(command_buffer).get();
3992}
3993
3994CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3995 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3996}
3997
John Zulaufd1f85d42020-04-15 12:23:15 -06003998void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003999 auto *access_context = GetAccessContextNoInsert(command_buffer);
4000 if (access_context) {
4001 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06004002 }
4003}
4004
John Zulaufd1f85d42020-04-15 12:23:15 -06004005void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
4006 auto access_found = cb_access_state.find(command_buffer);
4007 if (access_found != cb_access_state.end()) {
4008 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06004009 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06004010 cb_access_state.erase(access_found);
4011 }
4012}
4013
John Zulauf9cb530d2019-09-30 14:14:10 -06004014bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4015 uint32_t regionCount, const VkBufferCopy *pRegions) const {
4016 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004017 const auto *cb_context = GetAccessContext(commandBuffer);
4018 assert(cb_context);
4019 if (!cb_context) return skip;
4020 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06004021
John Zulauf3d84f1b2020-03-09 13:33:25 -06004022 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004023 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4024 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004025
4026 for (uint32_t region = 0; region < regionCount; region++) {
4027 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004028 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004029 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004030 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004031 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004032 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004033 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004034 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004035 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06004036 }
John Zulauf9cb530d2019-09-30 14:14:10 -06004037 }
John Zulauf16adfc92020-04-08 10:28:33 -06004038 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004039 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004040 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004041 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004042 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004043 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004044 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004045 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06004046 }
4047 }
4048 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06004049 }
4050 return skip;
4051}
4052
4053void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
4054 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004055 auto *cb_context = GetAccessContext(commandBuffer);
4056 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004057 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004058 auto *context = cb_context->GetCurrentAccessContext();
4059
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004060 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4061 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06004062
4063 for (uint32_t region = 0; region < regionCount; region++) {
4064 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06004065 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004066 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004067 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004068 }
John Zulauf16adfc92020-04-08 10:28:33 -06004069 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004070 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004071 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004072 }
4073 }
4074}
4075
John Zulauf4a6105a2020-11-17 15:11:05 -07004076void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4077 // Clear out events from the command buffer contexts
4078 for (auto &cb_context : cb_access_state) {
4079 cb_context.second->RecordDestroyEvent(event);
4080 }
4081}
4082
Tony-LunarGef035472021-11-02 10:23:33 -06004083bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4084 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004085 bool skip = false;
4086 const auto *cb_context = GetAccessContext(commandBuffer);
4087 assert(cb_context);
4088 if (!cb_context) return skip;
4089 const auto *context = cb_context->GetCurrentAccessContext();
4090
4091 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004092 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4093 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004094
4095 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4096 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4097 if (src_buffer) {
4098 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004099 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004100 if (hazard.hazard) {
4101 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004102 skip |=
4103 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4104 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4105 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4106 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004107 }
4108 }
4109 if (dst_buffer && !skip) {
4110 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004111 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004112 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004113 skip |=
4114 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4115 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4116 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4117 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004118 }
4119 }
4120 if (skip) break;
4121 }
4122 return skip;
4123}
4124
Tony-LunarGef035472021-11-02 10:23:33 -06004125bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4126 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4127 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4128}
4129
4130bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4131 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4132}
4133
4134void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004135 auto *cb_context = GetAccessContext(commandBuffer);
4136 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004137 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004138 auto *context = cb_context->GetCurrentAccessContext();
4139
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004140 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4141 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004142
4143 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4144 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4145 if (src_buffer) {
4146 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004147 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004148 }
4149 if (dst_buffer) {
4150 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004151 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004152 }
4153 }
4154}
4155
Tony-LunarGef035472021-11-02 10:23:33 -06004156void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4157 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4158}
4159
4160void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4161 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4162}
4163
John Zulauf5c5e88d2019-12-26 11:22:02 -07004164bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4165 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4166 const VkImageCopy *pRegions) const {
4167 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004168 const auto *cb_access_context = GetAccessContext(commandBuffer);
4169 assert(cb_access_context);
4170 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004171
John Zulauf3d84f1b2020-03-09 13:33:25 -06004172 const auto *context = cb_access_context->GetCurrentAccessContext();
4173 assert(context);
4174 if (!context) return skip;
4175
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004176 auto src_image = Get<IMAGE_STATE>(srcImage);
4177 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004178 for (uint32_t region = 0; region < regionCount; region++) {
4179 const auto &copy_region = pRegions[region];
4180 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004181 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004182 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004183 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004184 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004185 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004186 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004187 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004188 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004189 }
4190
4191 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004192 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004193 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004194 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004195 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004196 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004197 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004198 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004199 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004200 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004201 }
4202 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004203
John Zulauf5c5e88d2019-12-26 11:22:02 -07004204 return skip;
4205}
4206
4207void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4208 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4209 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004210 auto *cb_access_context = GetAccessContext(commandBuffer);
4211 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004212 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004213 auto *context = cb_access_context->GetCurrentAccessContext();
4214 assert(context);
4215
Jeremy Gebben9f537102021-10-05 16:37:12 -06004216 auto src_image = Get<IMAGE_STATE>(srcImage);
4217 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004218
4219 for (uint32_t region = 0; region < regionCount; region++) {
4220 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004221 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004222 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004223 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004224 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004225 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004226 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004227 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004228 }
4229 }
4230}
4231
Tony-LunarGb61514a2021-11-02 12:36:51 -06004232bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4233 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004234 bool skip = false;
4235 const auto *cb_access_context = GetAccessContext(commandBuffer);
4236 assert(cb_access_context);
4237 if (!cb_access_context) return skip;
4238
4239 const auto *context = cb_access_context->GetCurrentAccessContext();
4240 assert(context);
4241 if (!context) return skip;
4242
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004243 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4244 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004245
Jeff Leger178b1e52020-10-05 12:22:23 -04004246 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4247 const auto &copy_region = pCopyImageInfo->pRegions[region];
4248 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004249 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004250 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004251 if (hazard.hazard) {
4252 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004253 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004254 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004255 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004256 }
4257 }
4258
4259 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004260 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004261 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004262 if (hazard.hazard) {
4263 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004264 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004265 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004266 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004267 }
4268 if (skip) break;
4269 }
4270 }
4271
4272 return skip;
4273}
4274
Tony-LunarGb61514a2021-11-02 12:36:51 -06004275bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4276 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4277 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4278}
4279
4280bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4281 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4282}
4283
4284void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004285 auto *cb_access_context = GetAccessContext(commandBuffer);
4286 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004287 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004288 auto *context = cb_access_context->GetCurrentAccessContext();
4289 assert(context);
4290
Jeremy Gebben9f537102021-10-05 16:37:12 -06004291 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4292 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004293
4294 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4295 const auto &copy_region = pCopyImageInfo->pRegions[region];
4296 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004297 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004298 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004299 }
4300 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004301 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004302 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004303 }
4304 }
4305}
4306
Tony-LunarGb61514a2021-11-02 12:36:51 -06004307void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4308 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4309}
4310
4311void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4312 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4313}
4314
John Zulauf9cb530d2019-09-30 14:14:10 -06004315bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4316 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4317 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4318 uint32_t bufferMemoryBarrierCount,
4319 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4320 uint32_t imageMemoryBarrierCount,
4321 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4322 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004323 const auto *cb_access_context = GetAccessContext(commandBuffer);
4324 assert(cb_access_context);
4325 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004326
John Zulauf36ef9282021-02-02 11:47:24 -07004327 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4328 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4329 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4330 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004331 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004332 return skip;
4333}
4334
4335void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4336 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4337 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4338 uint32_t bufferMemoryBarrierCount,
4339 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4340 uint32_t imageMemoryBarrierCount,
4341 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004342 auto *cb_access_context = GetAccessContext(commandBuffer);
4343 assert(cb_access_context);
4344 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004345
John Zulauf1bf30522021-09-03 15:39:06 -06004346 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4347 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4348 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4349 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004350}
4351
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004352bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4353 const VkDependencyInfoKHR *pDependencyInfo) const {
4354 bool skip = false;
4355 const auto *cb_access_context = GetAccessContext(commandBuffer);
4356 assert(cb_access_context);
4357 if (!cb_access_context) return skip;
4358
4359 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4360 skip = pipeline_barrier.Validate(*cb_access_context);
4361 return skip;
4362}
4363
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004364bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4365 const VkDependencyInfo *pDependencyInfo) const {
4366 bool skip = false;
4367 const auto *cb_access_context = GetAccessContext(commandBuffer);
4368 assert(cb_access_context);
4369 if (!cb_access_context) return skip;
4370
4371 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4372 skip = pipeline_barrier.Validate(*cb_access_context);
4373 return skip;
4374}
4375
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004376void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4377 auto *cb_access_context = GetAccessContext(commandBuffer);
4378 assert(cb_access_context);
4379 if (!cb_access_context) return;
4380
John Zulauf1bf30522021-09-03 15:39:06 -06004381 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4382 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004383}
4384
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004385void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4386 auto *cb_access_context = GetAccessContext(commandBuffer);
4387 assert(cb_access_context);
4388 if (!cb_access_context) return;
4389
4390 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4391 *pDependencyInfo);
4392}
4393
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004394void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004395 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004396 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004397
John Zulauf5f13a792020-03-10 07:31:21 -06004398 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4399 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004400 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004401 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4402 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004403
John Zulauf1d5f9c12022-05-13 14:51:08 -06004404 QueueId queue_id = QueueSyncState::kQueueIdBase;
4405 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004406 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004407 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004408 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4409 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004410}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004411
John Zulauf355e49b2020-04-24 15:11:15 -06004412bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004413 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004414 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004415 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004416 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004417 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004418 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004419 }
John Zulauf355e49b2020-04-24 15:11:15 -06004420 return skip;
4421}
4422
4423bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4424 VkSubpassContents contents) const {
4425 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004426 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004427 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004428 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004429 return skip;
4430}
4431
4432bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004433 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004434 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004435 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004436 return skip;
4437}
4438
4439bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4440 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004441 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004442 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004443 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004444 return skip;
4445}
4446
John Zulauf3d84f1b2020-03-09 13:33:25 -06004447void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4448 VkResult result) {
4449 // The state tracker sets up the command buffer state
4450 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4451
4452 // Create/initialize the structure that trackers accesses at the command buffer scope.
4453 auto cb_access_context = GetAccessContext(commandBuffer);
4454 assert(cb_access_context);
4455 cb_access_context->Reset();
4456}
4457
4458void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004459 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004460 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004461 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004462 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004463 }
4464}
4465
4466void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4467 VkSubpassContents contents) {
4468 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004469 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004470 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004471 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004472}
4473
4474void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4475 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4476 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004477 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004478}
4479
4480void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4481 const VkRenderPassBeginInfo *pRenderPassBegin,
4482 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4483 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004484 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004485}
4486
Mike Schuchardt2df08912020-12-15 16:28:09 -08004487bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004488 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004489 bool skip = false;
4490
4491 auto cb_context = GetAccessContext(commandBuffer);
4492 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004493 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004494 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004495 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004496}
4497
4498bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4499 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004500 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004501 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004502 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004503 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4504 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004505 return skip;
4506}
4507
Mike Schuchardt2df08912020-12-15 16:28:09 -08004508bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4509 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004510 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004511 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004512 return skip;
4513}
4514
4515bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4516 const VkSubpassEndInfo *pSubpassEndInfo) const {
4517 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004518 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004519 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004520}
4521
4522void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004523 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004524 auto cb_context = GetAccessContext(commandBuffer);
4525 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004526 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004527
sjfricke0bea06e2022-06-05 09:22:26 +09004528 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004529}
4530
4531void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4532 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004533 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004534 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004535 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004536}
4537
4538void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4539 const VkSubpassEndInfo *pSubpassEndInfo) {
4540 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004541 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004542}
4543
4544void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4545 const VkSubpassEndInfo *pSubpassEndInfo) {
4546 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004547 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004548}
4549
sfricke-samsung85584a72021-09-30 21:43:38 -07004550bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004551 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004552 bool skip = false;
4553
4554 auto cb_context = GetAccessContext(commandBuffer);
4555 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004556 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004557
sjfricke0bea06e2022-06-05 09:22:26 +09004558 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004559 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004560 return skip;
4561}
4562
4563bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4564 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004565 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004566 return skip;
4567}
4568
Mike Schuchardt2df08912020-12-15 16:28:09 -08004569bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004570 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004571 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004572 return skip;
4573}
4574
4575bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004576 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004577 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004578 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004579 return skip;
4580}
4581
sjfricke0bea06e2022-06-05 09:22:26 +09004582void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4583 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004584 // Resolve the all subpass contexts to the command buffer contexts
4585 auto cb_context = GetAccessContext(commandBuffer);
4586 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004587 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004588
sjfricke0bea06e2022-06-05 09:22:26 +09004589 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004590}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004591
John Zulauf33fc1d52020-07-17 11:01:10 -06004592// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4593// updates to a resource which do not conflict at the byte level.
4594// TODO: Revisit this rule to see if it needs to be tighter or looser
4595// TODO: Add programatic control over suppression heuristics
4596bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4597 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4598}
4599
John Zulauf3d84f1b2020-03-09 13:33:25 -06004600void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004601 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004602 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004603}
4604
4605void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004606 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004607 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004608}
4609
4610void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004611 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004612 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004613}
locke-lunarga19c71d2020-03-02 18:17:04 -07004614
sfricke-samsung71f04e32022-03-16 01:21:21 -05004615template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004616bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004617 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4618 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004619 bool skip = false;
4620 const auto *cb_access_context = GetAccessContext(commandBuffer);
4621 assert(cb_access_context);
4622 if (!cb_access_context) return skip;
4623
4624 const auto *context = cb_access_context->GetCurrentAccessContext();
4625 assert(context);
4626 if (!context) return skip;
4627
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004628 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4629 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004630
4631 for (uint32_t region = 0; region < regionCount; region++) {
4632 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004633 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004634 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004635 if (src_buffer) {
4636 ResourceAccessRange src_range =
4637 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004638 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004639 if (hazard.hazard) {
4640 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004641 skip |=
4642 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4643 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4644 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4645 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004646 }
4647 }
4648
Jeremy Gebben40a22942020-12-22 14:22:06 -07004649 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004650 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004651 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004652 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004653 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004654 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004655 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004656 }
4657 if (skip) break;
4658 }
4659 if (skip) break;
4660 }
4661 return skip;
4662}
4663
Jeff Leger178b1e52020-10-05 12:22:23 -04004664bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4665 VkImageLayout dstImageLayout, uint32_t regionCount,
4666 const VkBufferImageCopy *pRegions) const {
4667 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004668 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004669}
4670
4671bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4672 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4673 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4674 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004675 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4676}
4677
4678bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4679 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4680 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4681 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4682 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004683}
4684
sfricke-samsung71f04e32022-03-16 01:21:21 -05004685template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004686void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004687 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4688 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004689 auto *cb_access_context = GetAccessContext(commandBuffer);
4690 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004691
Jeff Leger178b1e52020-10-05 12:22:23 -04004692 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004693 auto *context = cb_access_context->GetCurrentAccessContext();
4694 assert(context);
4695
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004696 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4697 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004698
4699 for (uint32_t region = 0; region < regionCount; region++) {
4700 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004701 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004702 if (src_buffer) {
4703 ResourceAccessRange src_range =
4704 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004705 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004706 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004707 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004708 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004709 }
4710 }
4711}
4712
Jeff Leger178b1e52020-10-05 12:22:23 -04004713void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4714 VkImageLayout dstImageLayout, uint32_t regionCount,
4715 const VkBufferImageCopy *pRegions) {
4716 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004717 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004718}
4719
4720void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4721 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4722 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4723 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4724 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004725 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4726}
4727
4728void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4729 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4730 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4731 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4732 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4733 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004734}
4735
sfricke-samsung71f04e32022-03-16 01:21:21 -05004736template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004737bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004738 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4739 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004740 bool skip = false;
4741 const auto *cb_access_context = GetAccessContext(commandBuffer);
4742 assert(cb_access_context);
4743 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004744
locke-lunarga19c71d2020-03-02 18:17:04 -07004745 const auto *context = cb_access_context->GetCurrentAccessContext();
4746 assert(context);
4747 if (!context) return skip;
4748
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004749 auto src_image = Get<IMAGE_STATE>(srcImage);
4750 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004751 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004752 for (uint32_t region = 0; region < regionCount; region++) {
4753 const auto &copy_region = pRegions[region];
4754 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004755 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004756 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004757 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004758 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004759 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004760 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004761 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004762 }
John Zulauf477700e2021-01-06 11:41:49 -07004763 if (dst_mem) {
4764 ResourceAccessRange dst_range =
4765 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004766 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004767 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004768 skip |=
4769 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4770 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4771 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4772 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004773 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004774 }
4775 }
4776 if (skip) break;
4777 }
4778 return skip;
4779}
4780
Jeff Leger178b1e52020-10-05 12:22:23 -04004781bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4782 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4783 const VkBufferImageCopy *pRegions) const {
4784 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004785 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004786}
4787
4788bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4789 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4790 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4791 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004792 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4793}
4794
4795bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4796 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4797 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4798 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4799 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004800}
4801
sfricke-samsung71f04e32022-03-16 01:21:21 -05004802template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004803void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004804 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004805 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004806 auto *cb_access_context = GetAccessContext(commandBuffer);
4807 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004808
Jeff Leger178b1e52020-10-05 12:22:23 -04004809 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004810 auto *context = cb_access_context->GetCurrentAccessContext();
4811 assert(context);
4812
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004813 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004814 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004815 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004816 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004817
4818 for (uint32_t region = 0; region < regionCount; region++) {
4819 const auto &copy_region = pRegions[region];
4820 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004821 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004822 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004823 if (dst_buffer) {
4824 ResourceAccessRange dst_range =
4825 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004826 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004827 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004828 }
4829 }
4830}
4831
Jeff Leger178b1e52020-10-05 12:22:23 -04004832void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4833 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4834 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004835 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004836}
4837
4838void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4839 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4840 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4841 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4842 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004843 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4844}
4845
4846void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4847 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4848 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4849 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4850 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4851 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004852}
4853
4854template <typename RegionType>
4855bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4856 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004857 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004858 bool skip = false;
4859 const auto *cb_access_context = GetAccessContext(commandBuffer);
4860 assert(cb_access_context);
4861 if (!cb_access_context) return skip;
4862
4863 const auto *context = cb_access_context->GetCurrentAccessContext();
4864 assert(context);
4865 if (!context) return skip;
4866
sjfricke0bea06e2022-06-05 09:22:26 +09004867 const char *caller_name = CommandTypeString(cmd_type);
4868
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004869 auto src_image = Get<IMAGE_STATE>(srcImage);
4870 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004871
4872 for (uint32_t region = 0; region < regionCount; region++) {
4873 const auto &blit_region = pRegions[region];
4874 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004875 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4876 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4877 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4878 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4879 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4880 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004881 auto hazard =
4882 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004883 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004884 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004885 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004886 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004887 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004888 }
4889 }
4890
4891 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004892 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4893 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4894 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4895 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4896 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4897 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004898 auto hazard =
4899 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004900 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004901 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004902 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004903 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004904 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004905 }
4906 if (skip) break;
4907 }
4908 }
4909
4910 return skip;
4911}
4912
Jeff Leger178b1e52020-10-05 12:22:23 -04004913bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4914 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4915 const VkImageBlit *pRegions, VkFilter filter) const {
4916 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004917 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004918}
4919
4920bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4921 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4922 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4923 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004924 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004925}
4926
Tony-LunarG542ae912021-11-04 16:06:44 -06004927bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4928 const VkBlitImageInfo2 *pBlitImageInfo) const {
4929 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004930 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4931 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004932}
4933
Jeff Leger178b1e52020-10-05 12:22:23 -04004934template <typename RegionType>
4935void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4936 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4937 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004938 auto *cb_access_context = GetAccessContext(commandBuffer);
4939 assert(cb_access_context);
4940 auto *context = cb_access_context->GetCurrentAccessContext();
4941 assert(context);
4942
Jeremy Gebben9f537102021-10-05 16:37:12 -06004943 auto src_image = Get<IMAGE_STATE>(srcImage);
4944 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004945
4946 for (uint32_t region = 0; region < regionCount; region++) {
4947 const auto &blit_region = pRegions[region];
4948 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004949 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4950 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4951 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4952 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4953 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4954 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004955 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004956 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004957 }
4958 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004959 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4960 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4961 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4962 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4963 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4964 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004965 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004966 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004967 }
4968 }
4969}
locke-lunarg36ba2592020-04-03 09:42:04 -06004970
Jeff Leger178b1e52020-10-05 12:22:23 -04004971void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4972 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4973 const VkImageBlit *pRegions, VkFilter filter) {
4974 auto *cb_access_context = GetAccessContext(commandBuffer);
4975 assert(cb_access_context);
4976 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4977 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4978 pRegions, filter);
4979 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4980}
4981
4982void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4983 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4984 auto *cb_access_context = GetAccessContext(commandBuffer);
4985 assert(cb_access_context);
4986 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4987 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4988 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4989 pBlitImageInfo->filter, tag);
4990}
4991
Tony-LunarG542ae912021-11-04 16:06:44 -06004992void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4993 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4994 auto *cb_access_context = GetAccessContext(commandBuffer);
4995 assert(cb_access_context);
4996 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4997 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4998 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4999 pBlitImageInfo->filter, tag);
5000}
5001
John Zulauffaea0ee2021-01-14 14:01:32 -07005002bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5003 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
5004 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005005 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005006 bool skip = false;
5007 if (drawCount == 0) return skip;
5008
sjfricke0bea06e2022-06-05 09:22:26 +09005009 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005010 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005011 VkDeviceSize size = struct_size;
5012 if (drawCount == 1 || stride == size) {
5013 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005014 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06005015 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5016 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005017 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005018 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06005019 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005020 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005021 }
5022 } else {
5023 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005024 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06005025 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5026 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005027 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005028 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
5029 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5030 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005031 break;
5032 }
5033 }
5034 }
5035 return skip;
5036}
5037
John Zulauf14940722021-04-12 15:19:02 -06005038void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06005039 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
5040 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005041 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06005042 VkDeviceSize size = struct_size;
5043 if (drawCount == 1 || stride == size) {
5044 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06005045 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005046 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005047 } else {
5048 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005049 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005050 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
5051 tag);
locke-lunargff255f92020-05-13 18:53:52 -06005052 }
5053 }
5054}
5055
John Zulauffaea0ee2021-01-14 14:01:32 -07005056bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
5057 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005058 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005059 bool skip = false;
5060
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005061 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005062 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06005063 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
5064 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06005065 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005066 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
5067 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
5068 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005069 }
5070 return skip;
5071}
5072
John Zulauf14940722021-04-12 15:19:02 -06005073void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005074 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005075 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005076 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005077}
5078
locke-lunarg36ba2592020-04-03 09:42:04 -06005079bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005080 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005081 const auto *cb_access_context = GetAccessContext(commandBuffer);
5082 assert(cb_access_context);
5083 if (!cb_access_context) return skip;
5084
sjfricke0bea06e2022-06-05 09:22:26 +09005085 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005086 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005087}
5088
5089void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005090 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005091 auto *cb_access_context = GetAccessContext(commandBuffer);
5092 assert(cb_access_context);
5093 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005094
locke-lunarg61870c22020-06-09 14:51:50 -06005095 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005096}
locke-lunarge1a67022020-04-29 00:15:36 -06005097
5098bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005099 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005100 const auto *cb_access_context = GetAccessContext(commandBuffer);
5101 assert(cb_access_context);
5102 if (!cb_access_context) return skip;
5103
5104 const auto *context = cb_access_context->GetCurrentAccessContext();
5105 assert(context);
5106 if (!context) return skip;
5107
sjfricke0bea06e2022-06-05 09:22:26 +09005108 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005109 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005110 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005111 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005112}
5113
5114void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005115 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005116 auto *cb_access_context = GetAccessContext(commandBuffer);
5117 assert(cb_access_context);
5118 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5119 auto *context = cb_access_context->GetCurrentAccessContext();
5120 assert(context);
5121
locke-lunarg61870c22020-06-09 14:51:50 -06005122 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5123 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005124}
5125
5126bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5127 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005128 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005129 const auto *cb_access_context = GetAccessContext(commandBuffer);
5130 assert(cb_access_context);
5131 if (!cb_access_context) return skip;
5132
sjfricke0bea06e2022-06-05 09:22:26 +09005133 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5134 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5135 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005136 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005137}
5138
5139void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5140 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005141 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005142 auto *cb_access_context = GetAccessContext(commandBuffer);
5143 assert(cb_access_context);
5144 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005145
locke-lunarg61870c22020-06-09 14:51:50 -06005146 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5147 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5148 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005149}
5150
5151bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5152 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005153 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005154 const auto *cb_access_context = GetAccessContext(commandBuffer);
5155 assert(cb_access_context);
5156 if (!cb_access_context) return skip;
5157
sjfricke0bea06e2022-06-05 09:22:26 +09005158 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5159 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5160 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005161 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005162}
5163
5164void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5165 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005166 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005167 auto *cb_access_context = GetAccessContext(commandBuffer);
5168 assert(cb_access_context);
5169 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005170
locke-lunarg61870c22020-06-09 14:51:50 -06005171 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5172 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5173 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005174}
5175
5176bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5177 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005178 bool skip = false;
5179 if (drawCount == 0) return skip;
5180
locke-lunargff255f92020-05-13 18:53:52 -06005181 const auto *cb_access_context = GetAccessContext(commandBuffer);
5182 assert(cb_access_context);
5183 if (!cb_access_context) return skip;
5184
5185 const auto *context = cb_access_context->GetCurrentAccessContext();
5186 assert(context);
5187 if (!context) return skip;
5188
sjfricke0bea06e2022-06-05 09:22:26 +09005189 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5190 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005191 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005192 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005193
5194 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5195 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5196 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005197 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005198 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005199}
5200
5201void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5202 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005203 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005204 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005205 auto *cb_access_context = GetAccessContext(commandBuffer);
5206 assert(cb_access_context);
5207 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5208 auto *context = cb_access_context->GetCurrentAccessContext();
5209 assert(context);
5210
locke-lunarg61870c22020-06-09 14:51:50 -06005211 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5212 cb_access_context->RecordDrawSubpassAttachment(tag);
5213 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005214
5215 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5216 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5217 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005218 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005219}
5220
5221bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5222 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005223 bool skip = false;
5224 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005225 const auto *cb_access_context = GetAccessContext(commandBuffer);
5226 assert(cb_access_context);
5227 if (!cb_access_context) return skip;
5228
5229 const auto *context = cb_access_context->GetCurrentAccessContext();
5230 assert(context);
5231 if (!context) return skip;
5232
sjfricke0bea06e2022-06-05 09:22:26 +09005233 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5234 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005235 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005236 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005237
5238 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5239 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5240 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005241 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005242 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005243}
5244
5245void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5246 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005247 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005248 auto *cb_access_context = GetAccessContext(commandBuffer);
5249 assert(cb_access_context);
5250 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5251 auto *context = cb_access_context->GetCurrentAccessContext();
5252 assert(context);
5253
locke-lunarg61870c22020-06-09 14:51:50 -06005254 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5255 cb_access_context->RecordDrawSubpassAttachment(tag);
5256 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005257
5258 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5259 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5260 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005261 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005262}
5263
5264bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5265 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005266 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005267 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005268 const auto *cb_access_context = GetAccessContext(commandBuffer);
5269 assert(cb_access_context);
5270 if (!cb_access_context) return skip;
5271
5272 const auto *context = cb_access_context->GetCurrentAccessContext();
5273 assert(context);
5274 if (!context) return skip;
5275
sjfricke0bea06e2022-06-05 09:22:26 +09005276 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5277 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005278 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005279 maxDrawCount, stride, cmd_type);
5280 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005281
5282 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5283 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5284 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005285 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005286 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005287}
5288
5289bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5290 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5291 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005292 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005293 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005294}
5295
sfricke-samsung85584a72021-09-30 21:43:38 -07005296void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5297 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5298 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005299 auto *cb_access_context = GetAccessContext(commandBuffer);
5300 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005301 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005302 auto *context = cb_access_context->GetCurrentAccessContext();
5303 assert(context);
5304
locke-lunarg61870c22020-06-09 14:51:50 -06005305 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5306 cb_access_context->RecordDrawSubpassAttachment(tag);
5307 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5308 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005309
5310 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5311 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5312 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005313 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005314}
5315
sfricke-samsung85584a72021-09-30 21:43:38 -07005316void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5317 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5318 uint32_t stride) {
5319 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5320 stride);
5321 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5322 CMD_DRAWINDIRECTCOUNT);
5323}
locke-lunarge1a67022020-04-29 00:15:36 -06005324bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5325 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5326 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005327 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005328 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005329}
5330
5331void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5332 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5333 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005334 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5335 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005336 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5337 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005338}
5339
5340bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5341 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5342 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005343 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005344 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005345}
5346
5347void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5348 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5349 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005350 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5351 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005352 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5353 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005354}
5355
5356bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5357 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005358 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005359 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005360 const auto *cb_access_context = GetAccessContext(commandBuffer);
5361 assert(cb_access_context);
5362 if (!cb_access_context) return skip;
5363
5364 const auto *context = cb_access_context->GetCurrentAccessContext();
5365 assert(context);
5366 if (!context) return skip;
5367
sjfricke0bea06e2022-06-05 09:22:26 +09005368 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5369 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005370 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005371 offset, maxDrawCount, stride, cmd_type);
5372 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005373
5374 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5375 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5376 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005377 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005378 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005379}
5380
5381bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5382 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5383 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005384 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005385 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005386}
5387
sfricke-samsung85584a72021-09-30 21:43:38 -07005388void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5389 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5390 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005391 auto *cb_access_context = GetAccessContext(commandBuffer);
5392 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005393 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005394 auto *context = cb_access_context->GetCurrentAccessContext();
5395 assert(context);
5396
locke-lunarg61870c22020-06-09 14:51:50 -06005397 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5398 cb_access_context->RecordDrawSubpassAttachment(tag);
5399 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5400 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005401
5402 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5403 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005404 // We will update the index and vertex buffer in SubmitQueue in the future.
5405 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005406}
5407
sfricke-samsung85584a72021-09-30 21:43:38 -07005408void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5409 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5410 uint32_t maxDrawCount, uint32_t stride) {
5411 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5412 maxDrawCount, stride);
5413 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5414 CMD_DRAWINDEXEDINDIRECTCOUNT);
5415}
5416
locke-lunarge1a67022020-04-29 00:15:36 -06005417bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5418 VkDeviceSize offset, VkBuffer countBuffer,
5419 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5420 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005421 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005422 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005423}
5424
5425void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5426 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5427 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005428 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5429 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005430 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5431 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005432}
5433
5434bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5435 VkDeviceSize offset, VkBuffer countBuffer,
5436 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5437 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005438 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005439 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005440}
5441
5442void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5443 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5444 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005445 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5446 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005447 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5448 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005449}
5450
5451bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5452 const VkClearColorValue *pColor, uint32_t rangeCount,
5453 const VkImageSubresourceRange *pRanges) const {
5454 bool skip = false;
5455 const auto *cb_access_context = GetAccessContext(commandBuffer);
5456 assert(cb_access_context);
5457 if (!cb_access_context) return skip;
5458
5459 const auto *context = cb_access_context->GetCurrentAccessContext();
5460 assert(context);
5461 if (!context) return skip;
5462
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005463 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005464
5465 for (uint32_t index = 0; index < rangeCount; index++) {
5466 const auto &range = pRanges[index];
5467 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005468 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005469 if (hazard.hazard) {
5470 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005471 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005472 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005473 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005474 }
5475 }
5476 }
5477 return skip;
5478}
5479
5480void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5481 const VkClearColorValue *pColor, uint32_t rangeCount,
5482 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005483 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005484 auto *cb_access_context = GetAccessContext(commandBuffer);
5485 assert(cb_access_context);
5486 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5487 auto *context = cb_access_context->GetCurrentAccessContext();
5488 assert(context);
5489
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005490 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005491
5492 for (uint32_t index = 0; index < rangeCount; index++) {
5493 const auto &range = pRanges[index];
5494 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005495 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005496 }
5497 }
5498}
5499
5500bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5501 VkImageLayout imageLayout,
5502 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5503 const VkImageSubresourceRange *pRanges) const {
5504 bool skip = false;
5505 const auto *cb_access_context = GetAccessContext(commandBuffer);
5506 assert(cb_access_context);
5507 if (!cb_access_context) return skip;
5508
5509 const auto *context = cb_access_context->GetCurrentAccessContext();
5510 assert(context);
5511 if (!context) return skip;
5512
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005513 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005514
5515 for (uint32_t index = 0; index < rangeCount; index++) {
5516 const auto &range = pRanges[index];
5517 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005518 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005519 if (hazard.hazard) {
5520 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005521 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005522 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005523 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005524 }
5525 }
5526 }
5527 return skip;
5528}
5529
5530void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5531 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5532 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005533 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005534 auto *cb_access_context = GetAccessContext(commandBuffer);
5535 assert(cb_access_context);
5536 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5537 auto *context = cb_access_context->GetCurrentAccessContext();
5538 assert(context);
5539
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005540 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005541
5542 for (uint32_t index = 0; index < rangeCount; index++) {
5543 const auto &range = pRanges[index];
5544 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005545 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005546 }
5547 }
5548}
5549
5550bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5551 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5552 VkDeviceSize dstOffset, VkDeviceSize stride,
5553 VkQueryResultFlags flags) const {
5554 bool skip = false;
5555 const auto *cb_access_context = GetAccessContext(commandBuffer);
5556 assert(cb_access_context);
5557 if (!cb_access_context) return skip;
5558
5559 const auto *context = cb_access_context->GetCurrentAccessContext();
5560 assert(context);
5561 if (!context) return skip;
5562
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005563 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005564
5565 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005566 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005567 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005568 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005569 skip |=
5570 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5571 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005572 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005573 }
5574 }
locke-lunargff255f92020-05-13 18:53:52 -06005575
5576 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005577 return skip;
5578}
5579
5580void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5581 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5582 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005583 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5584 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005585 auto *cb_access_context = GetAccessContext(commandBuffer);
5586 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005587 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005588 auto *context = cb_access_context->GetCurrentAccessContext();
5589 assert(context);
5590
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005591 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005592
5593 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005594 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005595 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005596 }
locke-lunargff255f92020-05-13 18:53:52 -06005597
5598 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005599}
5600
5601bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5602 VkDeviceSize size, uint32_t data) const {
5603 bool skip = false;
5604 const auto *cb_access_context = GetAccessContext(commandBuffer);
5605 assert(cb_access_context);
5606 if (!cb_access_context) return skip;
5607
5608 const auto *context = cb_access_context->GetCurrentAccessContext();
5609 assert(context);
5610 if (!context) return skip;
5611
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005612 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005613
5614 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005615 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005616 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005617 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005618 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005619 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005620 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005621 }
5622 }
5623 return skip;
5624}
5625
5626void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5627 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005628 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005629 auto *cb_access_context = GetAccessContext(commandBuffer);
5630 assert(cb_access_context);
5631 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5632 auto *context = cb_access_context->GetCurrentAccessContext();
5633 assert(context);
5634
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005635 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005636
5637 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005638 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005639 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005640 }
5641}
5642
5643bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5644 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5645 const VkImageResolve *pRegions) const {
5646 bool skip = false;
5647 const auto *cb_access_context = GetAccessContext(commandBuffer);
5648 assert(cb_access_context);
5649 if (!cb_access_context) return skip;
5650
5651 const auto *context = cb_access_context->GetCurrentAccessContext();
5652 assert(context);
5653 if (!context) return skip;
5654
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005655 auto src_image = Get<IMAGE_STATE>(srcImage);
5656 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005657
5658 for (uint32_t region = 0; region < regionCount; region++) {
5659 const auto &resolve_region = pRegions[region];
5660 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005661 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005662 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005663 if (hazard.hazard) {
5664 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005665 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005666 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005667 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005668 }
5669 }
5670
5671 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005672 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005673 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005674 if (hazard.hazard) {
5675 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005676 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005677 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005678 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005679 }
5680 if (skip) break;
5681 }
5682 }
5683
5684 return skip;
5685}
5686
5687void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5688 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5689 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005690 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5691 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005692 auto *cb_access_context = GetAccessContext(commandBuffer);
5693 assert(cb_access_context);
5694 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5695 auto *context = cb_access_context->GetCurrentAccessContext();
5696 assert(context);
5697
Jeremy Gebben9f537102021-10-05 16:37:12 -06005698 auto src_image = Get<IMAGE_STATE>(srcImage);
5699 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005700
5701 for (uint32_t region = 0; region < regionCount; region++) {
5702 const auto &resolve_region = pRegions[region];
5703 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005704 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005705 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005706 }
5707 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005708 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005709 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005710 }
5711 }
5712}
5713
Tony-LunarG562fc102021-11-12 13:58:35 -07005714bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5715 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005716 bool skip = false;
5717 const auto *cb_access_context = GetAccessContext(commandBuffer);
5718 assert(cb_access_context);
5719 if (!cb_access_context) return skip;
5720
5721 const auto *context = cb_access_context->GetCurrentAccessContext();
5722 assert(context);
5723 if (!context) return skip;
5724
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005725 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5726 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005727
5728 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5729 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5730 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005731 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005732 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005733 if (hazard.hazard) {
5734 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005735 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005736 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005737 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005738 }
5739 }
5740
5741 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005742 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005743 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005744 if (hazard.hazard) {
5745 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005746 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005747 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005748 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005749 }
5750 if (skip) break;
5751 }
5752 }
5753
5754 return skip;
5755}
5756
Tony-LunarG562fc102021-11-12 13:58:35 -07005757bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5758 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5759 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5760}
5761
5762bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5763 const VkResolveImageInfo2 *pResolveImageInfo) const {
5764 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5765}
5766
5767void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5768 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005769 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5770 auto *cb_access_context = GetAccessContext(commandBuffer);
5771 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005772 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005773 auto *context = cb_access_context->GetCurrentAccessContext();
5774 assert(context);
5775
Jeremy Gebben9f537102021-10-05 16:37:12 -06005776 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5777 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005778
5779 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5780 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5781 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005782 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005783 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005784 }
5785 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005786 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005787 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005788 }
5789 }
5790}
5791
Tony-LunarG562fc102021-11-12 13:58:35 -07005792void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5793 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5794 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5795}
5796
5797void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5798 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5799}
5800
locke-lunarge1a67022020-04-29 00:15:36 -06005801bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5802 VkDeviceSize dataSize, const void *pData) const {
5803 bool skip = false;
5804 const auto *cb_access_context = GetAccessContext(commandBuffer);
5805 assert(cb_access_context);
5806 if (!cb_access_context) return skip;
5807
5808 const auto *context = cb_access_context->GetCurrentAccessContext();
5809 assert(context);
5810 if (!context) return skip;
5811
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005812 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005813
5814 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005815 // VK_WHOLE_SIZE not allowed
5816 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005817 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005818 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005819 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005820 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005821 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005822 }
5823 }
5824 return skip;
5825}
5826
5827void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5828 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005829 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005830 auto *cb_access_context = GetAccessContext(commandBuffer);
5831 assert(cb_access_context);
5832 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5833 auto *context = cb_access_context->GetCurrentAccessContext();
5834 assert(context);
5835
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005836 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005837
5838 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005839 // VK_WHOLE_SIZE not allowed
5840 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005841 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005842 }
5843}
locke-lunargff255f92020-05-13 18:53:52 -06005844
5845bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5846 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5847 bool skip = false;
5848 const auto *cb_access_context = GetAccessContext(commandBuffer);
5849 assert(cb_access_context);
5850 if (!cb_access_context) return skip;
5851
5852 const auto *context = cb_access_context->GetCurrentAccessContext();
5853 assert(context);
5854 if (!context) return skip;
5855
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005856 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005857
5858 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005859 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005860 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005861 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005862 skip |=
5863 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5864 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005865 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005866 }
5867 }
5868 return skip;
5869}
5870
5871void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5872 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005873 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005874 auto *cb_access_context = GetAccessContext(commandBuffer);
5875 assert(cb_access_context);
5876 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5877 auto *context = cb_access_context->GetCurrentAccessContext();
5878 assert(context);
5879
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005880 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005881
5882 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005883 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005884 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005885 }
5886}
John Zulauf49beb112020-11-04 16:06:31 -07005887
5888bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5889 bool skip = false;
5890 const auto *cb_context = GetAccessContext(commandBuffer);
5891 assert(cb_context);
5892 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005893 const auto *access_context = cb_context->GetCurrentAccessContext();
5894 assert(access_context);
5895 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005896
John Zulaufe0757ba2022-06-10 16:51:45 -06005897 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005898 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005899}
5900
5901void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5902 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5903 auto *cb_context = GetAccessContext(commandBuffer);
5904 assert(cb_context);
5905 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005906
5907 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5908 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005909}
5910
John Zulauf4edde622021-02-15 08:54:50 -07005911bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5912 const VkDependencyInfoKHR *pDependencyInfo) const {
5913 bool skip = false;
5914 const auto *cb_context = GetAccessContext(commandBuffer);
5915 assert(cb_context);
5916 if (!cb_context || !pDependencyInfo) return skip;
5917
John Zulaufe0757ba2022-06-10 16:51:45 -06005918 const auto *access_context = cb_context->GetCurrentAccessContext();
5919 assert(access_context);
5920 if (!access_context) return skip;
5921
5922 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005923 return set_event_op.Validate(*cb_context);
5924}
5925
Tony-LunarGc43525f2021-11-15 16:12:38 -07005926bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5927 const VkDependencyInfo *pDependencyInfo) const {
5928 bool skip = false;
5929 const auto *cb_context = GetAccessContext(commandBuffer);
5930 assert(cb_context);
5931 if (!cb_context || !pDependencyInfo) return skip;
5932
John Zulaufe0757ba2022-06-10 16:51:45 -06005933 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005934 return set_event_op.Validate(*cb_context);
5935}
5936
John Zulauf4edde622021-02-15 08:54:50 -07005937void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5938 const VkDependencyInfoKHR *pDependencyInfo) {
5939 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5940 auto *cb_context = GetAccessContext(commandBuffer);
5941 assert(cb_context);
5942 if (!cb_context || !pDependencyInfo) return;
5943
John Zulaufe0757ba2022-06-10 16:51:45 -06005944 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5945 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005946}
5947
Tony-LunarGc43525f2021-11-15 16:12:38 -07005948void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5949 const VkDependencyInfo *pDependencyInfo) {
5950 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5951 auto *cb_context = GetAccessContext(commandBuffer);
5952 assert(cb_context);
5953 if (!cb_context || !pDependencyInfo) return;
5954
John Zulaufe0757ba2022-06-10 16:51:45 -06005955 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5956 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005957}
5958
John Zulauf49beb112020-11-04 16:06:31 -07005959bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5960 VkPipelineStageFlags stageMask) const {
5961 bool skip = false;
5962 const auto *cb_context = GetAccessContext(commandBuffer);
5963 assert(cb_context);
5964 if (!cb_context) return skip;
5965
John Zulauf36ef9282021-02-02 11:47:24 -07005966 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005967 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005968}
5969
5970void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5971 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5972 auto *cb_context = GetAccessContext(commandBuffer);
5973 assert(cb_context);
5974 if (!cb_context) return;
5975
John Zulauf1bf30522021-09-03 15:39:06 -06005976 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005977}
5978
John Zulauf4edde622021-02-15 08:54:50 -07005979bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5980 VkPipelineStageFlags2KHR stageMask) const {
5981 bool skip = false;
5982 const auto *cb_context = GetAccessContext(commandBuffer);
5983 assert(cb_context);
5984 if (!cb_context) return skip;
5985
5986 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5987 return reset_event_op.Validate(*cb_context);
5988}
5989
Tony-LunarGa2662db2021-11-16 07:26:24 -07005990bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5991 VkPipelineStageFlags2 stageMask) const {
5992 bool skip = false;
5993 const auto *cb_context = GetAccessContext(commandBuffer);
5994 assert(cb_context);
5995 if (!cb_context) return skip;
5996
5997 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5998 return reset_event_op.Validate(*cb_context);
5999}
6000
John Zulauf4edde622021-02-15 08:54:50 -07006001void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
6002 VkPipelineStageFlags2KHR stageMask) {
6003 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
6004 auto *cb_context = GetAccessContext(commandBuffer);
6005 assert(cb_context);
6006 if (!cb_context) return;
6007
John Zulauf1bf30522021-09-03 15:39:06 -06006008 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07006009}
6010
Tony-LunarGa2662db2021-11-16 07:26:24 -07006011void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
6012 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
6013 auto *cb_context = GetAccessContext(commandBuffer);
6014 assert(cb_context);
6015 if (!cb_context) return;
6016
6017 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
6018}
6019
John Zulauf49beb112020-11-04 16:06:31 -07006020bool SyncValidator::PreCallValidateCmdWaitEvents(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) const {
6027 bool skip = false;
6028 const auto *cb_context = GetAccessContext(commandBuffer);
6029 assert(cb_context);
6030 if (!cb_context) return skip;
6031
John Zulauf36ef9282021-02-02 11:47:24 -07006032 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
6033 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
6034 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07006035 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07006036}
6037
6038void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6039 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6040 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6041 uint32_t bufferMemoryBarrierCount,
6042 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6043 uint32_t imageMemoryBarrierCount,
6044 const VkImageMemoryBarrier *pImageMemoryBarriers) {
6045 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
6046 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
6047 imageMemoryBarrierCount, pImageMemoryBarriers);
6048
6049 auto *cb_context = GetAccessContext(commandBuffer);
6050 assert(cb_context);
6051 if (!cb_context) return;
6052
John Zulauf1bf30522021-09-03 15:39:06 -06006053 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06006054 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06006055 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07006056}
6057
John Zulauf4edde622021-02-15 08:54:50 -07006058bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6059 const VkDependencyInfoKHR *pDependencyInfos) const {
6060 bool skip = false;
6061 const auto *cb_context = GetAccessContext(commandBuffer);
6062 assert(cb_context);
6063 if (!cb_context) return skip;
6064
6065 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6066 skip |= wait_events_op.Validate(*cb_context);
6067 return skip;
6068}
6069
6070void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6071 const VkDependencyInfoKHR *pDependencyInfos) {
6072 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6073
6074 auto *cb_context = GetAccessContext(commandBuffer);
6075 assert(cb_context);
6076 if (!cb_context) return;
6077
John Zulauf1bf30522021-09-03 15:39:06 -06006078 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6079 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006080}
6081
Tony-LunarG1364cf52021-11-17 16:10:11 -07006082bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6083 const VkDependencyInfo *pDependencyInfos) const {
6084 bool skip = false;
6085 const auto *cb_context = GetAccessContext(commandBuffer);
6086 assert(cb_context);
6087 if (!cb_context) return skip;
6088
6089 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6090 skip |= wait_events_op.Validate(*cb_context);
6091 return skip;
6092}
6093
6094void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6095 const VkDependencyInfo *pDependencyInfos) {
6096 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6097
6098 auto *cb_context = GetAccessContext(commandBuffer);
6099 assert(cb_context);
6100 if (!cb_context) return;
6101
6102 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6103 pDependencyInfos);
6104}
6105
John Zulauf4a6105a2020-11-17 15:11:05 -07006106void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006107 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006108 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006109 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006110}
6111
6112// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006113SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006114 IgnoreReason reason = NotIgnored;
6115
sjfricke0bea06e2022-06-05 09:22:26 +09006116 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006117 reason = SetVsWait2;
6118 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6119 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006120 } else if (unsynchronized_set) {
6121 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006122 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006123 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006124 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006125 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006126 } else {
6127 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006128 }
6129
6130 return reason;
6131}
6132
Jeremy Gebben40a22942020-12-22 14:22:06 -07006133bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006134 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6135 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6136 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006137}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006138
sjfricke0bea06e2022-06-05 09:22:26 +09006139SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006140 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6141 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006142 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6143 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6144 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006145 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006146 auto &barrier_set = barriers_[0];
6147 barrier_set.dependency_flags = dependencyFlags;
6148 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6149 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006150 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006151 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6152 pMemoryBarriers);
6153 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6154 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6155 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6156 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006157}
6158
sjfricke0bea06e2022-06-05 09:22:26 +09006159SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006160 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006161 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006162 for (uint32_t i = 0; i < event_count; i++) {
6163 const auto &dep_info = dep_infos[i];
6164 auto &barrier_set = barriers_[i];
6165 barrier_set.dependency_flags = dep_info.dependencyFlags;
6166 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6167 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6168 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6169 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6170 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6171 dep_info.pMemoryBarriers);
6172 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6173 dep_info.pBufferMemoryBarriers);
6174 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6175 dep_info.pImageMemoryBarriers);
6176 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006177}
6178
sjfricke0bea06e2022-06-05 09:22:26 +09006179SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006180 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6181 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6182 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6183 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6184 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006185 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6186 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6187 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006188
sjfricke0bea06e2022-06-05 09:22:26 +09006189SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006190 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006191 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006192
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006193bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6194 bool skip = false;
6195 const auto *context = cb_context.GetCurrentAccessContext();
6196 assert(context);
6197 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006198 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6199
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006200 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006201 const auto &barrier_set = barriers_[0];
6202 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6203 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6204 const auto *image_state = image_barrier.image.get();
6205 if (!image_state) continue;
6206 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6207 if (hazard.hazard) {
6208 // PHASE1 TODO -- add tag information to log msg when useful.
6209 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006210 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006211 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6212 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6213 string_SyncHazard(hazard.hazard), image_barrier.index,
6214 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006215 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006216 }
6217 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006218 return skip;
6219}
6220
John Zulaufd5115702021-01-18 12:34:33 -07006221struct SyncOpPipelineBarrierFunctorFactory {
6222 using BarrierOpFunctor = PipelineBarrierOp;
6223 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6224 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6225 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6226 using BufferRange = ResourceAccessRange;
6227 using ImageRange = subresource_adapter::ImageRangeGenerator;
6228 using GlobalRange = ResourceAccessRange;
6229
John Zulauf00119522022-05-23 19:07:42 -06006230 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6231 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006232 }
John Zulauf14940722021-04-12 15:19:02 -06006233 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006234 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6235 }
John Zulauf00119522022-05-23 19:07:42 -06006236 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6237 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006238 }
6239
6240 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6241 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6242 const auto base_address = ResourceBaseAddress(buffer);
6243 return (range + base_address);
6244 }
John Zulauf110413c2021-03-20 05:38:38 -06006245 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006246 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006247
6248 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006249 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006250 return range_gen;
6251 }
6252 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6253};
6254
6255template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006256void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6257 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006258 for (const auto &barrier : barriers) {
6259 const auto *state = barrier.GetState();
6260 if (state) {
6261 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006262 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006263 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6264 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6265 }
6266 }
6267}
6268
6269template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006270void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6271 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006272 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6273 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006274 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006275 }
6276 for (const auto address_type : kAddressTypes) {
6277 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6278 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6279 }
6280}
6281
John Zulaufdab327f2022-07-08 12:02:05 -06006282ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006283 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006284 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006285 return tag;
6286}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006287
John Zulauf0223f142022-07-06 09:05:39 -06006288void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006289 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006290 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6291 assert(barriers_.size() == 1);
6292 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006293 if (!exec_context.ValidForSyncOps()) return;
6294
6295 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6296 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6297 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006298 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6299 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6300 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006301 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006302 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006303 } else {
6304 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006305 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006306 }
6307 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006308}
6309
John Zulauf8eda1562021-04-13 17:06:41 -06006310bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006311 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006312 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6313 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006314 return false;
6315}
6316
John Zulauf4edde622021-02-15 08:54:50 -07006317void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6318 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6319 const VkMemoryBarrier *barriers) {
6320 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006321 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006322 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006323 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006324 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006325 }
6326 if (0 == memory_barrier_count) {
6327 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006328 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006329 }
John Zulauf4edde622021-02-15 08:54:50 -07006330 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006331}
6332
John Zulauf4edde622021-02-15 08:54:50 -07006333void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6334 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6335 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6336 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006337 for (uint32_t index = 0; index < barrier_count; index++) {
6338 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006339 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006340 if (buffer) {
6341 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6342 const auto range = MakeRange(barrier.offset, barrier_size);
6343 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006344 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006345 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006346 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006347 }
6348 }
6349}
6350
John Zulauf4edde622021-02-15 08:54:50 -07006351void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006352 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006353 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006354 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006355 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006356 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6357 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6358 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006359 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006360 }
John Zulauf4edde622021-02-15 08:54:50 -07006361 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006362}
6363
John Zulauf4edde622021-02-15 08:54:50 -07006364void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6365 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006366 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006367 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006368 for (uint32_t index = 0; index < barrier_count; index++) {
6369 const auto &barrier = barriers[index];
6370 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6371 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006372 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006373 if (buffer) {
6374 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6375 const auto range = MakeRange(barrier.offset, barrier_size);
6376 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006377 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006378 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006379 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006380 }
6381 }
6382}
6383
John Zulauf4edde622021-02-15 08:54:50 -07006384void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6385 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6386 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6387 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006388 for (uint32_t index = 0; index < barrier_count; index++) {
6389 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006390 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006391 if (image) {
6392 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6393 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006394 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006395 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006396 image_memory_barriers.emplace_back();
6397 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006398 }
6399 }
6400}
John Zulaufd5115702021-01-18 12:34:33 -07006401
John Zulauf4edde622021-02-15 08:54:50 -07006402void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6403 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006404 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006405 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006406 for (uint32_t index = 0; index < barrier_count; index++) {
6407 const auto &barrier = barriers[index];
6408 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6409 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006410 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006411 if (image) {
6412 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6413 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006414 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006415 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006416 image_memory_barriers.emplace_back();
6417 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006418 }
6419 }
6420}
6421
sjfricke0bea06e2022-06-05 09:22:26 +09006422SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6423 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6424 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6425 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6426 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6427 const VkImageMemoryBarrier *pImageMemoryBarriers)
6428 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006429 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6430 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006431 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006432}
6433
sjfricke0bea06e2022-06-05 09:22:26 +09006434SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6435 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6436 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006437 MakeEventsList(sync_state, eventCount, pEvents);
6438 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6439}
6440
John Zulauf610e28c2021-08-03 17:46:23 -06006441const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6442
John Zulaufd5115702021-01-18 12:34:33 -07006443bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006444 bool skip = false;
6445 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006446 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006447
John Zulauf610e28c2021-08-03 17:46:23 -06006448 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006449 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6450 const auto &barrier_set = barriers_[barrier_set_index];
6451 if (barrier_set.single_exec_scope) {
6452 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6453 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6454 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6455 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6456 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6457 } else {
6458 const auto &barriers = barrier_set.memory_barriers;
6459 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6460 const auto &barrier = barriers[barrier_index];
6461 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6462 const std::string vuid =
6463 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6464 skip =
6465 sync_state.LogInfo(command_buffer_handle, vuid,
6466 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6467 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6468 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6469 }
6470 }
6471 }
6472 }
John Zulaufd5115702021-01-18 12:34:33 -07006473 }
6474
John Zulauf610e28c2021-08-03 17:46:23 -06006475 // The rest is common to record time and replay time.
6476 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6477 return skip;
6478}
6479
John Zulaufbb890452021-12-14 11:30:18 -07006480bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006481 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006482 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006483 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006484
Jeremy Gebben40a22942020-12-22 14:22:06 -07006485 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006486 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006487 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006488 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006489 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006490 size_t barrier_set_index = 0;
6491 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006492 for (const auto &event : events_) {
6493 const auto *sync_event = events_context->Get(event.get());
6494 const auto &barrier_set = barriers_[barrier_set_index];
6495 if (!sync_event) {
6496 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6497 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6498 // new validation error... wait without previously submitted set event...
6499 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 -07006500 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006501 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006502 }
John Zulauf610e28c2021-08-03 17:46:23 -06006503
6504 // For replay calls, don't revalidate "same command buffer" events
6505 if (sync_event->last_command_tag > base_tag) continue;
6506
John Zulauf78394fc2021-07-12 15:41:40 -06006507 const auto event_handle = sync_event->event->event();
6508 // TODO add "destroyed" checks
6509
John Zulaufe0757ba2022-06-10 16:51:45 -06006510 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006511 // Only accumulate barrier and event stages if there is a pending set in the current context
6512 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6513 event_stage_masks |= sync_event->scope.mask_param;
6514 }
6515
John Zulauf78394fc2021-07-12 15:41:40 -06006516 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006517
sjfricke0bea06e2022-06-05 09:22:26 +09006518 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006519 if (ignore_reason) {
6520 switch (ignore_reason) {
6521 case SyncEventState::ResetWaitRace:
6522 case SyncEventState::Reset2WaitRace: {
6523 // Four permuations of Reset and Wait calls...
6524 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006525 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006526 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006527 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6528 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006529 }
6530 const char *const message =
6531 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6532 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6533 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006534 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006535 break;
6536 }
6537 case SyncEventState::SetRace: {
6538 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6539 // this event
6540 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6541 const char *const message =
6542 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6543 const char *const reason = "First synchronization scope is undefined.";
6544 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6545 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006546 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006547 break;
6548 }
6549 case SyncEventState::MissingStageBits: {
6550 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6551 // Issue error message that event waited for is not in wait events scope
6552 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6553 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6554 ". Bits missing from srcStageMask %s. %s";
6555 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6556 sync_state.report_data->FormatHandle(event_handle).c_str(),
6557 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006558 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006559 break;
6560 }
6561 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006562 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006563 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6564 sync_state.report_data->FormatHandle(event_handle).c_str(),
6565 CommandTypeString(sync_event->last_command));
6566 break;
6567 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006568 case SyncEventState::MissingSetEvent: {
6569 // TODO: There are conditions at queue submit time where we can definitively say that
6570 // a missing set event is an error. Add those if not captured in CoreChecks
6571 break;
6572 }
John Zulauf78394fc2021-07-12 15:41:40 -06006573 default:
6574 assert(ignore_reason == SyncEventState::NotIgnored);
6575 }
6576 } else if (barrier_set.image_memory_barriers.size()) {
6577 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006578 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006579 assert(context);
6580 for (const auto &image_memory_barrier : image_memory_barriers) {
6581 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6582 const auto *image_state = image_memory_barrier.image.get();
6583 if (!image_state) continue;
6584 const auto &subresource_range = image_memory_barrier.range;
6585 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006586 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6587 src_access_scope, queue_id, *sync_event,
6588 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006589 if (hazard.hazard) {
6590 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6591 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6592 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6593 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006594 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006595 break;
6596 }
6597 }
6598 }
6599 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6600 // 03839
6601 barrier_set_index += barrier_set_incr;
6602 }
John Zulaufd5115702021-01-18 12:34:33 -07006603
6604 // 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 -07006605 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 -07006606 if (extra_stage_bits) {
6607 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006608 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6609 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006610 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006611 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006612 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006613 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006614 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006615 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006616 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006617 " vkCmdSetEvent may be in previously submitted command buffer.");
6618 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006619 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006620 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006621 }
6622 }
6623 return skip;
6624}
6625
6626struct SyncOpWaitEventsFunctorFactory {
6627 using BarrierOpFunctor = WaitEventBarrierOp;
6628 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6629 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6630 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6631 using BufferRange = EventSimpleRangeGenerator;
6632 using ImageRange = EventImageRangeGenerator;
6633 using GlobalRange = EventSimpleRangeGenerator;
6634
6635 // Need to restrict to only valid exec and access scope for this event
6636 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6637 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006638 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006639 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6640 return barrier;
6641 }
John Zulauf00119522022-05-23 19:07:42 -06006642 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006643 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006644 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006645 }
John Zulauf14940722021-04-12 15:19:02 -06006646 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006647 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6648 }
John Zulauf00119522022-05-23 19:07:42 -06006649 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006650 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006651 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006652 }
6653
6654 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6655 const AccessAddressType address_type = GetAccessAddressType(buffer);
6656 const auto base_address = ResourceBaseAddress(buffer);
6657 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6658 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6659 return filtered_range_gen;
6660 }
John Zulauf110413c2021-03-20 05:38:38 -06006661 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006662 if (!SimpleBinding(image)) return ImageRange();
6663 const auto address_type = GetAccessAddressType(image);
6664 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006665 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6666 false);
John Zulaufd5115702021-01-18 12:34:33 -07006667 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6668
6669 return filtered_range_gen;
6670 }
6671 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6672 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6673 }
6674 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6675 SyncEventState *sync_event;
6676};
6677
John Zulaufdab327f2022-07-08 12:02:05 -06006678ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006679 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006680
John Zulauf0223f142022-07-06 09:05:39 -06006681 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006682 return tag;
6683}
6684
John Zulauf0223f142022-07-06 09:05:39 -06006685void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006686 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6687 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6688 // 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 -06006689 if (!exec_context.ValidForSyncOps()) return;
6690 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6691 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6692 const QueueId queue_id = exec_context.GetQueueId();
6693
John Zulaufd5115702021-01-18 12:34:33 -07006694 access_context->ResolvePreviousAccesses();
6695
John Zulauf4edde622021-02-15 08:54:50 -07006696 size_t barrier_set_index = 0;
6697 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6698 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006699 for (auto &event_shared : events_) {
6700 if (!event_shared.get()) continue;
6701 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006702
sjfricke0bea06e2022-06-05 09:22:26 +09006703 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006704 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006705
John Zulauf4edde622021-02-15 08:54:50 -07006706 const auto &barrier_set = barriers_[barrier_set_index];
6707 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006708 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006709 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6710 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6711 // of the barriers is maintained.
6712 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006713 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6714 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6715 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006716
6717 // Apply the global barrier to the event itself (for race condition tracking)
6718 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6719 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6720 sync_event->barriers |= dst.exec_scope;
6721 } else {
6722 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6723 sync_event->barriers = 0U;
6724 }
John Zulauf4edde622021-02-15 08:54:50 -07006725 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006726 }
6727
6728 // Apply the pending barriers
6729 ResolvePendingBarrierFunctor apply_pending_action(tag);
6730 access_context->ApplyToContext(apply_pending_action);
6731}
6732
John Zulauf8eda1562021-04-13 17:06:41 -06006733bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006734 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6735 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006736}
6737
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006738bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6739 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6740 bool skip = false;
6741 const auto *cb_access_context = GetAccessContext(commandBuffer);
6742 assert(cb_access_context);
6743 if (!cb_access_context) return skip;
6744
6745 const auto *context = cb_access_context->GetCurrentAccessContext();
6746 assert(context);
6747 if (!context) return skip;
6748
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006749 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006750
6751 if (dst_buffer) {
6752 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6753 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6754 if (hazard.hazard) {
6755 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6756 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6757 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006758 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006759 }
6760 }
6761 return skip;
6762}
6763
John Zulauf669dfd52021-01-27 17:15:28 -07006764void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006765 events_.reserve(event_count);
6766 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006767 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006768 }
6769}
John Zulauf6ce24372021-01-30 05:56:25 -07006770
sjfricke0bea06e2022-06-05 09:22:26 +09006771SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006772 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006773 : SyncOpBase(cmd_type),
6774 event_(sync_state.Get<EVENT_STATE>(event)),
6775 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006776
John Zulauf1bf30522021-09-03 15:39:06 -06006777bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6778 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6779}
6780
John Zulaufbb890452021-12-14 11:30:18 -07006781bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6782 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006783 assert(events_context);
6784 bool skip = false;
6785 if (!events_context) return skip;
6786
John Zulaufbb890452021-12-14 11:30:18 -07006787 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006788 const auto *sync_event = events_context->Get(event_);
6789 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6790
John Zulauf1bf30522021-09-03 15:39:06 -06006791 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6792
John Zulauf6ce24372021-01-30 05:56:25 -07006793 const char *const set_wait =
6794 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6795 "hazards.";
6796 const char *message = set_wait; // Only one message this call.
6797 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6798 const char *vuid = nullptr;
6799 switch (sync_event->last_command) {
6800 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006801 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006802 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006803 // Needs a barrier between set and reset
6804 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6805 break;
John Zulauf4edde622021-02-15 08:54:50 -07006806 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006807 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006808 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006809 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6810 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6811 break;
6812 }
6813 default:
6814 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006815 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6816 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006817 break;
6818 }
6819 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006820 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6821 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006822 CommandTypeString(sync_event->last_command));
6823 }
6824 }
6825 return skip;
6826}
6827
John Zulaufdab327f2022-07-08 12:02:05 -06006828ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006829 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006830 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006831 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006832}
6833
John Zulauf8eda1562021-04-13 17:06:41 -06006834bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006835 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6836 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006837}
6838
John Zulauf0223f142022-07-06 09:05:39 -06006839void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6840 if (!exec_context.ValidForSyncOps()) return;
6841 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6842
John Zulaufe0757ba2022-06-10 16:51:45 -06006843 auto *sync_event = events_context->GetFromShared(event_);
6844 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6845
6846 // Update the event state
6847 sync_event->last_command = cmd_type_;
6848 sync_event->last_command_tag = tag;
6849 sync_event->unsynchronized_set = CMD_NONE;
6850 sync_event->ResetFirstScope();
6851 sync_event->barriers = 0U;
6852}
John Zulauf8eda1562021-04-13 17:06:41 -06006853
sjfricke0bea06e2022-06-05 09:22:26 +09006854SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006855 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006856 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006857 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006858 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006859 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006860 dep_info_() {
6861 // Snapshot the current access_context for later inspection at wait time.
6862 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6863 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6864 // or Submit time reference.
6865 if (access_context) {
6866 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6867 }
6868}
John Zulauf4edde622021-02-15 08:54:50 -07006869
sjfricke0bea06e2022-06-05 09:22:26 +09006870SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006871 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006872 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006873 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006874 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006875 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006876 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6877 if (access_context) {
6878 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6879 }
6880}
John Zulauf6ce24372021-01-30 05:56:25 -07006881
6882bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006883 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6884}
6885bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006886 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6887 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006888}
6889
John Zulaufbb890452021-12-14 11:30:18 -07006890bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006891 bool skip = false;
6892
John Zulaufbb890452021-12-14 11:30:18 -07006893 const auto &sync_state = exec_context.GetSyncState();
6894 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006895 assert(events_context);
6896 if (!events_context) return skip;
6897
6898 const auto *sync_event = events_context->Get(event_);
6899 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6900
John Zulauf610e28c2021-08-03 17:46:23 -06006901 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6902
John Zulauf6ce24372021-01-30 05:56:25 -07006903 const char *const reset_set =
6904 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6905 "hazards.";
6906 const char *const wait =
6907 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6908
6909 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006910 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006911 const char *message = nullptr;
6912 switch (sync_event->last_command) {
6913 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006914 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006915 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006916 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006917 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006918 message = reset_set;
6919 break;
6920 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006921 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006922 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006923 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006924 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006925 message = reset_set;
6926 break;
6927 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006928 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006929 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006930 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006931 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006932 message = wait;
6933 break;
6934 default:
6935 // The only other valid last command that wasn't one.
6936 assert(sync_event->last_command == CMD_NONE);
6937 break;
6938 }
John Zulauf4edde622021-02-15 08:54:50 -07006939 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006940 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006941 std::string vuid("SYNC-");
6942 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006943 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6944 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006945 CommandTypeString(sync_event->last_command));
6946 }
6947 }
6948
6949 return skip;
6950}
6951
John Zulaufdab327f2022-07-08 12:02:05 -06006952ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09006953 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006954 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006955 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006956 assert(recorded_context_);
6957 if (recorded_context_ && events_context) {
6958 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006959 }
6960 return tag;
6961}
John Zulauf6ce24372021-01-30 05:56:25 -07006962
John Zulauf0223f142022-07-06 09:05:39 -06006963void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006964 // Create a copy of the current context, and merge in the state snapshot at record set event time
6965 // 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 -06006966 if (!exec_context.ValidForSyncOps()) return;
6967 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6968 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6969 const QueueId queue_id = exec_context.GetQueueId();
6970
John Zulaufe0757ba2022-06-10 16:51:45 -06006971 auto merged_context = std::make_shared<AccessContext>(*access_context);
6972 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6973 DoRecord(queue_id, tag, merged_context, events_context);
6974}
6975
6976void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6977 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006978 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006979 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006980
6981 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6982 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6983 // any issues caused by naive scope setting here.
6984
6985 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6986 // Given:
6987 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6988 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6989
6990 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6991 sync_event->unsynchronized_set = sync_event->last_command;
6992 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006993 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006994 // We only set the scope if there isn't one
6995 sync_event->scope = src_exec_scope_;
6996
John Zulaufe0757ba2022-06-10 16:51:45 -06006997 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6998 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006999 sync_event->unsynchronized_set = CMD_NONE;
7000 sync_event->first_scope_tag = tag;
7001 }
John Zulauf4edde622021-02-15 08:54:50 -07007002 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09007003 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06007004 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07007005 sync_event->barriers = 0U;
7006}
John Zulauf64ffe552021-02-06 10:25:07 -07007007
sjfricke0bea06e2022-06-05 09:22:26 +09007008SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07007009 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07007010 const VkSubpassBeginInfo *pSubpassBeginInfo)
John Zulaufdab327f2022-07-08 12:02:05 -06007011 : SyncOpBase(cmd_type), rp_context_(nullptr) {
John Zulauf64ffe552021-02-06 10:25:07 -07007012 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06007013 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07007014 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007015 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07007016 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06007017 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07007018 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
7019 // Note that this a safe to presist as long as shared_attachments is not cleared
7020 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08007021 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07007022 attachments_.emplace_back(attachment.get());
7023 }
7024 }
7025 if (pSubpassBeginInfo) {
7026 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
7027 }
7028 }
7029}
7030
7031bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7032 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
7033 bool skip = false;
7034
7035 assert(rp_state_.get());
7036 if (nullptr == rp_state_.get()) return skip;
7037 auto &rp_state = *rp_state_.get();
7038
7039 const uint32_t subpass = 0;
7040
7041 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
7042 // hasn't happened yet)
7043 const std::vector<AccessContext> empty_context_vector;
7044 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
7045 cb_context.GetCurrentAccessContext());
7046
7047 // Validate attachment operations
7048 if (attachments_.size() == 0) return skip;
7049 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07007050
7051 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
7052 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
7053 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
7054 // operations (though it's currently a messy approach)
7055 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09007056 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007057
7058 // Validate load operations if there were no layout transition hazards
7059 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06007060 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09007061 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007062 }
7063
7064 return skip;
7065}
7066
John Zulaufdab327f2022-07-08 12:02:05 -06007067ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) {
John Zulauf64ffe552021-02-06 10:25:07 -07007068 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09007069 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
John Zulaufdab327f2022-07-08 12:02:05 -06007070 const ResourceUsageTag begin_tag =
7071 cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
7072
7073 // Note: this state update must be after RecordBeginRenderPass as there is no current render pass until that function runs
7074 rp_context_ = cb_context->GetCurrentRenderPassContext();
7075
7076 return begin_tag;
John Zulauf64ffe552021-02-06 10:25:07 -07007077}
7078
John Zulauf8eda1562021-04-13 17:06:41 -06007079bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007080 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007081 return false;
7082}
7083
John Zulaufdab327f2022-07-08 12:02:05 -06007084void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7085 // Need to update the exec_contexts state (which for RenderPass operations *must* be a QueueBatchContext, as
7086 // render pass operations are not allowed in secondary command buffers.
7087 const QueueId queue_id = exec_context.GetQueueId();
7088 assert(queue_id != QueueSyncState::kQueueIdInvalid); // Renderpass replay only valid at submit (not exec) time
7089 if (queue_id == QueueSyncState::kQueueIdInvalid) return;
7090
7091 exec_context.BeginRenderPassReplay(*this, tag);
7092}
John Zulauf8eda1562021-04-13 17:06:41 -06007093
sjfricke0bea06e2022-06-05 09:22:26 +09007094SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7095 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7096 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007097 if (pSubpassBeginInfo) {
7098 subpass_begin_info_.initialize(pSubpassBeginInfo);
7099 }
7100 if (pSubpassEndInfo) {
7101 subpass_end_info_.initialize(pSubpassEndInfo);
7102 }
7103}
7104
7105bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7106 bool skip = false;
7107 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7108 if (!renderpass_context) return skip;
7109
sjfricke0bea06e2022-06-05 09:22:26 +09007110 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007111 return skip;
7112}
7113
John Zulaufdab327f2022-07-08 12:02:05 -06007114ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007115 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007116}
7117
7118bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007119 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007120 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007121}
7122
sjfricke0bea06e2022-06-05 09:22:26 +09007123SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7124 const VkSubpassEndInfo *pSubpassEndInfo)
7125 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007126 if (pSubpassEndInfo) {
7127 subpass_end_info_.initialize(pSubpassEndInfo);
7128 }
7129}
7130
John Zulaufdab327f2022-07-08 12:02:05 -06007131void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7132 exec_context.NextSubpassReplay();
7133}
John Zulauf8eda1562021-04-13 17:06:41 -06007134
John Zulauf64ffe552021-02-06 10:25:07 -07007135bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7136 bool skip = false;
7137 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7138
7139 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007140 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007141 return skip;
7142}
7143
John Zulaufdab327f2022-07-08 12:02:05 -06007144ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09007145 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007146}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007147
John Zulauf8eda1562021-04-13 17:06:41 -06007148bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007149 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007150 return false;
7151}
7152
John Zulaufdab327f2022-07-08 12:02:05 -06007153void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
7154 exec_context.EndRenderPassReplay();
7155}
John Zulauf8eda1562021-04-13 17:06:41 -06007156
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007157void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7158 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7159 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7160 auto *cb_access_context = GetAccessContext(commandBuffer);
7161 assert(cb_access_context);
7162 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7163 auto *context = cb_access_context->GetCurrentAccessContext();
7164 assert(context);
7165
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007166 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007167
7168 if (dst_buffer) {
7169 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7170 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7171 }
7172}
John Zulaufd05c5842021-03-26 11:32:16 -06007173
John Zulaufae842002021-04-15 18:20:55 -06007174bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7175 const VkCommandBuffer *pCommandBuffers) const {
7176 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007177 const auto *cb_context = GetAccessContext(commandBuffer);
7178 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007179
7180 // Heavyweight, but we need a proxy copy of the active command buffer access context
7181 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007182
7183 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007184 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007185 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7186
John Zulaufae842002021-04-15 18:20:55 -06007187 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7188 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007189
7190 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7191 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007192 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007193
7194 // The barriers have already been applied in ValidatFirstUse
7195 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007196 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007197 }
7198
John Zulaufae842002021-04-15 18:20:55 -06007199 return skip;
7200}
7201
7202void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7203 const VkCommandBuffer *pCommandBuffers) {
7204 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007205 auto *cb_context = GetAccessContext(commandBuffer);
7206 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007207 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007208 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007209 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7210 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007211 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007212 }
John Zulaufae842002021-04-15 18:20:55 -06007213}
7214
John Zulauf1d5f9c12022-05-13 14:51:08 -06007215void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7216 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7217 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7218
7219 const auto queue_state = GetQueueSyncStateShared(queue);
7220 if (!queue_state) return; // Invalid queue
7221 QueueId waited_queue = queue_state->GetQueueId();
John Zulauf3da08bb2022-08-01 17:56:56 -06007222 ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007223
John Zulauf3da08bb2022-08-01 17:56:56 -06007224 // Eliminate waitable fences from the current queue.
7225 layer_data::EraseIf(waitable_fences_, [waited_queue](const SignaledFence &sf) { return sf.second.queue_id == waited_queue; });
John Zulauf1d5f9c12022-05-13 14:51:08 -06007226}
7227
7228void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7229 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007230
7231 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7232 for (auto &batch : queue_batch_contexts) {
7233 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007234 }
7235
John Zulauf3da08bb2022-08-01 17:56:56 -06007236 // As we we've waited for everything on device, any waits are mooted.
7237 waitable_fences_.clear();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007238}
7239
John Zulauf697c0e12022-04-19 16:31:12 -06007240struct QueueSubmitCmdState {
7241 std::shared_ptr<const QueueSyncState> queue;
7242 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007243 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007244 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007245 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7246 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007247};
7248
7249template <>
7250thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7251
John Zulaufbbda4572022-04-19 16:20:45 -06007252bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7253 VkFence fence) const {
7254 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007255
7256 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007257 if (!enabled[sync_validation_queue_submit]) return skip;
7258
John Zulauf00119522022-05-23 19:07:42 -06007259 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007260 const auto fence_state = Get<FENCE_STATE>(fence);
7261 cmd_state->queue = GetQueueSyncStateShared(queue);
7262 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007263
John Zulauf697c0e12022-04-19 16:31:12 -06007264 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7265 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7266
7267 // verify each submit batch
7268 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7269 // most recently created batch
7270 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7271 std::shared_ptr<QueueBatchContext> batch;
7272 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7273 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007274 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7275 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007276
John Zulaufe0757ba2022-06-10 16:51:45 -06007277 // Skip import and validation of empty batches
7278 if (batch->GetTagRange().size()) {
7279 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007280
John Zulaufe0757ba2022-06-10 16:51:45 -06007281 // For each submit in the batch...
7282 for (const auto &cb : *batch) {
7283 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
John Zulauf0223f142022-07-06 09:05:39 -06007284 skip |= cb.cb->ValidateFirstUse(*batch.get(), "vkQueueSubmit", cb.index);
John Zulaufe0757ba2022-06-10 16:51:45 -06007285
7286 // The barriers have already been applied in ValidatFirstUse
7287 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7288 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7289 }
John Zulauf697c0e12022-04-19 16:31:12 -06007290 }
7291
John Zulaufe0757ba2022-06-10 16:51:45 -06007292 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007293 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7294 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007295 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007296 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007297 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7298 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7299 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007300 }
7301 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7302 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7303 last_batch = batch;
7304 }
7305 // The most recently created batch will become the queue's "last batch" in the record phase
7306 if (batch) {
7307 cmd_state->last_batch = std::move(batch);
7308 }
7309
7310 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007311 return skip;
7312}
7313
7314void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7315 VkResult result) {
7316 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007317
John Zulaufcb7e1672022-05-04 13:46:08 -06007318 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007319 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7320
John Zulaufcb7e1672022-05-04 13:46:08 -06007321 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7322 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007323 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007324
7325 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007326 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7327
John Zulauf697c0e12022-04-19 16:31:12 -06007328 // Don't need to look up the queue state again, but we need a non-const version
7329 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007330
John Zulaufcb7e1672022-05-04 13:46:08 -06007331 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7332 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7333 // QBC's are those referenced by unwaited signals and the last batch.
7334 for (auto &sig_sem : cmd_state->signaled) {
7335 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007336 auto &sig_batch = sig_sem.second->batch;
7337 sig_batch->ResetAccessLog();
7338 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7339 if (sig_batch != cmd_state->last_batch) {
7340 sig_batch->ResetEventsContext();
7341 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007342 }
7343 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007344 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007345 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007346
John Zulaufcb7e1672022-05-04 13:46:08 -06007347 // Update the queue to point to the last batch from the submit
7348 if (cmd_state->last_batch) {
7349 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007350
7351 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7352 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7353 auto last_batch = queue_state->LastBatch();
7354 if (last_batch) {
7355 last_batch->ResetEventsContext();
7356 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007357 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007358 }
7359
7360 // Update the global access log from the one built during validation
7361 global_access_log_.MergeMove(std::move(cmd_state->logger));
7362
John Zulauf3da08bb2022-08-01 17:56:56 -06007363 ResourceUsageRange fence_tag_range = ReserveGlobalTagRange(1U);
7364 UpdateFenceWaitInfo(fence, queue_state->GetQueueId(), fence_tag_range.begin);
John Zulaufbbda4572022-04-19 16:20:45 -06007365}
7366
7367bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7368 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007369 bool skip = false;
7370 if (!enabled[sync_validation_queue_submit]) return skip;
7371
John Zulauf697c0e12022-04-19 16:31:12 -06007372 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007373 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007374}
7375
7376void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7377 VkFence fence, VkResult result) {
7378 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007379 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7380
7381 if (!enabled[sync_validation_queue_submit]) return;
7382
John Zulauf697c0e12022-04-19 16:31:12 -06007383 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007384}
7385
John Zulauf3da08bb2022-08-01 17:56:56 -06007386void SyncValidator::PostCallRecordGetFenceStatus(VkDevice device, VkFence fence, VkResult result) {
7387 StateTracker::PostCallRecordGetFenceStatus(device, fence, result);
7388 if (!enabled[sync_validation_queue_submit]) return;
7389 if (result == VK_SUCCESS) {
7390 // fence is signalled, mark it as waited for
7391 WaitForFence(fence);
7392 }
7393}
7394
7395void SyncValidator::PostCallRecordWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll,
7396 uint64_t timeout, VkResult result) {
7397 StateTracker::PostCallRecordWaitForFences(device, fenceCount, pFences, waitAll, timeout, result);
7398 if (!enabled[sync_validation_queue_submit]) return;
7399 if ((result == VK_SUCCESS) && ((VK_TRUE == waitAll) || (1 == fenceCount))) {
7400 // We can only know the pFences have signal if we waited for all of them, or there was only one of them
7401 for (uint32_t i = 0; i < fenceCount; i++) {
7402 WaitForFence(pFences[i]);
7403 }
7404 }
7405}
7406
John Zulaufd0ec59f2021-03-13 14:25:08 -07007407AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7408 : view_(view), view_mask_(), gen_store_() {
7409 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7410 const IMAGE_STATE &image_state = *view_->image_state.get();
7411 const auto base_address = ResourceBaseAddress(image_state);
7412 const auto *encoder = image_state.fragment_encoder.get();
7413 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007414 // Get offset and extent for the view, accounting for possible depth slicing
7415 const VkOffset3D zero_offset = view->GetOffset();
7416 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007417 // Intentional copy
7418 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7419 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007420 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7421 view->IsDepthSliced());
7422 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007423
7424 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7425 if (depth && (depth != view_mask_)) {
7426 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007427 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007428 }
7429 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7430 if (stencil && (stencil != view_mask_)) {
7431 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007432 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7433 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007434 }
7435}
7436
7437const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7438 const ImageRangeGen *got = nullptr;
7439 switch (gen_type) {
7440 case kViewSubresource:
7441 got = &gen_store_[kViewSubresource];
7442 break;
7443 case kRenderArea:
7444 got = &gen_store_[kRenderArea];
7445 break;
7446 case kDepthOnlyRenderArea:
7447 got =
7448 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7449 break;
7450 case kStencilOnlyRenderArea:
7451 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7452 : &gen_store_[Gen::kStencilOnlyRenderArea];
7453 break;
7454 default:
7455 assert(got);
7456 }
7457 return got;
7458}
7459
7460AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7461 assert(IsValid());
7462 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7463 if (depth_op) {
7464 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7465 if (stencil_op) {
7466 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7467 return kRenderArea;
7468 }
7469 return kDepthOnlyRenderArea;
7470 }
7471 if (stencil_op) {
7472 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7473 return kStencilOnlyRenderArea;
7474 }
7475
7476 assert(depth_op || stencil_op);
7477 return kRenderArea;
7478}
7479
7480AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007481
John Zulaufe0757ba2022-06-10 16:51:45 -06007482void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007483 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7484 for (auto &event_pair : map_) {
7485 assert(event_pair.second); // Shouldn't be storing empty
7486 auto &sync_event = *event_pair.second;
7487 // 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 -06007488 // But only if occuring before the tag
7489 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007490 sync_event.barriers |= dst.exec_scope;
7491 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7492 }
7493 }
7494}
John Zulaufbb890452021-12-14 11:30:18 -07007495
John Zulaufe0757ba2022-06-10 16:51:45 -06007496void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7497 const SyncExecScope src_scope =
7498 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7499 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7500 ApplyBarrier(src_scope, dst_scope, tag);
7501}
7502
7503SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7504 // We need a deep copy of the const context to update during validation phase
7505 for (const auto &event : from.map_) {
7506 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7507 }
7508 return *this;
7509}
7510
John Zulaufcb7e1672022-05-04 13:46:08 -06007511QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
John Zulaufdab327f2022-07-08 12:02:05 -06007512 : CommandExecutionContext(&sync_state),
7513 queue_state_(&queue_state),
7514 tag_range_(0, 0),
7515 current_access_context_(&access_context_),
7516 batch_log_(nullptr) {}
John Zulaufcb7e1672022-05-04 13:46:08 -06007517
John Zulauf697c0e12022-04-19 16:31:12 -06007518template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007519void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7520 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007521 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007522 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007523}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007524void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007525 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007526}
John Zulauf697c0e12022-04-19 16:31:12 -06007527
7528VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7529
John Zulauf1d5f9c12022-05-13 14:51:08 -06007530void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
John Zulauf3da08bb2022-08-01 17:56:56 -06007531 ResourceAccessState::QueueTagPredicate predicate{queue_id, tag};
7532 access_context_.EraseIf([&predicate](ResourceAccessRangeMap::value_type &access) {
7533 // Apply..Wait returns true if the waited access is empty...
7534 return access.second.ApplyQueueTagWait(predicate);
7535 });
John Zulaufe0757ba2022-06-10 16:51:45 -06007536
7537 if (queue_id == GetQueueId()) {
7538 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7539 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007540}
7541
7542// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007543void QueueBatchContext::ApplyDeviceWait() {
7544 access_context_.Reset();
7545 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7546}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007547
John Zulaufdab327f2022-07-08 12:02:05 -06007548HazardResult QueueBatchContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range) {
7549 // Queue batch handling requires dealing with renderpass state and picking the correct access context
7550 if (rp_replay_) {
7551 return rp_replay_.replay_context->DetectFirstUseHazard(GetQueueId(), tag_range, *current_access_context_);
7552 }
7553 return current_replay_->GetCurrentAccessContext()->DetectFirstUseHazard(GetQueueId(), tag_range, access_context_);
7554}
7555
7556void QueueBatchContext::BeginRenderPassReplay(const SyncOpBeginRenderPass &begin_op, const ResourceUsageTag tag) {
7557 current_access_context_ = rp_replay_.Begin(GetQueueFlags(), begin_op, access_context_);
7558 current_access_context_->ResolvePreviousAccesses();
7559}
7560
7561void QueueBatchContext::NextSubpassReplay() {
7562 current_access_context_ = rp_replay_.Next();
7563 current_access_context_->ResolvePreviousAccesses();
7564}
7565
7566void QueueBatchContext::EndRenderPassReplay() {
7567 rp_replay_.End(access_context_);
7568 current_access_context_ = &access_context_;
7569}
7570
7571AccessContext *QueueBatchContext::RenderPassReplayState::Begin(VkQueueFlags queue_flags, const SyncOpBeginRenderPass &begin_op_,
7572 const AccessContext &external_context) {
7573 Reset();
7574
7575 begin_op = &begin_op_;
7576 subpass = 0;
7577
7578 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7579 assert(rp_context);
7580 replay_context = &rp_context->GetContexts()[0];
7581
7582 InitSubpassContexts(queue_flags, *rp_context->GetRenderPassState(), &external_context, subpass_contexts);
7583 return &subpass_contexts[0];
7584}
7585
7586AccessContext *QueueBatchContext::RenderPassReplayState::Next() {
7587 subpass++;
7588
7589 const RenderPassAccessContext *rp_context = begin_op->GetRenderPassAccessContext();
7590
7591 replay_context = &rp_context->GetContexts()[subpass];
7592 return &subpass_contexts[subpass];
7593}
7594
7595void QueueBatchContext::RenderPassReplayState::End(AccessContext &external_context) {
7596 external_context.ResolveChildContexts(subpass_contexts);
7597 Reset();
7598}
7599
John Zulaufecf4ac52022-06-06 10:08:42 -06007600class ApplySemaphoreBarrierAction {
7601 public:
7602 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7603 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7604
7605 private:
7606 const SemaphoreScope &signal_;
7607 const SemaphoreScope wait_;
7608};
7609
7610std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7611 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007612 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007613 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007614
John Zulaufcb7e1672022-05-04 13:46:08 -06007615 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7616 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007617 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007618
John Zulaufecf4ac52022-06-06 10:08:42 -06007619 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007620
John Zulaufecf4ac52022-06-06 10:08:42 -06007621 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007622 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007623 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7624 if (signal_scope.queue == wait_scope.queue) {
7625 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7626 // valid accesses for the sync scope.
7627 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7628 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7629 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007630 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007631 } else {
7632 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7633 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007634 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007635 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7636 // enforce deep constness.
7637 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007638}
7639
7640// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7641template <>
7642class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7643 public:
7644 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7645 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7646 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7647 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7648 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7649 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7650
7651 private:
7652 const VkSubmitInfo &info_;
7653};
7654template <typename BatchInfo, typename Fn>
7655void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7656 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7657 Accessor batch(batch_info);
7658 const uint32_t wait_count = batch.WaitSemaphoreCount();
7659 for (uint32_t i = 0; i < wait_count; ++i) {
7660 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7661 }
7662}
7663
7664template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007665void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7666 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007667 // Copy in the event state from the previous batch (on this queue)
7668 if (prev) {
7669 events_context_.DeepCopy(prev->events_context_);
7670 }
7671
John Zulaufecf4ac52022-06-06 10:08:42 -06007672 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7673 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7674 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7675 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7676 if (resolved) {
7677 batches_resolved.emplace(std::move(resolved));
7678 }
John Zulauf697c0e12022-04-19 16:31:12 -06007679 });
7680
John Zulaufecf4ac52022-06-06 10:08:42 -06007681 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7682 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7683 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007684 }
7685
John Zulauf697c0e12022-04-19 16:31:12 -06007686 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007687 async_batches_ =
7688 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7689 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007690 });
7691 for (const auto &async_batch : async_batches_) {
7692 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7693 }
7694}
7695
7696template <typename BatchInfo>
7697void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7698 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7699 Accessor batch(batch_info);
7700
7701 // Create the list of command buffers to submit
7702 const uint32_t cb_count = batch.CommandBufferCount();
7703 command_buffers_.reserve(cb_count);
7704 for (uint32_t index = 0; index < cb_count; ++index) {
7705 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7706 if (cb_context) {
7707 tag_range_.end += cb_context->GetTagLimit();
7708 command_buffers_.emplace_back(index, std::move(cb_context));
7709 }
7710 }
7711}
7712
7713// Look up the usage informaiton from the local or global logger
7714std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7715 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7716 std::stringstream out;
7717 AccessLogger::AccessRecord access = use_logger[tag];
7718 if (access.IsValid()) {
7719 const AccessLogger::BatchRecord &batch = *access.batch;
7720 const ResourceUsageRecord &record = *access.record;
7721 // Queue and Batch information
7722 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7723 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7724
7725 // Commandbuffer Usages Information
7726 out << record;
7727 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7728 out << ", reset_no: " << std::to_string(record.reset_count);
7729 }
7730 return out.str();
7731}
7732
7733VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7734
John Zulauf00119522022-05-23 19:07:42 -06007735QueueId QueueBatchContext::GetQueueId() const {
7736 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7737 return id;
7738}
7739
John Zulauf697c0e12022-04-19 16:31:12 -06007740void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7741 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7742 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7743 SetTagBias(global_tags.begin);
7744 // Add an access log for the batches range and point the batch at it.
7745 logger_ = &logger;
7746 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7747}
7748
7749void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7750 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7751 batch_log_->Append(submitted_cb.GetAccessLog());
7752}
7753
7754void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7755 const auto size = tag_range_.size();
7756 tag_range_.begin = bias;
7757 tag_range_.end = bias + size;
7758 access_context_.SetStartTag(bias);
7759}
7760
John Zulauf697c0e12022-04-19 16:31:12 -06007761AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7762 const ResourceUsageRange &range) {
7763 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7764 assert(inserted.second);
7765 return &inserted.first->second;
7766}
7767
7768void AccessLogger::MergeMove(AccessLogger &&child) {
7769 for (auto &range : child.access_log_map_) {
7770 BatchLog &child_batch = range.second;
7771 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7772 insert_pair.first->second = std::move(child_batch);
7773 assert(insert_pair.second);
7774 }
7775 child.Reset();
7776}
7777
7778void AccessLogger::Reset() {
7779 prev_ = nullptr;
7780 access_log_map_.clear();
7781}
7782
7783// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7784// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7785// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7786// the contexts Resolve all history from previous all contexts when created
7787void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7788 last_batch_ = std::move(last);
7789 last_batch_->ResetAccessLog();
7790}
7791
7792// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7793// scope state.
7794// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7795// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7796uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7797
7798void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7799 log_.insert(log_.end(), other.cbegin(), other.cend());
7800 for (const auto &record : other) {
7801 assert(record.cb_state);
7802 cbs_referenced_.insert(record.cb_state->shared_from_this());
7803 }
7804}
7805
7806AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7807 assert(index < log_.size());
7808 return AccessRecord{&batch_, &log_[index]};
7809}
7810
7811AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7812 AccessRecord access_record = {nullptr, nullptr};
7813
7814 auto found_range = access_log_map_.find(tag);
7815 if (found_range != access_log_map_.cend()) {
7816 const ResourceUsageTag bias = found_range->first.begin;
7817 assert(tag >= bias);
7818 access_record = found_range->second[tag - bias];
7819 } else if (prev_) {
7820 access_record = (*prev_)[tag];
7821 }
7822
7823 return access_record;
7824}
John Zulaufcb7e1672022-05-04 13:46:08 -06007825
John Zulaufecf4ac52022-06-06 10:08:42 -06007826// This is a const method, force the returned value to be const
7827std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007828 std::shared_ptr<Signal> prev_state;
7829 if (prev_) {
7830 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7831 }
7832 return prev_state;
7833}
John Zulaufecf4ac52022-06-06 10:08:42 -06007834
7835SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7836 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7837 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7838 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7839 assert(batch);
7840 assert(sem_state);
7841}
John Zulauf3da08bb2022-08-01 17:56:56 -06007842
7843FenceSyncState::FenceSyncState() : fence(), tag(kInvalidTag), queue_id(QueueSyncState::kQueueIdInvalid) {}