blob: bb4ef9fabc9bb13ca0d658e056fdbcabca78259a [file] [log] [blame]
Jeremy Gebben610d3a62022-01-01 12:53:17 -07001/* Copyright (c) 2015-2022 The Khronos Group Inc.
2 * Copyright (c) 2015-2022 Valve Corporation
3 * Copyright (c) 2015-2022 LunarG, Inc.
Nadav Geva41c12a22021-05-21 13:14:05 -04004 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Camdeneaa86ea2019-07-26 11:00:09 -06005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Camden Stocker <camden@lunarg.com>
Nadav Geva41c12a22021-05-21 13:14:05 -040019 * Author: Nadav Geva <nadav.geva@amd.com>
Camdeneaa86ea2019-07-26 11:00:09 -060020 */
21
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070022#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060023#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060024#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010025#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070026#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060027#include "cmd_buffer_state.h"
28#include "device_state.h"
29#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060030
31#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000032#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010033#include <memory>
Camden5b184be2019-08-13 07:50:19 -060034
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037 std::string name;
38};
39
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070040const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060041 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Nadav Geva41c12a22021-05-21 13:14:05 -040042 {kBPVendorAMD, {vendor_specific_amd, "AMD"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000043};
44
Hannes Harnisch607d1d92021-07-10 18:44:56 +020045const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
48 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
49 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
50 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
51};
52
53const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
56 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
57 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
58 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
59};
60
Jeremy Gebben20da7a12022-02-25 14:07:46 -070061ReadLockGuard BestPractices::ReadLock() {
62 if (fine_grained_locking) {
63 return ReadLockGuard(validation_object_mutex, std::defer_lock);
64 } else {
65 return ReadLockGuard(validation_object_mutex);
66 }
67}
68
69WriteLockGuard BestPractices::WriteLock() {
70 if (fine_grained_locking) {
71 return WriteLockGuard(validation_object_mutex, std::defer_lock);
72 } else {
73 return WriteLockGuard(validation_object_mutex);
74 }
75}
76
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060077std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
78 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060079 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -070080 return std::static_pointer_cast<CMD_BUFFER_STATE>(std::make_shared<bp_state::CommandBuffer>(this, cb, pCreateInfo, pool));
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060081}
82
Jeremy Gebben20da7a12022-02-25 14:07:46 -070083bp_state::CommandBuffer::CommandBuffer(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
84 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060085 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
86
Attilio Provenzano19d6a982020-02-27 12:41:41 +000087bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070088 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060089 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000090 return true;
91 }
92 }
93 return false;
94}
95
96const char* VendorSpecificTag(BPVendorFlags vendors) {
97 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070098 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000099
100 auto res = tag_map.find(vendors);
101 if (res == tag_map.end()) {
102 // Build the vendor tag string
103 std::stringstream vendor_tag;
104
105 vendor_tag << "[";
106 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700107 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000108 if (vendors & vendor.first) {
109 if (!first_vendor) {
110 vendor_tag << ", ";
111 }
112 vendor_tag << vendor.second.name;
113 first_vendor = false;
114 }
115 }
116 vendor_tag << "]";
117
118 tag_map[vendors] = vendor_tag.str();
119 res = tag_map.find(vendors);
120 }
121
122 return res->second.c_str();
123}
124
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700125const char* DepReasonToString(ExtDeprecationReason reason) {
126 switch (reason) {
127 case kExtPromoted:
128 return "promoted to";
129 break;
130 case kExtObsoleted:
131 return "obsoleted by";
132 break;
133 case kExtDeprecated:
134 return "deprecated by";
135 break;
136 default:
137 return "";
138 break;
139 }
140}
141
142bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
143 const char* vuid) const {
144 bool skip = false;
145 auto dep_info_it = deprecated_extensions.find(extension_name);
146 if (dep_info_it != deprecated_extensions.end()) {
147 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600148 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700149 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
150 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700151 skip |=
152 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
153 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600154 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700155 if (dep_info.target.length() == 0) {
156 skip |= LogWarning(instance, vuid,
157 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
158 "without replacement.",
159 api_name, extension_name);
160 } else {
161 skip |= LogWarning(instance, vuid,
162 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
163 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
164 }
165 }
166 }
167 return skip;
168}
169
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200170bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
171{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700172 bool skip = false;
173 auto dep_info_it = special_use_extensions.find(extension_name);
174
175 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200176 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
177 "and it is strongly recommended that it be otherwise avoided.";
178 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800179
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700180 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800181 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
182 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700183 }
184 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200185 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
186 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700187 }
188 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200189 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
190 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700191 }
192 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200193 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
194 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700195 }
196 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200197 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700198 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200199 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700200 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700201 }
202 return skip;
203}
204
Camden5b184be2019-08-13 07:50:19 -0600205bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500206 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600207 bool skip = false;
208
209 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
210 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800211 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700212 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
213 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600214 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600215 uint32_t specified_version =
216 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
217 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700218 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200219 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600220 }
221
222 return skip;
223}
224
Camden5b184be2019-08-13 07:50:19 -0600225bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500226 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600227 bool skip = false;
228
229 // get API version of physical device passed when creating device.
230 VkPhysicalDeviceProperties physical_device_properties{};
231 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500232 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600233
234 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600235 if (api_version > device_api_version) {
236 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600237 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600238
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700239 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
240 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
241 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600242 }
243
244 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
245 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800246 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700247 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
248 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600249 }
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600250 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700251 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200252 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600253 }
254
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700255 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600256 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700257 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
258 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600259 }
260
Nadav Gevaf0808442021-05-21 13:51:25 -0400261 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
Szilard Papp7d2c7952020-06-22 14:38:13 +0100262 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
263 skip |= LogPerformanceWarning(
264 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
Nadav Gevaf0808442021-05-21 13:51:25 -0400265 "%s %s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100266 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
267 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
268 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
Nadav Gevaf0808442021-05-21 13:51:25 -0400269 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100270 }
271
Camden5b184be2019-08-13 07:50:19 -0600272 return skip;
273}
274
275bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500276 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600277 bool skip = false;
278
279 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700280 std::stringstream buffer_hex;
281 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600282
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700283 skip |= LogWarning(
284 device, kVUID_BestPractices_SharingModeExclusive,
285 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
286 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700287 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600288 }
289
290 return skip;
291}
292
293bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500294 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600295 bool skip = false;
296
297 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700298 std::stringstream image_hex;
299 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600300
301 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700302 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
303 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
304 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700305 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600306 }
307
ziga-lunarg6df3d102022-03-18 17:02:14 +0100308 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
309 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
310 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
311 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
312 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
313 }
314
Attilio Provenzano02859b22020-02-27 14:17:28 +0000315 if (VendorCheckEnabled(kBPVendorArm)) {
316 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
317 skip |= LogPerformanceWarning(
318 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
319 "%s vkCreateImage(): Trying to create an image with %u samples. "
320 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
321 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
322 }
323
324 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
325 skip |= LogPerformanceWarning(
326 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
327 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
328 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
329 "and do not need to be backed by physical storage. "
330 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
331 VendorSpecificTag(kBPVendorArm));
332 }
333 }
334
Nadav Gevaf0808442021-05-21 13:51:25 -0400335 if (VendorCheckEnabled(kBPVendorAMD)) {
336 std::stringstream image_hex;
337 image_hex << "0x" << std::hex << HandleToUint64(pImage);
338
339 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
340 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
341 skip |= LogPerformanceWarning(device,
342 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
343 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
344 "Using a SHARING_MODE_CONCURRENT "
345 "is not recommended with color and depth targets",
346 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
347 }
348
349 if ((pCreateInfo->usage &
350 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
351 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
352 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
353 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
354 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
355 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
356 }
357
358 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
359 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
360 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
361 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
362 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
363 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
364 }
365 }
366
Camden5b184be2019-08-13 07:50:19 -0600367 return skip;
368}
369
370bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500371 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600372 bool skip = false;
373
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600374 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600375 if (bp_pd_state) {
376 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
377 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
378 "vkCreateSwapchainKHR() called before getting surface capabilities from "
379 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
380 }
Camden83a9c372019-08-14 11:41:38 -0600381
Shannon McPherson73e58c82021-03-05 17:14:26 -0700382 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
383 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600384 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
385 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
386 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
387 }
Camden83a9c372019-08-14 11:41:38 -0600388
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600389 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
390 skip |= LogWarning(
391 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
392 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
393 }
Camden83a9c372019-08-14 11:41:38 -0600394 }
395
Camden5b184be2019-08-13 07:50:19 -0600396 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700397 skip |=
398 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600399 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700400 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
401 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600402 }
403
ziga-lunarg79beba62022-03-30 01:17:30 +0200404 const auto present_mode = pCreateInfo->presentMode;
405 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
406 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100407 skip |= LogPerformanceWarning(
408 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
409 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
410 ", which means double buffering is going "
411 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
412 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
413 "3 to use triple buffering to maximize performance in such cases.",
414 pCreateInfo->minImageCount);
415 }
416
Szilard Pappd5f0f812020-06-22 09:01:29 +0100417 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
418 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
419 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
420 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
421 "Presentation modes which are not FIFO will present the latest available frame and discard other "
422 "frame(s) if any.",
423 VendorSpecificTag(kBPVendorArm));
424 }
425
Camden5b184be2019-08-13 07:50:19 -0600426 return skip;
427}
428
429bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
430 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500431 const VkAllocationCallbacks* pAllocator,
432 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600433 bool skip = false;
434
435 for (uint32_t i = 0; i < swapchainCount; i++) {
436 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700437 skip |= LogWarning(
438 device, kVUID_BestPractices_SharingModeExclusive,
439 "Warning: A shared swapchain (index %" PRIu32
440 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
441 "queues (queueFamilyIndexCount of %" PRIu32 ").",
442 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600443 }
444 }
445
446 return skip;
447}
448
449bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500450 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600451 bool skip = false;
452
453 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
454 VkFormat format = pCreateInfo->pAttachments[i].format;
455 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
456 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
457 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700458 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
459 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
460 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
461 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
462 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600463 }
464 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700465 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
466 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
467 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
468 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
469 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600470 }
471 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000472
473 const auto& attachment = pCreateInfo->pAttachments[i];
474 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
475 bool access_requires_memory =
476 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
477
478 if (FormatHasStencil(format)) {
479 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
480 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
481 }
482
483 if (access_requires_memory) {
484 skip |= LogPerformanceWarning(
485 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
486 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
487 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
488 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
489 i, static_cast<uint32_t>(attachment.samples));
490 }
491 }
Camden5b184be2019-08-13 07:50:19 -0600492 }
493
494 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
495 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
496 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
497 }
498
499 return skip;
500}
501
Tony-LunarG767180f2020-04-23 14:03:59 -0600502bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
503 const VkImageView* image_views) const {
504 bool skip = false;
505
506 // Check for non-transient attachments that should be transient and vice versa
507 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200508 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600509 bool attachment_should_be_transient =
510 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
511
512 if (FormatHasStencil(attachment.format)) {
513 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
514 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
515 }
516
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600517 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600518 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600519 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600520
521 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
522
523 // The check for an image that should not be transient applies to all GPUs
524 if (!attachment_should_be_transient && image_is_transient) {
525 skip |= LogPerformanceWarning(
526 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
527 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
528 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
529 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
530 i);
531 }
532
533 bool supports_lazy = false;
534 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
535 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
536 supports_lazy = true;
537 }
538 }
539
540 // The check for an image that should be transient only applies to GPUs supporting
541 // lazily allocated memory
542 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
543 skip |= LogPerformanceWarning(
544 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
545 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
546 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
547 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
548 i);
549 }
550 }
551 }
552 return skip;
553}
554
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000555bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
556 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
557 bool skip = false;
558
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600559 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800560 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600561 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000562 }
563
564 return skip;
565}
566
Sam Wallse746d522020-03-16 21:20:23 +0000567bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
568 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
569 bool skip = false;
570 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
571
572 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700573 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000574 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
575 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700576 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000577 skip |= LogPerformanceWarning(
578 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
579 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
580 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
581 VendorSpecificTag(kBPVendorArm));
582 }
583 }
584
585 return skip;
586}
587
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600588void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
589 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000590 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700591 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
592 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000593 // we record successful allocations by subtracting the allocation count from the last recorded free count
594 const auto alloc_count = pAllocateInfo->descriptorSetCount;
595 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700596 if (pool_state->freed_count > alloc_count) {
597 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700598 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700599 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700600 }
Sam Wallse746d522020-03-16 21:20:23 +0000601 }
602 }
603}
604
605void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
606 const VkDescriptorSet* pDescriptorSets, VkResult result) {
607 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
608 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700609 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000610 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700611 if (pool_state) {
612 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000613 }
614 }
615}
616
Camden5b184be2019-08-13 07:50:19 -0600617bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500618 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600619 bool skip = false;
620
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700621 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700622 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
623 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600624 }
625
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000626 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
627 skip |= LogPerformanceWarning(
628 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600629 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
630 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000631 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
632 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
633 }
634
Camden83a9c372019-08-14 11:41:38 -0600635 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
636
637 return skip;
638}
639
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600640void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
641 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
642 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700643 if (result != VK_SUCCESS) {
644 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
645 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800646 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700647 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600648 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700649 return;
650 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700651}
Camden Stocker9738af92019-10-16 13:54:03 -0700652
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600653void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
654 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700655 auto error = std::find(error_codes.begin(), error_codes.end(), result);
656 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000657 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
658 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
659
660 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
661 if (common_failure != common_failure_codes.end()) {
662 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
663 } else {
664 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
665 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700666 return;
667 }
668 auto success = std::find(success_codes.begin(), success_codes.end(), result);
669 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600670 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
671 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500672 }
673}
674
Jeff Bolz5c801d12019-10-09 10:38:45 -0500675bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
676 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700677 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600678 bool skip = false;
679
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700680 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600681
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700682 for (const auto& item : mem_info->ObjectBindings()) {
683 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600684 LogObjectList objlist(device);
685 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600686 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600687 skip |= LogWarning(objlist, layer_name.c_str(), "VK Object %s still has a reference to mem obj %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600688 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600689 }
690
Camden5b184be2019-08-13 07:50:19 -0600691 return skip;
692}
693
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000694bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600695 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700696 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600697
sfricke-samsunge2441192019-11-06 14:07:57 -0800698 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700699 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
700 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
701 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600702 }
703
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700704 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000705
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300706 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000707 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
708 skip |= LogPerformanceWarning(
709 device, kVUID_BestPractices_SmallDedicatedAllocation,
710 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600711 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
712 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000713 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
714 }
715
Camden Stockerb603cc82019-09-03 10:09:02 -0600716 return skip;
717}
718
719bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500720 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600721 bool skip = false;
722 const char* api_name = "BindBufferMemory()";
723
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000724 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600725
726 return skip;
727}
728
729bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500730 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600731 char api_name[64];
732 bool skip = false;
733
734 for (uint32_t i = 0; i < bindInfoCount; i++) {
735 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000736 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737 }
738
739 return skip;
740}
Camden Stockerb603cc82019-09-03 10:09:02 -0600741
742bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500743 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600744 char api_name[64];
745 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600746
Camden Stocker8b798ab2019-09-03 10:33:28 -0600747 for (uint32_t i = 0; i < bindInfoCount; i++) {
748 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000749 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600750 }
751
752 return skip;
753}
754
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000755bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600756 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700757 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600758
sfricke-samsung71bc6572020-04-29 15:49:43 -0700759 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600760 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700761 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
762 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
763 api_name, report_data->FormatHandle(image).c_str());
764 }
765 } else {
766 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
767 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600768 }
769
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700770 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000771
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600772 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000773 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
774 skip |= LogPerformanceWarning(
775 device, kVUID_BestPractices_SmallDedicatedAllocation,
776 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600777 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
778 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000779 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
780 }
781
782 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
783 // make sure this type is actually used.
784 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
785 // (i.e.most tile - based renderers)
786 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
787 bool supports_lazy = false;
788 uint32_t suggested_type = 0;
789
790 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600791 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000792 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
793 supports_lazy = true;
794 suggested_type = i;
795 break;
796 }
797 }
798 }
799
800 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
801
802 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
803 skip |= LogPerformanceWarning(
804 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600805 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000806 "but this memory type is not LAZILY_ALLOCATED_BIT. You should use memory type %u here instead to save "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600807 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600808 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000809 }
810 }
811
Camden Stocker8b798ab2019-09-03 10:33:28 -0600812 return skip;
813}
814
815bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500816 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600817 bool skip = false;
818 const char* api_name = "vkBindImageMemory()";
819
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000820 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600821
822 return skip;
823}
824
825bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500826 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600827 char api_name[64];
828 bool skip = false;
829
830 for (uint32_t i = 0; i < bindInfoCount; i++) {
831 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700832 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600833 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
834 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600835 }
836
837 return skip;
838}
839
840bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500841 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600842 char api_name[64];
843 bool skip = false;
844
845 for (uint32_t i = 0; i < bindInfoCount; i++) {
846 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000847 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600848 }
849
850 return skip;
851}
Camden83a9c372019-08-14 11:41:38 -0600852
Attilio Provenzano02859b22020-02-27 14:17:28 +0000853static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
854 switch (format) {
855 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
856 case VK_FORMAT_R16_SFLOAT:
857 case VK_FORMAT_R16G16_SFLOAT:
858 case VK_FORMAT_R16G16B16_SFLOAT:
859 case VK_FORMAT_R16G16B16A16_SFLOAT:
860 case VK_FORMAT_R32_SFLOAT:
861 case VK_FORMAT_R32G32_SFLOAT:
862 case VK_FORMAT_R32G32B32_SFLOAT:
863 case VK_FORMAT_R32G32B32A32_SFLOAT:
864 return false;
865
866 default:
867 return true;
868 }
869}
870
871bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
872 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
873 bool skip = false;
874
875 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700876 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000877
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700878 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
879 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
880 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000881 return skip;
882 }
883
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600884 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200885 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000886
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200887 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
888 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
889
890 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200891 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000892 uint32_t att = subpass.pColorAttachments[j].attachment;
893
894 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
895 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
896 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
897 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
898 "color attachment #%u makes use "
899 "of a format which cannot be blended at full throughput when using MSAA.",
900 VendorSpecificTag(kBPVendorArm), i, j);
901 }
902 }
903 }
904 }
905
906 return skip;
907}
908
Nadav Gevaf0808442021-05-21 13:51:25 -0400909void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
910 const VkComputePipelineCreateInfo* pCreateInfos,
911 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
912 VkResult result, void* pipe_state) {
913 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700914 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -0400915}
916
Camden5b184be2019-08-13 07:50:19 -0600917bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
918 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600919 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500920 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600921 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
922 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100923 if (skip) {
924 return skip;
925 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600926 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600927
928 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700929 skip |= LogPerformanceWarning(
930 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
931 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
932 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600933 }
934
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000935 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200936 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000937
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600938 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200939 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600940 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700941 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
942 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600943 count++;
944 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000945 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600946 if (count > kMaxInstancedVertexBuffers) {
947 skip |= LogPerformanceWarning(
948 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
949 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
950 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
951 count, kMaxInstancedVertexBuffers);
952 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000953 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000954
Szilard Pappaaf2da32020-06-22 10:37:35 +0100955 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
956 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200957 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
958 VendorCheckEnabled(kBPVendorArm)) {
959 skip |= LogPerformanceWarning(
960 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
961 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
962 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
963 "efficiency during rasterization. Consider disabling depthBias or increasing either "
964 "depthBiasConstantFactor or depthBiasSlopeFactor.",
965 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100966 }
967
Attilio Provenzano02859b22020-02-27 14:17:28 +0000968 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000969 }
Nadav Gevaf0808442021-05-21 13:51:25 -0400970 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700971 auto prev_pipeline = pipeline_cache_.load();
972 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -0400973 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
974 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
975 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
976 }
977
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700978 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -0400979 skip |=
980 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
981 "%s Performance warning: Too many pipelines created, consider consolidation",
982 VendorSpecificTag(kBPVendorAMD));
983 }
984
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -0600985 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -0400986 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
987 "%s Performance warning: Use of primitive restart is not recommended",
988 VendorSpecificTag(kBPVendorAMD));
989 }
990
991 // TODO: this might be too aggressive of a check
992 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
993 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
994 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
995 VendorSpecificTag(kBPVendorAMD));
996 }
997 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000998
Camden5b184be2019-08-13 07:50:19 -0600999 return skip;
1000}
1001
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001002static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1003 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1004 std::vector<bp_state::AttachmentInfo> result;
Tony-LunarG5e1dbcd2022-03-29 08:19:58 -06001005 if (!rp || rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001006 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001007 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001008
1009 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1010
1011 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1012 // are only non-null if they are enabled.
1013 if (create_info.pColorBlendState) {
1014 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1015 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1016 for (uint32_t j = 0; j < num_color_attachments; j++) {
1017 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1018 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1019 if (attachment != VK_ATTACHMENT_UNUSED) {
1020 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1021 }
1022 }
1023 }
1024 }
1025
1026 if (create_info.pDepthStencilState &&
1027 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1028 create_info.pDepthStencilState->stencilTestEnable)) {
1029 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1030 if (attachment != VK_ATTACHMENT_UNUSED) {
1031 VkImageAspectFlags aspects = 0;
1032 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1033 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1034 }
1035 if (create_info.pDepthStencilState->stencilTestEnable) {
1036 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1037 }
1038 result.push_back({attachment, aspects});
1039 }
1040 }
1041 return result;
1042}
1043
1044bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1045 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1046 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1047 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1048 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1049
1050std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1051 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1052 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1053 return std::static_pointer_cast<PIPELINE_STATE>(
1054 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001055}
1056
Sam Walls0961ec02020-03-31 16:39:15 +01001057void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1058 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1059 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1060 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001061 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001062 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001063}
1064
Camden5b184be2019-08-13 07:50:19 -06001065bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1066 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001067 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001068 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001069 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1070 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001071
1072 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001073 skip |= LogPerformanceWarning(
1074 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1075 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1076 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001077 }
1078
Nadav Gevaf0808442021-05-21 13:51:25 -04001079 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001080 auto prev_pipeline = pipeline_cache_.load();
1081 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1082 skip |= LogPerformanceWarning(
1083 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1084 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001085 "improve cache hit rate",
1086 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001087 }
1088 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001089
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001090 for (uint32_t i = 0; i < createInfoCount; i++) {
1091 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1092 if (VendorCheckEnabled(kBPVendorArm)) {
1093 skip |= ValidateCreateComputePipelineArm(createInfo);
1094 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001095
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001096 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1097 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1098 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1099 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1100 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1101 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1102 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1103 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1104 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001105 }
1106 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001107 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001108 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001109
1110 return skip;
1111}
1112
1113bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1114 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001115 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001116 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001117 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1118 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001119
1120 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001121 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001122
1123 uint32_t thread_count = x * y * z;
1124
1125 // Generate a priori warnings about work group sizes.
1126 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1127 skip |= LogPerformanceWarning(
1128 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1129 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1130 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1131 "groups with less than %u threads, especially when using barrier() or shared memory.",
1132 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1133 }
1134
1135 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1136 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1137 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1138 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1139 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1140 "%u, %u) is not aligned to %u "
1141 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1142 "leave threads idle on the shader "
1143 "core.",
1144 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1145 kThreadGroupDispatchCountAlignmentArm);
1146 }
1147
sfricke-samsungef15e482022-01-26 11:32:49 -08001148 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1149 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001150
1151 unsigned dimensions = 0;
1152 if (x > 1) dimensions++;
1153 if (y > 1) dimensions++;
1154 if (z > 1) dimensions++;
1155 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1156 dimensions = std::max(dimensions, 1u);
1157
1158 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1159 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1160 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1161 bool accesses_2d = false;
1162 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001163 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001164 if (dim < 0) continue;
1165 auto spvdim = spv::Dim(dim);
1166 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1167 }
1168
1169 if (accesses_2d && dimensions < 2) {
1170 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1171 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1172 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1173 "exhibiting poor spatial locality with respect to one or more shader resources.",
1174 VendorSpecificTag(kBPVendorArm), x, y, z);
1175 }
1176
Camden5b184be2019-08-13 07:50:19 -06001177 return skip;
1178}
1179
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001180bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001181 bool skip = false;
1182
1183 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001184 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1185 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001186 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001187 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1188 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001189 }
1190
1191 return skip;
1192}
1193
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001194bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1195 bool skip = false;
1196
1197 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1198 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1199 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1200 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1201 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1202 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1203 }
1204
1205 return skip;
1206}
1207
1208bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1209 bool skip = false;
1210 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1211
1212 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1213 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1214
1215 return skip;
1216}
1217
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001218void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001219 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1220 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1221 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1222 LogPerformanceWarning(
1223 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1224 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1225 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1226 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1227 "convenient opportunity.",
1228 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1229 }
1230 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001231
1232 // AMD best practice
1233 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001234 num_queue_submissions_ = 0;
1235 num_barriers_objects_ = 0;
1236 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001237}
1238
Jeff Bolz5c801d12019-10-09 10:38:45 -05001239bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1240 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001241 bool skip = false;
1242
1243 for (uint32_t submit = 0; submit < submitCount; submit++) {
1244 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1245 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1246 }
1247 }
1248
1249 return skip;
1250}
1251
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001252bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1253 VkFence fence) const {
1254 bool skip = false;
1255
1256 for (uint32_t submit = 0; submit < submitCount; submit++) {
1257 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1258 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1259 }
1260 }
1261
1262 return skip;
1263}
1264
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001265bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1266 VkFence fence) const {
1267 bool skip = false;
1268
1269 for (uint32_t submit = 0; submit < submitCount; submit++) {
1270 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1271 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1272 }
1273 }
1274
1275 return skip;
1276}
1277
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001278bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1279 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1280 bool skip = false;
1281
1282 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1283 skip |= LogPerformanceWarning(
1284 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1285 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1286 "pool instead.");
1287 }
1288
1289 return skip;
1290}
1291
1292bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1293 const VkCommandBufferBeginInfo* pBeginInfo) const {
1294 bool skip = false;
1295
1296 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1297 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1298 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1299 }
1300
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001301 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1302 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001303 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1304 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1305 VendorSpecificTag(kBPVendorArm));
1306 }
1307
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001308 return skip;
1309}
1310
Jeff Bolz5c801d12019-10-09 10:38:45 -05001311bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001312 bool skip = false;
1313
1314 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1315
1316 return skip;
1317}
1318
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001319bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1320 const VkDependencyInfoKHR* pDependencyInfo) const {
1321 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1322}
1323
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001324bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1325 const VkDependencyInfo* pDependencyInfo) const {
1326 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1327}
1328
Jeff Bolz5c801d12019-10-09 10:38:45 -05001329bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1330 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001331 bool skip = false;
1332
1333 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1334
1335 return skip;
1336}
1337
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001338bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1339 VkPipelineStageFlags2KHR stageMask) const {
1340 bool skip = false;
1341
1342 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1343
1344 return skip;
1345}
1346
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001347bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1348 VkPipelineStageFlags2 stageMask) const {
1349 bool skip = false;
1350
1351 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1352
1353 return skip;
1354}
1355
Camden5b184be2019-08-13 07:50:19 -06001356bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1357 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1358 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1359 uint32_t bufferMemoryBarrierCount,
1360 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1361 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001362 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001363 bool skip = false;
1364
1365 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1366 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1367
1368 return skip;
1369}
1370
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001371bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1372 const VkDependencyInfoKHR* pDependencyInfos) const {
1373 bool skip = false;
1374 for (uint32_t i = 0; i < eventCount; i++) {
1375 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1376 }
1377
1378 return skip;
1379}
1380
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001381bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1382 const VkDependencyInfo* pDependencyInfos) const {
1383 bool skip = false;
1384 for (uint32_t i = 0; i < eventCount; i++) {
1385 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1386 }
1387
1388 return skip;
1389}
1390
Camden5b184be2019-08-13 07:50:19 -06001391bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1392 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1393 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1394 uint32_t bufferMemoryBarrierCount,
1395 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1396 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001397 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001398 bool skip = false;
1399
1400 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1401 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1402
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001403 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1404 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1405 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1406 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1407 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1408 "may be discarded, but the newLayout is %s, which is read only.",
1409 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1410 }
1411 }
1412
Nadav Gevaf0808442021-05-21 13:51:25 -04001413 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001414 auto num = num_barriers_objects_.load();
1415 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001416 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001417 "%s Performance warning: In this frame, %" PRIu32
1418 " barriers were already submitted. Barriers have a high cost and can "
1419 "stall the GPU. "
1420 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1421 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001422 }
1423
1424 std::array<VkImageLayout, 3> read_layouts = {
1425 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1426 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1427 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1428 };
1429
1430 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1431 // read to read barriers
1432 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1433 bool old_is_read_layout = found != read_layouts.end();
1434 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1435 bool new_is_read_layout = found != read_layouts.end();
1436 if (old_is_read_layout && new_is_read_layout) {
1437 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1438 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1439 "time you use it.",
1440 VendorSpecificTag(kBPVendorAMD));
1441 }
1442
1443 // general with no storage
1444 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1445 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1446 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1447 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1448 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1449 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1450 VendorSpecificTag(kBPVendorAMD));
1451 }
1452 }
1453 }
1454 }
1455
Camden5b184be2019-08-13 07:50:19 -06001456 return skip;
1457}
1458
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001459bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1460 const VkDependencyInfoKHR* pDependencyInfo) const {
1461 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1462}
1463
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001464bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1465 const VkDependencyInfo* pDependencyInfo) const {
1466 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1467}
1468
Camden5b184be2019-08-13 07:50:19 -06001469bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001470 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001471 bool skip = false;
1472
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001473 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1474
1475 return skip;
1476}
1477
1478bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1479 VkQueryPool queryPool, uint32_t query) const {
1480 bool skip = false;
1481
1482 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001483
1484 return skip;
1485}
1486
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001487bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1488 VkQueryPool queryPool, uint32_t query) const {
1489 bool skip = false;
1490
1491 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1492
1493 return skip;
1494}
1495
Sam Walls0961ec02020-03-31 16:39:15 +01001496void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1497 VkPipeline pipeline) {
1498 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1499
Nadav Gevaf0808442021-05-21 13:51:25 -04001500 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001501 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001502
Sam Walls0961ec02020-03-31 16:39:15 +01001503 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001504 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001505 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001506 if (pipeline_state) {
1507 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001508 assert(cb_node);
1509 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001510
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001511 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001512 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001513
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001514 const auto* blend_state = pipeline_state->ColorBlendState();
1515 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001516
1517 if (blend_state) {
1518 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001519 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001520 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1521 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001522 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001523 }
1524 }
1525 }
1526
1527 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001528 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001529
1530 if (stencil_state && stencil_state->depthTestEnable) {
1531 switch (stencil_state->depthCompareOp) {
1532 case VK_COMPARE_OP_EQUAL:
1533 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1534 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001535 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001536 break;
1537 default:
1538 break;
1539 }
1540 }
Sam Walls0961ec02020-03-31 16:39:15 +01001541 }
1542 }
1543}
1544
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001545static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1546 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1547 const auto& subpass_info = createInfo.pSubpasses[subpass];
1548 if (subpass_info.pResolveAttachments) {
1549 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1550 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1551 }
1552 }
1553 }
1554
1555 return false;
1556}
1557
Attilio Provenzano02859b22020-02-27 14:17:28 +00001558static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1559 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001560 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001561
1562 // If an attachment is ever used as a color attachment,
1563 // resolve attachment or depth stencil attachment,
1564 // it needs to exist on tile at some point.
1565
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001566 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1567 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001568 }
1569
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001570 if (subpass_info.pResolveAttachments) {
1571 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1572 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1573 }
1574 }
1575
1576 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001577 }
1578
1579 return false;
1580}
1581
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001582static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1583 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1584 return false;
1585 }
1586
1587 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001588 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001589
1590 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1591 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1592 return true;
1593 }
1594 }
1595 }
1596
1597 return false;
1598}
1599
Attilio Provenzano02859b22020-02-27 14:17:28 +00001600bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1601 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1602 bool skip = false;
1603
1604 if (!pRenderPassBegin) {
1605 return skip;
1606 }
1607
Gareth Webbdc6549a2021-06-16 03:52:24 +01001608 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1609 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1610 "This render pass has a zero-size render area. It cannot write to any attachments, "
1611 "and can only be used for side effects such as layout transitions.");
1612 }
1613
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001614 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001615 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001616 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001617 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001618 if (rpabi) {
1619 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1620 }
1621 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001622 // Check if any attachments have LOAD operation on them
1623 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001624 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001625
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001626 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001627 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001628 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001629 }
1630
1631 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001632 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001633 }
1634
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001635 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001636
1637 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001638 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1639 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001640 }
1641
1642 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001643 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1644 skip |= LogPerformanceWarning(
1645 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1646 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1647 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001648 "which will copy in total %u pixels (renderArea = "
1649 "{ %" PRId32 ", %" PRId32 ", %" PRIu32", %" PRIu32 " }) to the tile buffer.",
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001650 VendorSpecificTag(kBPVendorArm), att,
1651 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1652 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1653 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001654 }
1655 }
1656 }
1657
1658 return skip;
1659}
1660
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001661void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1662 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001663 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001664 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1665 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001666 }
1667}
1668
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001669void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1670 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001671 // If we're viewing a 3D slice, ignore base array layer.
1672 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001673 const uint32_t base_array_layer = state->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001674
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001675 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001676 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001677 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1678 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001679
1680 for (uint32_t layer = 0; layer < array_layers; layer++) {
1681 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001682 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1683 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001684 }
1685 }
1686}
1687
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001688void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1689 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1690 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001691 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001692
1693 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001694 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001695 }
1696}
1697
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001698void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001699 std::shared_ptr<bp_state::Image> &state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001700 uint32_t array_layer, uint32_t mip_level) {
Jeremy Gebben7fd238f2022-03-04 10:32:24 -07001701 if (VendorCheckEnabled(kBPVendorArm)) {
1702 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](
1703 const ValidationStateTracker&, const QUEUE_STATE&, const CMD_BUFFER_STATE&) -> bool {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001704 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
Jeremy Gebben7fd238f2022-03-04 10:32:24 -07001705 return false;
1706 });
1707 }
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001708}
1709
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001710void BestPractices::ValidateImageInQueueArm(const char* function_name, const bp_state::Image& image,
1711 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001712 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001713 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001714 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001715 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001716 LogPerformanceWarning(
1717 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001718 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001719 "image was used, it was written to with STORE_OP_STORE. "
1720 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1721 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001722 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001723 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001724 LogPerformanceWarning(
1725 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001726 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was cleared as part of LOAD_OP_CLEAR, but last time "
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001727 "image was used, it was written to with vkCmdClear*Image(). "
1728 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1729 "tile-based architectures."
1730 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001731 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001732 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001733 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1734 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001735 const char *last_cmd = nullptr;
1736 const char *vuid = nullptr;
1737 const char *suggestion = nullptr;
1738
1739 switch (last_usage) {
1740 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1741 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1742 last_cmd = "vkCmdBlitImage";
1743 suggestion =
1744 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1745 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1746 "which avoids the memory roundtrip.";
1747 break;
1748 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1749 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1750 last_cmd = "vkCmdClear*Image";
1751 suggestion =
1752 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1753 "tile-based architectures. "
1754 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1755 break;
1756 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1757 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1758 last_cmd = "vkCmdCopy*Image";
1759 suggestion =
1760 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1761 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1762 "which avoids the memory roundtrip.";
1763 break;
1764 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1765 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1766 last_cmd = "vkCmdResolveImage";
1767 suggestion =
1768 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1769 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1770 "which avoids the memory roundtrip.";
1771 break;
1772 default:
1773 break;
1774 }
1775
1776 LogPerformanceWarning(
1777 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001778 "%s: %s Subresource (arrayLayer: %u, mipLevel: %u) of image was loaded to tile as part of LOAD_OP_LOAD, but last "
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001779 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001780 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001781 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001782}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001783
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001784void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1785 uint32_t array_layer, uint32_t mip_level) {
1786 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001787 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001788 ValidateImageInQueueArm(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001789 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001790}
1791
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001792void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1793 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1794 cb.queue_submit_functions_after_render_pass.end());
1795 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001796}
1797
1798void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1799 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001800 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1801 if (cb_node) {
1802 AddDeferredQueueOperations(*cb_node);
1803 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001804}
1805
1806void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1807 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001808 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1809 if (cb_node) {
1810 AddDeferredQueueOperations(*cb_node);
1811 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001812}
1813
1814void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1815 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001816 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1817 if (cb_node) {
1818 AddDeferredQueueOperations(*cb_node);
1819 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001820}
1821
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001822void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1823 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001824 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001825 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001826 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1827}
1828
1829void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1830 const VkRenderPassBeginInfo* pRenderPassBegin,
1831 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1832 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1833 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1834}
1835
1836void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1837 const VkRenderPassBeginInfo* pRenderPassBegin,
1838 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1839 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1840 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1841}
1842
1843void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001844
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001845 if (!pRenderPassBegin) {
1846 return;
1847 }
1848
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001849 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001850
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001851 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001852 if (rp_state) {
1853 // Check load ops
1854 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001855 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001856
1857 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1858 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1859 continue;
1860 }
1861
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001862 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001863
1864 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1865 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001866 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001867 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1868 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001869 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001870 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001871 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001872 }
1873
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001874 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001875 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001876
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001877 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001878 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1879 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001880 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001881 }
1882 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001883 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001884 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001885
Jeremy Gebben9f537102021-10-05 16:37:12 -06001886 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001887 }
1888
1889 // Check store ops
1890 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001891 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001892
1893 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1894 continue;
1895 }
1896
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001897 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001898
1899 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1900 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001901 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001902 }
1903
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001904 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001905
Jeremy Gebben9f537102021-10-05 16:37:12 -06001906 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001907 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001908 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1909 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001910 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001911 }
1912 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001913 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001914 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001915
Jeremy Gebben9f537102021-10-05 16:37:12 -06001916 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001917 }
1918 }
1919}
1920
Attilio Provenzano02859b22020-02-27 14:17:28 +00001921bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1922 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001923 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1924 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001925 return skip;
1926}
1927
1928bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1929 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001930 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001931 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1932 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001933 return skip;
1934}
1935
1936bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001937 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001938 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1939 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001940 return skip;
1941}
1942
Sam Walls0961ec02020-03-31 16:39:15 +01001943void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1944 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001945 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001946 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001947 cb->hasDrawCmd = false;
1948 assert(cb);
1949 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001950 render_pass_state.touchesAttachments.clear();
1951 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001952 render_pass_state.numDrawCallsDepthOnly = 0;
1953 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1954 render_pass_state.colorAttachment = false;
1955 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001956 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001957 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001958
Jeremy Gebbenf4449392022-01-28 10:09:10 -07001959 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001960
1961 // track depth / color attachment usage within the renderpass
1962 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1963 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001964 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001965
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001966 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001967 }
1968}
1969
1970void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1971 VkSubpassContents contents) {
1972 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1973 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1974}
1975
1976void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1977 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1978 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1979 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1980}
1981
1982void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1983 const VkRenderPassBeginInfo* pRenderPassBegin,
1984 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1985 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1986 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1987}
1988
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001989// Generic function to handle validation for all CmdDraw* type functions
1990bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1991 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001992 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001993 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001994 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1995 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001996 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001997
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001998 // Verify vertex binding
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001999 if (pipeline_state->vertex_input_state && pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002000 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002001 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002002 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002003 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2004 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002005 }
2006 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002007
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002008 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002009 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002010 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002011 if (rp_state) {
2012 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2013 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002014 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002015 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002016 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2017 const auto* raster_state = pipe->RasterizationState();
2018 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2019 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002020 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2021 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2022 }
2023 }
2024 }
2025 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002026 }
2027 return skip;
2028}
2029
Sam Walls0961ec02020-03-31 16:39:15 +01002030void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002031 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002032 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002033 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002034 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002035 }
2036
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002037 if (cb_node->render_pass_state.drawTouchAttachments) {
2038 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2039 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002040 }
2041 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002042 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002043 }
2044}
2045
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002046void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2047 auto& render_pass_state = cb_node.render_pass_state;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002048 if (draw_count >= kDepthPrePassMinDrawCountArm) {
2049 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2050 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002051 }
2052}
2053
Camden5b184be2019-08-13 07:50:19 -06002054bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002055 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002056 bool skip = false;
2057
2058 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002059 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2060 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002061 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002062 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002063
2064 return skip;
2065}
2066
Sam Walls0961ec02020-03-31 16:39:15 +01002067void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2068 uint32_t firstVertex, uint32_t firstInstance) {
2069 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2070 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2071}
2072
Camden5b184be2019-08-13 07:50:19 -06002073bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002074 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002075 bool skip = false;
2076
2077 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002078 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2079 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002080 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002081 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2082
Attilio Provenzano02859b22020-02-27 14:17:28 +00002083 // Check if we reached the limit for small indexed draw calls.
2084 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002085 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002086 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002087 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
2088 VendorCheckEnabled(kBPVendorArm)) {
2089 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002090 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002091 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2092 "You can try batching drawcalls or instancing when applicable.",
2093 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
2094 }
2095
Sam Walls8e77e4f2020-03-16 20:47:40 +00002096 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002097 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002098 }
2099
2100 return skip;
2101}
2102
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002103bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002104 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2105 bool skip = false;
2106
2107 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002108
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002109 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2110 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002111
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002112 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002113 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002114 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2115 const void* ib_mem = ib_mem_state.p_driver_data;
2116 bool primitive_restart_enable = false;
2117
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002118 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002119 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002120 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002121
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002122 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2123 if (ia_state) {
2124 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002125 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002126
2127 // no point checking index buffer if the memory is nonexistant/unmapped, or if there is no graphics pipeline bound to this CB
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002128 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002129 uint32_t scan_stride;
2130 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2131 scan_stride = sizeof(uint8_t);
2132 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2133 scan_stride = sizeof(uint16_t);
2134 } else {
2135 scan_stride = sizeof(uint32_t);
2136 }
2137
2138 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2139 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2140
2141 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2142 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2143 // irrespective of whether or not they're part of the draw call.
2144
2145 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2146 uint32_t min_index = ~0u;
2147 // start with maximum as 0 and adjust to indices in the buffer
2148 uint32_t max_index = 0u;
2149
2150 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2151 // for the given index buffer
2152 uint32_t vertex_shade_count = 0;
2153
2154 PostTransformLRUCacheModel post_transform_cache;
2155
2156 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2157 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2158 // target architecture.
2159 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2160 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2161 post_transform_cache.resize(32);
2162
2163 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2164 uint32_t scan_index;
2165 uint32_t primitive_restart_value;
2166 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2167 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2168 primitive_restart_value = 0xFF;
2169 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2170 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2171 primitive_restart_value = 0xFFFF;
2172 } else {
2173 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2174 primitive_restart_value = 0xFFFFFFFF;
2175 }
2176
2177 max_index = std::max(max_index, scan_index);
2178 min_index = std::min(min_index, scan_index);
2179
2180 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2181 bool in_cache = post_transform_cache.query_cache(scan_index);
2182 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2183 if (!in_cache) vertex_shade_count++;
2184 }
2185 }
2186
2187 // if the max and min values were not set, then we either have no indices, or all primitive restarts, exit...
Sam Walls61b06892020-07-23 16:20:50 +01002188 // if the max and min are the same, then it implies all the indices are the same, then we don't need to do anything
2189 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002190
2191 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002192 skip |=
2193 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2194 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2195 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2196 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2197 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2198 VendorSpecificTag(kBPVendorArm),
2199 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002200 return skip;
2201 }
2202
2203 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2204 // each bit of the n-th bucket contains the inclusion information for indices (n*n_buckets) to ((n+1)*n_buckets)
Sam Walls61b06892020-07-23 16:20:50 +01002205 const size_t refs_per_bucket = 64;
2206 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2207
2208 const uint32_t n_indices = max_index - min_index + 1;
2209 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2210 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2211
2212 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2213 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002214
2215 // To avoid using too much memory, we run over the indices again.
2216 // Knowing the size from the last scan allows us to record index usage with bitsets
2217 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2218 uint32_t scan_index;
2219 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2220 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2221 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2222 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2223 } else {
2224 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2225 }
2226 // keep track of the set of all indices used to reference vertices in the draw call
2227 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002228 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2229 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002230 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2231 }
2232
2233 uint32_t vertex_reference_count = 0;
2234 for (const auto& bitset : vertex_reference_buckets) {
2235 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2236 }
2237
2238 // low index buffer utilization implies that: of the vertices available to the draw call, not all are utilized
Mark Young0ec6b062020-11-19 15:32:17 -07002239 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002240 // low hit rate (high miss rate) implies the order of indices in the draw call may be possible to improve
Mark Young0ec6b062020-11-19 15:32:17 -07002241 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002242
2243 if (utilization < 0.5f) {
2244 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2245 "%s The indices which were specified for the draw call only utilise approximately "
2246 "%.02f%% of the bound vertex buffer.",
2247 VendorSpecificTag(kBPVendorArm), utilization);
2248 }
2249
2250 if (cache_hit_rate <= 0.5f) {
2251 skip |=
2252 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2253 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2254 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2255 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2256 "recently shaded vertices.",
2257 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2258 }
2259 }
2260
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002261 return skip;
2262}
2263
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002264bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2265 const VkCommandBuffer* pCommandBuffers) const {
2266 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002267 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002268 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002269 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002270 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002271 continue;
2272 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002273 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002274 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002275 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2276 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002277 }
2278 }
2279 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002280
2281 if (VendorCheckEnabled(kBPVendorAMD)) {
2282 if (commandBufferCount > 0) {
2283 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2284 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2285 VendorSpecificTag(kBPVendorAMD));
2286 }
2287 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002288 return skip;
2289}
2290
2291void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2292 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002293 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2294
2295 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2296 if (!primary) {
2297 return;
2298 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002299
2300 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002301 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2302 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002303 continue;
2304 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002305
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002306 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2307 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2308 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2309 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002310 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002311 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002312 }
2313 }
2314
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002315 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2316 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002317 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002318
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002319 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2320 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002321
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002322 if (secondary->hasDrawCmd) {
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002323 primary->hasDrawCmd = true;
2324 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002325 }
2326
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002327}
2328
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002329void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2330 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002331 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002332 auto itr =
2333 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2334 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002335
2336 if (itr != state.touchesAttachments.end()) {
2337 itr->aspects |= aspects;
2338 } else {
2339 state.touchesAttachments.push_back({ fb_attachment, aspects });
2340 }
2341}
2342
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002343void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002344 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2345 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002346 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002347 // If we observe a full clear before any other access to a frame buffer attachment,
2348 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002349 auto itr =
2350 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2351 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002352
2353 uint32_t new_aspects = aspects;
2354 if (itr != state.touchesAttachments.end()) {
2355 new_aspects = aspects & ~itr->aspects;
2356 itr->aspects |= aspects;
2357 } else {
2358 state.touchesAttachments.push_back({ fb_attachment, aspects });
2359 }
2360
2361 if (new_aspects == 0) {
2362 return;
2363 }
2364
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002365 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002366 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2367 // CmdExecuteCommands.
2368 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2369 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2370 }
2371}
2372
2373void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2374 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2375 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002376 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2377
2378 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2379 auto* rp_state = cmd_state->activeRenderPass.get();
2380 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002381 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2382
2383 if (rectCount == 0 || !rp_state) {
2384 return;
2385 }
2386
2387 if (!is_secondary && !fb_state) {
2388 return;
2389 }
2390
2391 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002392 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002393
ziga-lunarg885c6542022-03-07 01:08:25 +01002394 if (!rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
2395 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2396 for (uint32_t i = 0; i < attachmentCount; i++) {
2397 auto& attachment = pClearAttachments[i];
2398 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2399 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002400
ziga-lunarg885c6542022-03-07 01:08:25 +01002401 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2402 if (subpass.pDepthStencilAttachment) {
2403 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2404 }
2405 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2406 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002407 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002408
ziga-lunarg885c6542022-03-07 01:08:25 +01002409 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2410 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002411 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002412 aspects, rectCount, pRects);
2413 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002414 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002415 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002416 }
2417 }
2418 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002419}
2420
Attilio Provenzano02859b22020-02-27 14:17:28 +00002421void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2422 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2423 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2424 firstInstance);
2425
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002426 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002427 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2428 cmd_state->small_indexed_draw_call_count++;
2429 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002430
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002431 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002432}
2433
Sam Walls0961ec02020-03-31 16:39:15 +01002434void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2435 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2436 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2437 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2438}
2439
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002440bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2441 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2442 uint32_t maxDrawCount, uint32_t stride) const {
2443 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2444
2445 return skip;
2446}
2447
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002448bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2449 VkDeviceSize offset, VkBuffer countBuffer,
2450 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2451 uint32_t stride) const {
2452 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002453
2454 return skip;
2455}
2456
2457bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002458 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002459 bool skip = false;
2460
2461 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002462 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2463 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002464 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002465 }
2466
2467 return skip;
2468}
2469
Sam Walls0961ec02020-03-31 16:39:15 +01002470void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2471 uint32_t count, uint32_t stride) {
2472 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2473 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2474}
2475
Camden5b184be2019-08-13 07:50:19 -06002476bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002477 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002478 bool skip = false;
2479
2480 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002481 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2482 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002483 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002484 }
2485
2486 return skip;
2487}
2488
Sam Walls0961ec02020-03-31 16:39:15 +01002489void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2490 uint32_t count, uint32_t stride) {
2491 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2492 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2493}
2494
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002495void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2496 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
2497 const auto& layout = *descriptor_set->GetLayout();
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002498
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002499 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2500 // For bindless scenarios, we should not attempt to track descriptor set state.
2501 // It is highly uncertain which resources are actually bound.
2502 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2503 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2504 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2505 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2506 continue;
2507 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002508
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002509 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
2510 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
2511 VkImageView image_view{VK_NULL_HANDLE};
2512
2513 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2514 switch (descriptor->GetClass()) {
2515 case cvdescriptorset::DescriptorClass::Image: {
2516 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2517 image_view = image_descriptor->GetImageView();
2518 }
2519 break;
2520 }
2521 case cvdescriptorset::DescriptorClass::ImageSampler: {
2522 if (const auto image_sampler_descriptor =
2523 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2524 image_view = image_sampler_descriptor->GetImageView();
2525 }
2526 break;
2527 }
2528 default:
2529 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002530 }
2531
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002532 if (image_view) {
2533 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2534 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2535 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002536 }
2537 }
2538 }
2539 }
2540}
2541
2542void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2543 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002544 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2545 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002546}
2547
2548void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2549 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002550 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2551 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002552}
2553
2554void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2555 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002556 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2557 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002558}
2559
Camden5b184be2019-08-13 07:50:19 -06002560bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002561 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002562 bool skip = false;
2563
2564 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002565 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2566 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2567 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2568 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002569 }
2570
2571 return skip;
2572}
Camden83a9c372019-08-14 11:41:38 -06002573
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002574bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2575 bool skip = false;
2576 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2577 skip |= ValidateCmdEndRenderPass(commandBuffer);
2578 return skip;
2579}
2580
2581bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2582 bool skip = false;
2583 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2584 skip |= ValidateCmdEndRenderPass(commandBuffer);
2585 return skip;
2586}
2587
Sam Walls0961ec02020-03-31 16:39:15 +01002588bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2589 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002590 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002591 skip |= ValidateCmdEndRenderPass(commandBuffer);
2592 return skip;
2593}
2594
2595bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2596 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002597 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002598
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002599 if (cmd == nullptr) return skip;
2600 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002601
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002602 bool uses_depth = (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
2603 render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2604 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002605 if (uses_depth) {
2606 skip |= LogPerformanceWarning(
2607 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2608 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2609 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2610 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2611 VendorSpecificTag(kBPVendorArm));
2612 }
2613
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002614 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2615
2616 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2617
2618 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2619 // it is redundant to have it be part of the render pass.
2620 // Only consider it redundant if it will actually consume bandwidth, i.e.
2621 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2622 // as is using pure input attachments.
2623 // CLEAR -> STORE might be considered a "useful" thing to do, but
2624 // the optimal thing to do is to defer the clear until you're actually
2625 // going to render to the image.
2626
2627 uint32_t num_attachments = rp->createInfo.attachmentCount;
2628 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002629 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2630 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002631 continue;
2632 }
2633
2634 auto& attachment = rp->createInfo.pAttachments[i];
2635
2636 VkImageAspectFlags bandwidth_aspects = 0;
2637
2638 if (!FormatIsStencilOnly(attachment.format) &&
2639 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2640 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2641 if (FormatHasDepth(attachment.format)) {
2642 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2643 } else {
2644 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2645 }
2646 }
2647
2648 if (FormatHasStencil(attachment.format) &&
2649 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2650 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2651 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2652 }
2653
2654 if (!bandwidth_aspects) {
2655 continue;
2656 }
2657
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002658 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002659 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002660 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002661 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002662 untouched_aspects &= ~itr->aspects;
2663 }
2664
2665 if (untouched_aspects) {
2666 skip |= LogPerformanceWarning(
2667 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2668 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2669 "was never accessed by a pipeline or clear command. "
2670 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2671 "if the attachments are not intended to be accessed.",
2672 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2673 }
2674 }
2675 }
2676
Sam Walls0961ec02020-03-31 16:39:15 +01002677 return skip;
2678}
2679
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002680void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002681 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2682 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002683}
2684
2685void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002686 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2687 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002688}
2689
Camden Stocker9c051442019-11-06 14:28:43 -08002690bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2691 const char* api_name) const {
2692 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002693 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002694
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002695 if (bp_pd_state) {
2696 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2697 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2698 "Potential problem with calling %s() without first retrieving properties from "
2699 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2700 api_name);
2701 }
Camden Stocker9c051442019-11-06 14:28:43 -08002702 }
2703
2704 return skip;
2705}
2706
Camden83a9c372019-08-14 11:41:38 -06002707bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002708 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002709 bool skip = false;
2710
Camden Stocker9c051442019-11-06 14:28:43 -08002711 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002712
Camden Stocker9c051442019-11-06 14:28:43 -08002713 return skip;
2714}
2715
2716bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2717 uint32_t planeIndex,
2718 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2719 bool skip = false;
2720
2721 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2722
2723 return skip;
2724}
2725
2726bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2727 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2728 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2729 bool skip = false;
2730
2731 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002732
2733 return skip;
2734}
Camden05de2d42019-08-19 10:23:56 -06002735
2736bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002737 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002738 bool skip = false;
2739
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002740 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002741
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002742 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002743 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002744 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002745 skip |=
2746 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2747 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2748 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002749 }
Camden05de2d42019-08-19 10:23:56 -06002750
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002751 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2752 skip |= LogWarning(
2753 device, kVUID_BestPractices_Swapchain_InvalidCount,
2754 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002755 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002756 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2757 }
2758 }
2759
Camden05de2d42019-08-19 10:23:56 -06002760 return skip;
2761}
2762
2763// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002764bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002765 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002766 const CALL_STATE call_state,
2767 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002768 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002769 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2770 if (UNCALLED == call_state) {
2771 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002772 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002773 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2774 "recommended "
2775 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2776 caller_name, caller_name);
2777 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002778 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2779 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002780 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2781 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2782 ". It is recommended to instead receive all the properties by calling %s with "
2783 "pQueueFamilyPropertyCount that was "
2784 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002785 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002786 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002787 }
2788
2789 return skip;
2790}
2791
Jeff Bolz5c801d12019-10-09 10:38:45 -05002792bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2793 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002794 bool skip = false;
2795
2796 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002797 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002798 if (!as_state->memory_requirements_checked) {
2799 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2800 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2801 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002802 skip |= LogWarning(
2803 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002804 "vkBindAccelerationStructureMemoryNV(): "
2805 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2806 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2807 }
2808 }
2809
2810 return skip;
2811}
2812
Camden05de2d42019-08-19 10:23:56 -06002813bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2814 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002815 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002816 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002817 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002818 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002819 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2820 "vkGetPhysicalDeviceQueueFamilyProperties()");
2821 }
2822 return false;
Camden05de2d42019-08-19 10:23:56 -06002823}
2824
Mike Schuchardt2df08912020-12-15 16:28:09 -08002825bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2826 uint32_t* pQueueFamilyPropertyCount,
2827 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002828 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002829 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002830 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002831 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2832 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2833 }
2834 return false;
Camden05de2d42019-08-19 10:23:56 -06002835}
2836
Jeff Bolz5c801d12019-10-09 10:38:45 -05002837bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002838 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002839 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002840 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002841 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002842 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2843 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2844 }
2845 return false;
Camden05de2d42019-08-19 10:23:56 -06002846}
2847
2848bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2849 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002850 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002851 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002852 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002853 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002854 bool skip = false;
2855 if (call_state == UNCALLED) {
2856 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2857 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002858 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2859 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2860 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002861 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002862 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002863 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2864 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2865 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2866 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002867 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06002868 }
2869 }
2870 return skip;
2871}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002872
2873bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002874 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002875 bool skip = false;
2876
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002877 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2878 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002879 // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002880 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002881 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2882 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002883 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002884 // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002885 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2886 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002887 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002888 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002889 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002890 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002891 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002892 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2893 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2894 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002895 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002896 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2897 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002898 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002899 }
2900 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002901 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002902 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002903 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002904 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2905 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002906 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002907 }
2908 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002909 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2910 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002911 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002912 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002913 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002914 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06002915 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002916 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2917 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2918 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002919 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002920 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2921 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002922 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002923 }
2924 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002925 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002926 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002927 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002928 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2929 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002930 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002931 }
2932 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2933 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002934 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002935 }
2936 }
2937 }
2938 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002939 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2940 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002941 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002942 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002943 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2944 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002945 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002946 }
2947 }
2948 }
2949
2950 return skip;
2951}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002952
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002953void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2954 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002955 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002956 return;
2957 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002958
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002959 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2960 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2961 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2962 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04002963 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002964 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002965 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002966 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002967 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2968 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2969 image_state->sparse_metadata_bound = true;
2970 }
2971 }
2972 }
2973 }
2974}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002975
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002976bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002977 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002978 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002979 // We don't know the accurate render area in a secondary,
2980 // so assume we clear the entire frame buffer.
2981 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2982 return true;
2983 }
2984
2985 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2986 for (uint32_t i = 0; i < rectCount; i++) {
2987 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002988 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002989 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2990 return true;
2991 }
2992 }
2993
2994 return false;
2995}
2996
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002997bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
2998 VkImageAspectFlags aspects, bool secondary) const {
2999 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003000 bool skip = false;
3001
3002 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3003 return skip;
3004 }
3005
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003006 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003007
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003008 auto attachment_itr =
3009 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3010 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003011
3012 // Only report aspects which haven't been touched yet.
3013 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003014 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003015 new_aspects &= ~attachment_itr->aspects;
3016 }
3017
3018 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003019 if (!cmd.hasDrawCmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003020 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003021 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003022 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3023 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003024 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003025 }
3026
3027 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3028 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3029 skip |= LogPerformanceWarning(
3030 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3031 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3032 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3033 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003034 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003035 }
3036
3037 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3038 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003039 skip |=
3040 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3041 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3042 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3043 "it is more efficient.",
3044 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003045 }
3046
3047 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3048 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003049 skip |=
3050 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3051 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3052 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3053 "it is more efficient.",
3054 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003055 }
3056
3057 return skip;
3058}
3059
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003060bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003061 const VkClearAttachment* pAttachments, uint32_t rectCount,
3062 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003063 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003064 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003065 if (!cb_node) return skip;
3066
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003067 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3068 // Defer checks to ExecuteCommands.
3069 return skip;
3070 }
3071
3072 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003073 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003074 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003075 }
3076
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003077 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3078 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003079 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003080 if (rp) {
3081 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3082
3083 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003084 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003085
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003086 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3087 uint32_t color_attachment = attachment.colorAttachment;
3088 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003089 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003090 }
3091
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003092 if (subpass.pDepthStencilAttachment &&
3093 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003094 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003095 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003096 }
3097 }
3098 }
3099
Nadav Gevaf0808442021-05-21 13:51:25 -04003100 if (VendorCheckEnabled(kBPVendorAMD)) {
3101 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3102 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3103 bool black_check = false;
3104 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3105 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3106 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3107 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3108 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3109
3110 bool white_check = false;
3111 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3112 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3113 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3114 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3115 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3116
3117 if (black_check && white_check) {
3118 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3119 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3120 "Consider changing to one of the following:"
3121 "RGBA(0, 0, 0, 0) "
3122 "RGBA(0, 0, 0, 1) "
3123 "RGBA(1, 1, 1, 0) "
3124 "RGBA(1, 1, 1, 1)",
3125 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3126 }
3127 } else {
3128 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3129 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3130 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3131 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3132 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3133 "attachment %" PRId32 " is not a fast clear value."
3134 "Consider changing to one of the following:"
3135 "D=0.0f, S=0"
3136 "D=1.0f, S=0",
3137 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3138 }
3139 }
3140 }
3141 }
3142
Camden Stockerf55721f2019-09-09 11:04:49 -06003143 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003144}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003145
3146bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3147 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3148 const VkImageResolve* pRegions) const {
3149 bool skip = false;
3150
3151 skip |= VendorCheckEnabled(kBPVendorArm) &&
3152 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3153 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3154 "This is a very slow and extremely bandwidth intensive path. "
3155 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3156 VendorSpecificTag(kBPVendorArm));
3157
3158 return skip;
3159}
3160
Jeff Leger178b1e52020-10-05 12:22:23 -04003161bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3162 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3163 bool skip = false;
3164
3165 skip |= VendorCheckEnabled(kBPVendorArm) &&
3166 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3167 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3168 "This is a very slow and extremely bandwidth intensive path. "
3169 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3170 VendorSpecificTag(kBPVendorArm));
3171
3172 return skip;
3173}
3174
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003175bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3176 const VkResolveImageInfo2* pResolveImageInfo) const {
3177 bool skip = false;
3178
3179 skip |= VendorCheckEnabled(kBPVendorArm) &&
3180 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3181 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3182 "This is a very slow and extremely bandwidth intensive path. "
3183 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3184 VendorSpecificTag(kBPVendorArm));
3185
3186 return skip;
3187}
3188
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003189void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3190 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3191 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003192 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003193 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003194 auto src = Get<bp_state::Image>(srcImage);
3195 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003196
3197 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003198 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3199 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003200 }
3201}
3202
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003203void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3204 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003205 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003206 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003207 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3208 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003209 uint32_t regionCount = pResolveImageInfo->regionCount;
3210
3211 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003212 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3213 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003214 }
3215}
3216
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003217void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3218 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003219 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003220 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003221 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3222 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003223 uint32_t regionCount = pResolveImageInfo->regionCount;
3224
3225 for (uint32_t i = 0; i < regionCount; i++) {
3226 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3227 pResolveImageInfo->pRegions[i].srcSubresource);
3228 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3229 pResolveImageInfo->pRegions[i].dstSubresource);
3230 }
3231}
3232
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003233void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3234 const VkClearColorValue* pColor, uint32_t rangeCount,
3235 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003236 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003237 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003238 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003239
3240 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003241 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003242 }
3243}
3244
3245void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3246 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3247 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003248 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003249 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003250 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003251
3252 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003253 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003254 }
3255}
3256
3257void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3258 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3259 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003260 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003261 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003262 auto src = Get<bp_state::Image>(srcImage);
3263 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003264
3265 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003266 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3267 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003268 }
3269}
3270
3271void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3272 VkImageLayout dstImageLayout, uint32_t regionCount,
3273 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003274 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003275 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003276 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003277
3278 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003279 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003280 }
3281}
3282
3283void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3284 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003285 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003286 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003287 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003288
3289 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003290 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003291 }
3292}
3293
3294void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3295 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3296 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003297 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003298 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003299 auto src = Get<bp_state::Image>(srcImage);
3300 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003301
3302 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003303 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3304 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003305 }
3306}
3307
Attilio Provenzano02859b22020-02-27 14:17:28 +00003308bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3309 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3310 bool skip = false;
3311
3312 if (VendorCheckEnabled(kBPVendorArm)) {
3313 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3314 skip |= LogPerformanceWarning(
3315 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3316 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3317 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3318 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003319 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003320 }
3321
3322 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3323 skip |= LogPerformanceWarning(
3324 device, kVUID_BestPractices_CreateSampler_LodClamping,
3325 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3326 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3327 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3328 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3329 }
3330
3331 if (pCreateInfo->mipLodBias != 0.0f) {
3332 skip |=
3333 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3334 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3335 "descriptors being created and may cause reduced performance.",
3336 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3337 }
3338
3339 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3340 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3341 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3342 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3343 skip |= LogPerformanceWarning(
3344 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3345 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3346 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3347 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3348 VendorSpecificTag(kBPVendorArm));
3349 }
3350
3351 if (pCreateInfo->unnormalizedCoordinates) {
3352 skip |= LogPerformanceWarning(
3353 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3354 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3355 "descriptors being created and may cause reduced performance.",
3356 VendorSpecificTag(kBPVendorArm));
3357 }
3358
3359 if (pCreateInfo->anisotropyEnable) {
3360 skip |= LogPerformanceWarning(
3361 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3362 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3363 "and may cause reduced performance.",
3364 VendorSpecificTag(kBPVendorArm));
3365 }
3366 }
3367
3368 return skip;
3369}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003370
Nadav Gevaf0808442021-05-21 13:51:25 -04003371void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3372 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3373 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3374 void* cgpl_state) {
3375 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3376 pPipelines);
3377 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003378 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003379}
3380
3381bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3382 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3383 const VkCopyDescriptorSet* pDescriptorCopies) const {
3384 bool skip = false;
3385 if (VendorCheckEnabled(kBPVendorAMD)) {
3386 if (descriptorCopyCount > 0) {
3387 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3388 "%s Performance warning: copying descriptor sets is not recommended",
3389 VendorSpecificTag(kBPVendorAMD));
3390 }
3391 }
3392
3393 return skip;
3394}
3395
3396bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3397 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3398 const VkAllocationCallbacks* pAllocator,
3399 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3400 bool skip = false;
3401 if (VendorCheckEnabled(kBPVendorAMD)) {
3402 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3403 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3404 "vkUpdateDescriptorSet instead",
3405 VendorSpecificTag(kBPVendorAMD));
3406 }
3407
3408 return skip;
3409}
3410
3411bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3412 const VkClearColorValue* pColor, uint32_t rangeCount,
3413 const VkImageSubresourceRange* pRanges) const {
3414 bool skip = false;
3415 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003416 skip |= LogPerformanceWarning(
3417 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003418 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3419 "vkCmdClearAttachments instead",
3420 VendorSpecificTag(kBPVendorAMD));
3421 }
3422
3423 return skip;
3424}
3425
3426bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3427 VkImageLayout imageLayout,
3428 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3429 const VkImageSubresourceRange* pRanges) const {
3430 bool skip = false;
3431 if (VendorCheckEnabled(kBPVendorAMD)) {
3432 skip |= LogPerformanceWarning(
3433 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3434 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3435 "vkCmdClearAttachments instead",
3436 VendorSpecificTag(kBPVendorAMD));
3437 }
3438
3439 return skip;
3440}
3441
3442bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3443 const VkAllocationCallbacks* pAllocator,
3444 VkPipelineLayout* pPipelineLayout) const {
3445 bool skip = false;
3446 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003447 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003448 // Descriptor sets cost 1 DWORD each.
3449 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3450 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3451 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3452 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3453 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003454 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003455 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003456 }
3457
3458 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3459 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3460 }
3461
3462 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3463 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3464 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3465 "Descriptor sets cost 1 DWORD each. "
3466 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3467 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3468 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3469 VendorSpecificTag(kBPVendorAMD));
3470 }
3471 }
3472
3473 return skip;
3474}
3475
3476bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3477 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3478 const VkImageCopy* pRegions) const {
3479 bool skip = false;
3480 std::stringstream src_image_hex;
3481 std::stringstream dst_image_hex;
3482 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3483 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3484
3485 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003486 auto src_state = Get<IMAGE_STATE>(srcImage);
3487 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003488
3489 if (src_state && dst_state) {
3490 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3491 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3492 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3493 skip |=
3494 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3495 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3496 "image (vkCmdCopyImageToBuffer) "
3497 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3498 "copies when converting between linear and optimal images",
3499 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3500 }
3501 }
3502 }
3503
3504 return skip;
3505}
3506
3507bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3508 VkPipeline pipeline) const {
3509 bool skip = false;
3510
3511 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003512 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003513 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3514 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3515 "for example, by sorting draw calls by pipeline.",
3516 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3517 }
3518 }
3519
3520 return skip;
3521}
3522
3523void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3524 VkFence fence, VkResult result) {
3525 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003526 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003527}
3528
3529bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3530 bool skip = false;
3531
3532 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003533 auto num = num_queue_submissions_.load();
3534 if (num > kNumberOfSubmissionWarningLimitAMD) {
3535 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3536 "%s Performance warning: command buffers submitted %" PRId32
3537 " times this frame. Submitting command buffers has a CPU "
3538 "and GPU overhead. Submit fewer times to incur less overhead.",
3539 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003540 }
3541 }
3542
3543 return skip;
3544}
3545
3546void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3547 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3548 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3549 uint32_t bufferMemoryBarrierCount,
3550 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3551 uint32_t imageMemoryBarrierCount,
3552 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003553 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003554}
3555
3556bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3557 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3558 bool skip = false;
3559 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003560 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003561 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3562 "%s Performance warning: High number of vkSemaphore objects created."
3563 "Minimize the amount of queue synchronization that is used. "
3564 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3565 VendorSpecificTag(kBPVendorAMD));
3566 }
3567 }
3568
3569 return skip;
3570}
3571
3572bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3573 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3574 bool skip = false;
3575 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003576 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003577 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3578 "%s Performance warning: High number of VkFence objects created."
3579 "Minimize the amount of CPU-GPU synchronization that is used. "
3580 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3581 VendorSpecificTag(kBPVendorAMD));
3582 }
3583 }
3584
3585 return skip;
3586}
3587
Sam Walls8e77e4f2020-03-16 20:47:40 +00003588void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3589
3590bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3591 // look for a cache hit
3592 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3593 if (hit != _entries.end()) {
3594 // mark the cache hit as being most recently used
3595 hit->age = iteration++;
3596 return true;
3597 }
3598
3599 // if there's no cache hit, we need to model the entry being inserted into the cache
3600 CacheEntry new_entry = {value, iteration};
3601 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3602 // if there is still space left in the cache, use the next available slot
3603 *(_entries.begin() + iteration) = new_entry;
3604 } else {
3605 // otherwise replace the least recently used cache entry
3606 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3607 *lru = new_entry;
3608 }
3609 iteration++;
3610 return false;
3611}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003612
3613bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3614 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003615 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003616 bool skip = false;
3617 if (swapchain_data && swapchain_data->images.size() == 0) {
3618 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3619 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3620 "vkGetSwapchainImagesKHR after swapchain creation.");
3621 }
3622 return skip;
3623}
3624
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003625void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3626 if (no_pointer) {
3627 if (UNCALLED == call_state) {
3628 call_state = QUERY_COUNT;
3629 }
3630 } else { // Save queue family properties
3631 call_state = QUERY_DETAILS;
3632 }
3633}
3634
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003635void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3636 uint32_t* pQueueFamilyPropertyCount,
3637 VkQueueFamilyProperties* pQueueFamilyProperties) {
3638 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3639 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003640 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003641 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003642 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3643 nullptr == pQueueFamilyProperties);
3644 }
3645}
3646
3647void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3648 uint32_t* pQueueFamilyPropertyCount,
3649 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3650 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3651 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003652 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003653 if (bp_pd_state) {
3654 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3655 nullptr == pQueueFamilyProperties);
3656 }
3657}
3658
3659void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3660 uint32_t* pQueueFamilyPropertyCount,
3661 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3662 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3663 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003664 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003665 if (bp_pd_state) {
3666 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3667 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003668 }
3669}
3670
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003671void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3672 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003673 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003674 if (bp_pd_state) {
3675 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3676 }
3677}
3678
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003679void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3680 VkPhysicalDeviceFeatures2* pFeatures) {
3681 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003682 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003683 if (bp_pd_state) {
3684 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3685 }
3686}
3687
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003688void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3689 VkPhysicalDeviceFeatures2* pFeatures) {
3690 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003691 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003692 if (bp_pd_state) {
3693 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3694 }
3695}
3696
3697void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3698 VkSurfaceKHR surface,
3699 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3700 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003701 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003702 if (bp_pd_state) {
3703 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3704 }
3705}
3706
3707void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3708 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3709 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003710 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003711 if (bp_pd_state) {
3712 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3713 }
3714}
3715
3716void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3717 VkSurfaceKHR surface,
3718 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3719 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003720 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003721 if (bp_pd_state) {
3722 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3723 }
3724}
3725
3726void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3727 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3728 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003729 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003730 if (bp_pd_data) {
3731 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3732
3733 if (*pPresentModeCount) {
3734 if (call_state < QUERY_COUNT) {
3735 call_state = QUERY_COUNT;
3736 }
3737 }
3738 if (pPresentModes) {
3739 if (call_state < QUERY_DETAILS) {
3740 call_state = QUERY_DETAILS;
3741 }
3742 }
3743 }
3744}
3745
3746void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3747 uint32_t* pSurfaceFormatCount,
3748 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003749 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003750 if (bp_pd_data) {
3751 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3752
3753 if (*pSurfaceFormatCount) {
3754 if (call_state < QUERY_COUNT) {
3755 call_state = QUERY_COUNT;
3756 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003757 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003758 }
3759 if (pSurfaceFormats) {
3760 if (call_state < QUERY_DETAILS) {
3761 call_state = QUERY_DETAILS;
3762 }
3763 }
3764 }
3765}
3766
3767void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3768 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3769 uint32_t* pSurfaceFormatCount,
3770 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003771 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003772 if (bp_pd_data) {
3773 if (*pSurfaceFormatCount) {
3774 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3775 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3776 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003777 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003778 }
3779 if (pSurfaceFormats) {
3780 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3781 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3782 }
3783 }
3784 }
3785}
3786
3787void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3788 uint32_t* pPropertyCount,
3789 VkDisplayPlanePropertiesKHR* pProperties,
3790 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003791 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003792 if (bp_pd_data) {
3793 if (*pPropertyCount) {
3794 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3795 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3796 }
3797 }
3798 if (pProperties) {
3799 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3800 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3801 }
3802 }
3803 }
3804}
3805
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003806void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3807 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3808 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003809 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003810 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3811 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3812 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003813 }
3814 }
3815}
3816
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003817void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3818 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3819
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003820 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003821 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003822 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003823 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003824 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003825 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003826 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003827 }
3828 }
3829 }
3830}