blob: efe9b8396e72a37bf6d7f620ca88e89eb4c4014f [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
LawG475463092022-02-22 10:45:54 +000040const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {{kBPVendorArm, {vendor_specific_arm, "Arm"}},
41 {kBPVendorAMD, {vendor_specific_amd, "AMD"}},
Rodrigo Locattic779cb32022-02-25 19:26:31 -030042 {kBPVendorIMG, {vendor_specific_img, "IMG"}},
43 {kBPVendorNVIDIA, {vendor_specific_nvidia, "NVIDIA"}}};
Attilio Provenzano19d6a982020-02-27 12:41:41 +000044
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
Rodrigo Locattic2d5cf42022-03-01 18:05:26 -0300244 std::vector<std::string> extensions;
245 {
246 uint32_t property_count = 0;
247 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, nullptr) == VK_SUCCESS) {
248 std::vector<VkExtensionProperties> property_list(property_count);
249 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, property_list.data()) == VK_SUCCESS) {
250 extensions.reserve(property_list.size());
251 for (const VkExtensionProperties& properties : property_list) {
252 extensions.push_back(properties.extensionName);
253 }
254 }
255 }
256 }
257
Camden5b184be2019-08-13 07:50:19 -0600258 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300259 const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
260
261 if (white_list(extension_name, kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800262 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700263 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300264 extension_name);
Camden5b184be2019-08-13 07:50:19 -0600265 }
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300266
267 skip |= ValidateDeprecatedExtensions("CreateDevice", extension_name, api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700268 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300269 skip |= ValidateSpecialUseExtensions("CreateDevice", extension_name, kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600270 }
271
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700272 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600273 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700274 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
275 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600276 }
277
LawG43f848c72022-02-23 09:35:21 +0000278 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
279 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100280 skip |= LogPerformanceWarning(
281 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000282 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100283 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
284 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
285 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000286 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100287 }
288
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300289 const bool enabled_pageable_device_local_memory = IsExtEnabled(device_extensions.vk_ext_pageable_device_local_memory);
290 if (VendorCheckEnabled(kBPVendorNVIDIA) && !enabled_pageable_device_local_memory &&
291 std::find(extensions.begin(), extensions.end(), VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) != extensions.end()) {
292 skip |= LogPerformanceWarning(
293 device, kVUID_BestPractices_CreateDevice_PageableDeviceLocalMemory,
294 "%s vkCreateDevice() called without pageable device local memory. "
295 "Use pageableDeviceLocalMemory from VK_EXT_pageable_device_local_memory when it is available.",
296 VendorSpecificTag(kBPVendorNVIDIA));
297 }
298
Camden5b184be2019-08-13 07:50:19 -0600299 return skip;
300}
301
302bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500303 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600304 bool skip = false;
305
306 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700307 std::stringstream buffer_hex;
308 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600309
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700310 skip |= LogWarning(
311 device, kVUID_BestPractices_SharingModeExclusive,
312 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
313 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700314 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600315 }
316
317 return skip;
318}
319
320bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500321 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600322 bool skip = false;
323
324 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700325 std::stringstream image_hex;
326 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600327
328 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700329 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
330 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
331 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700332 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600333 }
334
ziga-lunarg6df3d102022-03-18 17:02:14 +0100335 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
336 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
337 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
338 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
339 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
340 }
341
LawG4655f59c2022-02-23 13:55:55 +0000342 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000343 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
344 skip |= LogPerformanceWarning(
345 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000346 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000347 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
348 "and do not need to be backed by physical storage. "
349 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000350 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000351 }
352 }
353
LawG4ba113892022-02-23 14:39:02 +0000354 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
355 skip |= LogPerformanceWarning(
356 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
357 "%s vkCreateImage(): Trying to create an image with %u samples. "
358 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
359 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
360 }
361
362 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
363 skip |= LogPerformanceWarning(
364 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
365 "%s vkCreateImage(): Trying to create an image with %u samples. "
366 "The device may not have full support for true multisampling for images with more than %u samples. "
367 "XT devices support up to 8 samples, XE up to 4 samples.",
368 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
369 }
370
LawG4db16f802022-03-21 17:33:39 +0000371 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
372 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
373 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
374 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
375 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
376 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
377 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
378 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
379 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
380 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
381 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
382 VendorSpecificTag(kBPVendorIMG));
383 }
384
Nadav Gevaf0808442021-05-21 13:51:25 -0400385 if (VendorCheckEnabled(kBPVendorAMD)) {
386 std::stringstream image_hex;
387 image_hex << "0x" << std::hex << HandleToUint64(pImage);
388
389 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
390 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
391 skip |= LogPerformanceWarning(device,
392 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
393 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
394 "Using a SHARING_MODE_CONCURRENT "
395 "is not recommended with color and depth targets",
396 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
397 }
398
399 if ((pCreateInfo->usage &
400 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
401 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
402 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
403 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
404 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
405 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
406 }
407
408 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
409 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
410 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
411 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
412 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
413 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
414 }
415 }
416
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300417 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
418 std::stringstream image_hex;
419 image_hex << "0x" << std::hex << HandleToUint64(pImage);
420
421 if (pCreateInfo->tiling == VK_IMAGE_TILING_LINEAR) {
422 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateImage_TilingLinear,
423 "%s Performance warning: image (%s) is created with tiling VK_IMAGE_TILING_LINEAR. "
424 "Use VK_IMAGE_TILING_OPTIMAL instead.",
425 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
426 }
Rodrigo Locatti3290c2b2022-03-09 18:25:56 -0300427
428 if (pCreateInfo->format == VK_FORMAT_D32_SFLOAT || pCreateInfo->format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
429 skip |= LogPerformanceWarning(
430 device, kVUID_BestPractices_CreateImage_Depth32Format,
431 "%s Performance warning: image (%s) is created with a 32-bit depth format. Use VK_FORMAT_D24_UNORM_S8_UINT or "
432 "VK_FORMAT_D16_UNORM instead, unless the extra precision is needed.",
433 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
434 }
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300435 }
436
Camden5b184be2019-08-13 07:50:19 -0600437 return skip;
438}
439
440bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500441 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600442 bool skip = false;
443
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600444 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600445 if (bp_pd_state) {
446 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
447 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
448 "vkCreateSwapchainKHR() called before getting surface capabilities from "
449 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
450 }
Camden83a9c372019-08-14 11:41:38 -0600451
Shannon McPherson73e58c82021-03-05 17:14:26 -0700452 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
453 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600454 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
455 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
456 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
457 }
Camden83a9c372019-08-14 11:41:38 -0600458
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600459 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
460 skip |= LogWarning(
461 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
462 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
463 }
Camden83a9c372019-08-14 11:41:38 -0600464 }
465
Camden5b184be2019-08-13 07:50:19 -0600466 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700467 skip |=
468 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600469 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700470 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
471 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600472 }
473
ziga-lunarg79beba62022-03-30 01:17:30 +0200474 const auto present_mode = pCreateInfo->presentMode;
475 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
476 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100477 skip |= LogPerformanceWarning(
478 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
479 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
480 ", which means double buffering is going "
481 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
482 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
483 "3 to use triple buffering to maximize performance in such cases.",
484 pCreateInfo->minImageCount);
485 }
486
Szilard Pappd5f0f812020-06-22 09:01:29 +0100487 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
488 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
489 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
490 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
491 "Presentation modes which are not FIFO will present the latest available frame and discard other "
492 "frame(s) if any.",
493 VendorSpecificTag(kBPVendorArm));
494 }
495
Camden5b184be2019-08-13 07:50:19 -0600496 return skip;
497}
498
499bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
500 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500501 const VkAllocationCallbacks* pAllocator,
502 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600503 bool skip = false;
504
505 for (uint32_t i = 0; i < swapchainCount; i++) {
506 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700507 skip |= LogWarning(
508 device, kVUID_BestPractices_SharingModeExclusive,
509 "Warning: A shared swapchain (index %" PRIu32
510 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
511 "queues (queueFamilyIndexCount of %" PRIu32 ").",
512 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600513 }
514 }
515
516 return skip;
517}
518
519bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500520 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600521 bool skip = false;
522
523 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
524 VkFormat format = pCreateInfo->pAttachments[i].format;
525 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
526 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
527 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700528 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
529 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
530 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
531 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
532 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600533 }
534 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700535 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
536 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
537 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
538 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
539 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600540 }
541 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000542
543 const auto& attachment = pCreateInfo->pAttachments[i];
544 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
545 bool access_requires_memory =
546 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
547
548 if (FormatHasStencil(format)) {
549 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
550 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
551 }
552
553 if (access_requires_memory) {
554 skip |= LogPerformanceWarning(
555 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
556 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
557 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
558 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
559 i, static_cast<uint32_t>(attachment.samples));
560 }
561 }
Camden5b184be2019-08-13 07:50:19 -0600562 }
563
564 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
565 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
566 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
567 }
568
569 return skip;
570}
571
Tony-LunarG767180f2020-04-23 14:03:59 -0600572bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
573 const VkImageView* image_views) const {
574 bool skip = false;
575
576 // Check for non-transient attachments that should be transient and vice versa
577 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200578 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600579 bool attachment_should_be_transient =
580 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
581
582 if (FormatHasStencil(attachment.format)) {
583 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
584 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
585 }
586
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600587 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600588 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600589 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600590
591 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
592
593 // The check for an image that should not be transient applies to all GPUs
594 if (!attachment_should_be_transient && image_is_transient) {
595 skip |= LogPerformanceWarning(
596 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
597 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
598 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
599 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
600 i);
601 }
602
603 bool supports_lazy = false;
604 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
605 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
606 supports_lazy = true;
607 }
608 }
609
610 // The check for an image that should be transient only applies to GPUs supporting
611 // lazily allocated memory
612 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
613 skip |= LogPerformanceWarning(
614 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
615 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
616 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
617 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
618 i);
619 }
620 }
621 }
622 return skip;
623}
624
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000625bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
626 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
627 bool skip = false;
628
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600629 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800630 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600631 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000632 }
633
634 return skip;
635}
636
Sam Wallse746d522020-03-16 21:20:23 +0000637bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
638 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
639 bool skip = false;
640 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
641
642 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700643 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000644 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
645 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700646 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000647 skip |= LogPerformanceWarning(
648 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
649 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
650 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
651 VendorSpecificTag(kBPVendorArm));
652 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200653
654 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
655 // Track number of descriptorSets allowable in this pool
656 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
657 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
658 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
659 ". This pool only has %" PRIu32 " descriptorSets remaining.",
660 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
661 pool_state->GetAvailableSets());
662 }
663 }
Sam Wallse746d522020-03-16 21:20:23 +0000664 }
665
666 return skip;
667}
668
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600669void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
670 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000671 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700672 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
673 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000674 // we record successful allocations by subtracting the allocation count from the last recorded free count
675 const auto alloc_count = pAllocateInfo->descriptorSetCount;
676 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700677 if (pool_state->freed_count > alloc_count) {
678 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700679 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700680 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700681 }
Sam Wallse746d522020-03-16 21:20:23 +0000682 }
683 }
684}
685
686void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
687 const VkDescriptorSet* pDescriptorSets, VkResult result) {
688 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
689 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700690 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000691 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700692 if (pool_state) {
693 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000694 }
695 }
696}
697
Camden5b184be2019-08-13 07:50:19 -0600698bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500699 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600700 bool skip = false;
701
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700702 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700703 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
704 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600705 }
706
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000707 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
708 skip |= LogPerformanceWarning(
709 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600710 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
711 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000712 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
713 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
714 }
715
Camden83a9c372019-08-14 11:41:38 -0600716 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
717
718 return skip;
719}
720
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600721void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
722 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
723 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700724 if (result != VK_SUCCESS) {
725 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
726 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800727 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700728 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600729 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700730 return;
731 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700732}
Camden Stocker9738af92019-10-16 13:54:03 -0700733
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600734void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
735 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700736 auto error = std::find(error_codes.begin(), error_codes.end(), result);
737 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000738 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
739 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
740
741 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
742 if (common_failure != common_failure_codes.end()) {
743 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
744 } else {
745 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
746 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700747 return;
748 }
749 auto success = std::find(success_codes.begin(), success_codes.end(), result);
750 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600751 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
752 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500753 }
754}
755
Jeff Bolz5c801d12019-10-09 10:38:45 -0500756bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
757 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700758 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600759 bool skip = false;
760
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700761 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600762
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700763 for (const auto& item : mem_info->ObjectBindings()) {
764 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600765 LogObjectList objlist(device);
766 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600767 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600768 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 -0600769 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600770 }
771
Camden5b184be2019-08-13 07:50:19 -0600772 return skip;
773}
774
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000775bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600776 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700777 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600778
sfricke-samsunge2441192019-11-06 14:07:57 -0800779 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700780 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
781 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
782 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600783 }
784
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700785 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000786
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300787 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000788 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
789 skip |= LogPerformanceWarning(
790 device, kVUID_BestPractices_SmallDedicatedAllocation,
791 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600792 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
793 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000794 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
795 }
796
Camden Stockerb603cc82019-09-03 10:09:02 -0600797 return skip;
798}
799
800bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500801 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600802 bool skip = false;
803 const char* api_name = "BindBufferMemory()";
804
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000805 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600806
807 return skip;
808}
809
810bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500811 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600812 char api_name[64];
813 bool skip = false;
814
815 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200816 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000817 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600818 }
819
820 return skip;
821}
Camden Stockerb603cc82019-09-03 10:09:02 -0600822
823bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500824 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600825 char api_name[64];
826 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600827
Camden Stocker8b798ab2019-09-03 10:33:28 -0600828 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200829 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000830 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600831 }
832
833 return skip;
834}
835
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000836bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600837 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700838 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600839
sfricke-samsung71bc6572020-04-29 15:49:43 -0700840 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600841 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700842 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
843 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
844 api_name, report_data->FormatHandle(image).c_str());
845 }
846 } else {
847 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
848 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600849 }
850
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700851 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000852
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600853 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000854 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
855 skip |= LogPerformanceWarning(
856 device, kVUID_BestPractices_SmallDedicatedAllocation,
857 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600858 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
859 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000860 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
861 }
862
863 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
864 // make sure this type is actually used.
865 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
866 // (i.e.most tile - based renderers)
867 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
868 bool supports_lazy = false;
869 uint32_t suggested_type = 0;
870
871 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600872 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000873 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
874 supports_lazy = true;
875 suggested_type = i;
876 break;
877 }
878 }
879 }
880
881 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
882
883 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
884 skip |= LogPerformanceWarning(
885 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600886 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000887 "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 -0600888 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600889 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000890 }
891 }
892
Camden Stocker8b798ab2019-09-03 10:33:28 -0600893 return skip;
894}
895
896bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500897 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600898 bool skip = false;
899 const char* api_name = "vkBindImageMemory()";
900
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000901 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600902
903 return skip;
904}
905
906bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500907 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600908 char api_name[64];
909 bool skip = false;
910
911 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200912 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700913 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600914 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
915 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600916 }
917
918 return skip;
919}
920
921bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500922 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600923 char api_name[64];
924 bool skip = false;
925
926 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200927 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000928 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600929 }
930
931 return skip;
932}
Camden83a9c372019-08-14 11:41:38 -0600933
Attilio Provenzano02859b22020-02-27 14:17:28 +0000934static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
935 switch (format) {
936 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
937 case VK_FORMAT_R16_SFLOAT:
938 case VK_FORMAT_R16G16_SFLOAT:
939 case VK_FORMAT_R16G16B16_SFLOAT:
940 case VK_FORMAT_R16G16B16A16_SFLOAT:
941 case VK_FORMAT_R32_SFLOAT:
942 case VK_FORMAT_R32G32_SFLOAT:
943 case VK_FORMAT_R32G32B32_SFLOAT:
944 case VK_FORMAT_R32G32B32A32_SFLOAT:
945 return false;
946
947 default:
948 return true;
949 }
950}
951
952bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
953 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
954 bool skip = false;
955
956 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700957 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000958
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700959 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
960 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
961 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000962 return skip;
963 }
964
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600965 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200966 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000967
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200968 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
969 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
970
971 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200972 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000973 uint32_t att = subpass.pColorAttachments[j].attachment;
974
975 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
976 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
977 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
978 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
979 "color attachment #%u makes use "
980 "of a format which cannot be blended at full throughput when using MSAA.",
981 VendorSpecificTag(kBPVendorArm), i, j);
982 }
983 }
984 }
985 }
986
987 return skip;
988}
989
Nadav Gevaf0808442021-05-21 13:51:25 -0400990void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
991 const VkComputePipelineCreateInfo* pCreateInfos,
992 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
993 VkResult result, void* pipe_state) {
994 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700995 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -0400996}
997
Camden5b184be2019-08-13 07:50:19 -0600998bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
999 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001000 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001001 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001002 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1003 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +01001004 if (skip) {
1005 return skip;
1006 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001007 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001008
1009 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001010 skip |= LogPerformanceWarning(
1011 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1012 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
1013 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001014 }
1015
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001016 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001017 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001018
Tony-LunarGb6a2daf2022-07-29 11:30:55 -06001019 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV) && create_info.pVertexInputState) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001020 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001021 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001022 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
1023 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001024 count++;
1025 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001026 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001027 if (count > kMaxInstancedVertexBuffers) {
1028 skip |= LogPerformanceWarning(
1029 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
1030 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
1031 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
1032 count, kMaxInstancedVertexBuffers);
1033 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001034 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001035
Szilard Pappaaf2da32020-06-22 10:37:35 +01001036 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1037 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001038 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1039 VendorCheckEnabled(kBPVendorArm)) {
1040 skip |= LogPerformanceWarning(
1041 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1042 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1043 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1044 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1045 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1046 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001047 }
1048
Attilio Provenzano02859b22020-02-27 14:17:28 +00001049 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001050 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001051 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001052 auto prev_pipeline = pipeline_cache_.load();
1053 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001054 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1055 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1056 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1057 }
1058
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001059 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001060 skip |=
1061 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1062 "%s Performance warning: Too many pipelines created, consider consolidation",
1063 VendorSpecificTag(kBPVendorAMD));
1064 }
1065
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001066 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001067 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1068 "%s Performance warning: Use of primitive restart is not recommended",
1069 VendorSpecificTag(kBPVendorAMD));
1070 }
1071
1072 // TODO: this might be too aggressive of a check
1073 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1074 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1075 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1076 VendorSpecificTag(kBPVendorAMD));
1077 }
1078 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001079
Camden5b184be2019-08-13 07:50:19 -06001080 return skip;
1081}
1082
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001083static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1084 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1085 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001086 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001087 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001088 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001089
1090 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1091
1092 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1093 // are only non-null if they are enabled.
1094 if (create_info.pColorBlendState) {
1095 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1096 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1097 for (uint32_t j = 0; j < num_color_attachments; j++) {
1098 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1099 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1100 if (attachment != VK_ATTACHMENT_UNUSED) {
1101 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1102 }
1103 }
1104 }
1105 }
1106
1107 if (create_info.pDepthStencilState &&
1108 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1109 create_info.pDepthStencilState->stencilTestEnable)) {
1110 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1111 if (attachment != VK_ATTACHMENT_UNUSED) {
1112 VkImageAspectFlags aspects = 0;
1113 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1114 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1115 }
1116 if (create_info.pDepthStencilState->stencilTestEnable) {
1117 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1118 }
1119 result.push_back({attachment, aspects});
1120 }
1121 }
1122 return result;
1123}
1124
1125bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1126 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1127 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1128 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1129 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1130
1131std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1132 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1133 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1134 return std::static_pointer_cast<PIPELINE_STATE>(
1135 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001136}
1137
Sam Walls0961ec02020-03-31 16:39:15 +01001138void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1139 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1140 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1141 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001142 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001143 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001144}
1145
Camden5b184be2019-08-13 07:50:19 -06001146bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1147 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001148 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001149 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001150 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1151 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001152
1153 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001154 skip |= LogPerformanceWarning(
1155 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1156 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1157 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001158 }
1159
Nadav Gevaf0808442021-05-21 13:51:25 -04001160 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001161 auto prev_pipeline = pipeline_cache_.load();
1162 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1163 skip |= LogPerformanceWarning(
1164 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1165 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001166 "improve cache hit rate",
1167 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001168 }
1169 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001170
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001171 for (uint32_t i = 0; i < createInfoCount; i++) {
1172 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1173 if (VendorCheckEnabled(kBPVendorArm)) {
1174 skip |= ValidateCreateComputePipelineArm(createInfo);
1175 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001176
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001177 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1178 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1179 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1180 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1181 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1182 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1183 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1184 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1185 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001186 }
1187 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001188 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001189 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001190
1191 return skip;
1192}
1193
1194bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1195 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001196 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001197 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001198 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1199 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001200
1201 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001202 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001203
1204 uint32_t thread_count = x * y * z;
1205
1206 // Generate a priori warnings about work group sizes.
1207 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1208 skip |= LogPerformanceWarning(
1209 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1210 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1211 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1212 "groups with less than %u threads, especially when using barrier() or shared memory.",
1213 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1214 }
1215
1216 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1217 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1218 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1219 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1220 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1221 "%u, %u) is not aligned to %u "
1222 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1223 "leave threads idle on the shader "
1224 "core.",
1225 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1226 kThreadGroupDispatchCountAlignmentArm);
1227 }
1228
sfricke-samsungef15e482022-01-26 11:32:49 -08001229 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1230 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001231
1232 unsigned dimensions = 0;
1233 if (x > 1) dimensions++;
1234 if (y > 1) dimensions++;
1235 if (z > 1) dimensions++;
1236 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1237 dimensions = std::max(dimensions, 1u);
1238
1239 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1240 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1241 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1242 bool accesses_2d = false;
1243 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001244 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001245 if (dim < 0) continue;
1246 auto spvdim = spv::Dim(dim);
1247 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1248 }
1249
1250 if (accesses_2d && dimensions < 2) {
1251 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1252 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1253 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1254 "exhibiting poor spatial locality with respect to one or more shader resources.",
1255 VendorSpecificTag(kBPVendorArm), x, y, z);
1256 }
1257
Camden5b184be2019-08-13 07:50:19 -06001258 return skip;
1259}
1260
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001261bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001262 bool skip = false;
1263
1264 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001265 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1266 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001267 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001268 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1269 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001270 }
1271
1272 return skip;
1273}
1274
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001275bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1276 bool skip = false;
1277
1278 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1279 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1280 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1281 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1282 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1283 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1284 }
1285
1286 return skip;
1287}
1288
1289bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1290 bool skip = false;
1291 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1292
1293 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1294 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1295
1296 return skip;
1297}
1298
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001299void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001300 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1301 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1302 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1303 LogPerformanceWarning(
1304 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1305 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1306 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1307 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1308 "convenient opportunity.",
1309 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1310 }
1311 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001312
1313 // AMD best practice
1314 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001315 num_queue_submissions_ = 0;
1316 num_barriers_objects_ = 0;
1317 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001318}
1319
Jeff Bolz5c801d12019-10-09 10:38:45 -05001320bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1321 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001322 bool skip = false;
1323
1324 for (uint32_t submit = 0; submit < submitCount; submit++) {
1325 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1326 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1327 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001328 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1329 skip |=
1330 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1331 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1332 submit, submit);
1333 }
1334 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1335 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1336 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1337 submit, submit);
1338 }
Camden5b184be2019-08-13 07:50:19 -06001339 }
1340
1341 return skip;
1342}
1343
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001344bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1345 VkFence fence) const {
1346 bool skip = false;
1347
1348 for (uint32_t submit = 0; submit < submitCount; submit++) {
1349 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1350 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1351 }
1352 }
1353
1354 return skip;
1355}
1356
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001357bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1358 VkFence fence) const {
1359 bool skip = false;
1360
1361 for (uint32_t submit = 0; submit < submitCount; submit++) {
1362 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1363 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1364 }
1365 }
1366
1367 return skip;
1368}
1369
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001370bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1371 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1372 bool skip = false;
1373
1374 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1375 skip |= LogPerformanceWarning(
1376 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1377 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1378 "pool instead.");
1379 }
1380
1381 return skip;
1382}
1383
1384bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1385 const VkCommandBufferBeginInfo* pBeginInfo) const {
1386 bool skip = false;
1387
1388 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1389 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1390 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1391 }
1392
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001393 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1394 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001395 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1396 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1397 VendorSpecificTag(kBPVendorArm));
1398 }
1399
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001400 return skip;
1401}
1402
Jeff Bolz5c801d12019-10-09 10:38:45 -05001403bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001404 bool skip = false;
1405
1406 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1407
1408 return skip;
1409}
1410
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001411bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1412 const VkDependencyInfoKHR* pDependencyInfo) const {
1413 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1414}
1415
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001416bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1417 const VkDependencyInfo* pDependencyInfo) const {
1418 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1419}
1420
Jeff Bolz5c801d12019-10-09 10:38:45 -05001421bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1422 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001423 bool skip = false;
1424
1425 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1426
1427 return skip;
1428}
1429
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001430bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1431 VkPipelineStageFlags2KHR stageMask) const {
1432 bool skip = false;
1433
1434 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1435
1436 return skip;
1437}
1438
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001439bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1440 VkPipelineStageFlags2 stageMask) const {
1441 bool skip = false;
1442
1443 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1444
1445 return skip;
1446}
1447
Camden5b184be2019-08-13 07:50:19 -06001448bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1449 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1450 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1451 uint32_t bufferMemoryBarrierCount,
1452 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1453 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001454 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001455 bool skip = false;
1456
1457 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1458 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1459
1460 return skip;
1461}
1462
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001463bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1464 const VkDependencyInfoKHR* pDependencyInfos) const {
1465 bool skip = false;
1466 for (uint32_t i = 0; i < eventCount; i++) {
1467 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1468 }
1469
1470 return skip;
1471}
1472
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001473bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1474 const VkDependencyInfo* pDependencyInfos) const {
1475 bool skip = false;
1476 for (uint32_t i = 0; i < eventCount; i++) {
1477 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1478 }
1479
1480 return skip;
1481}
1482
Camden5b184be2019-08-13 07:50:19 -06001483bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1484 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1485 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1486 uint32_t bufferMemoryBarrierCount,
1487 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1488 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001489 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001490 bool skip = false;
1491
1492 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1493 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1494
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001495 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1496 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1497 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1498 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1499 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1500 "may be discarded, but the newLayout is %s, which is read only.",
1501 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1502 }
1503 }
1504
Nadav Gevaf0808442021-05-21 13:51:25 -04001505 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001506 auto num = num_barriers_objects_.load();
1507 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001508 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001509 "%s Performance warning: In this frame, %" PRIu32
1510 " barriers were already submitted. Barriers have a high cost and can "
1511 "stall the GPU. "
1512 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1513 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001514 }
1515
1516 std::array<VkImageLayout, 3> read_layouts = {
1517 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1518 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1519 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1520 };
1521
1522 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1523 // read to read barriers
1524 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1525 bool old_is_read_layout = found != read_layouts.end();
1526 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1527 bool new_is_read_layout = found != read_layouts.end();
1528 if (old_is_read_layout && new_is_read_layout) {
1529 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1530 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1531 "time you use it.",
1532 VendorSpecificTag(kBPVendorAMD));
1533 }
1534
1535 // general with no storage
1536 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1537 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1538 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1539 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1540 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1541 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1542 VendorSpecificTag(kBPVendorAMD));
1543 }
1544 }
1545 }
1546 }
1547
Camden5b184be2019-08-13 07:50:19 -06001548 return skip;
1549}
1550
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001551bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1552 const VkDependencyInfoKHR* pDependencyInfo) const {
1553 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1554}
1555
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001556bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1557 const VkDependencyInfo* pDependencyInfo) const {
1558 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1559}
1560
Camden5b184be2019-08-13 07:50:19 -06001561bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001562 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001563 bool skip = false;
1564
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001565 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1566
1567 return skip;
1568}
1569
1570bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1571 VkQueryPool queryPool, uint32_t query) const {
1572 bool skip = false;
1573
1574 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001575
1576 return skip;
1577}
1578
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001579bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1580 VkQueryPool queryPool, uint32_t query) const {
1581 bool skip = false;
1582
1583 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1584
1585 return skip;
1586}
1587
Sam Walls0961ec02020-03-31 16:39:15 +01001588void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1589 VkPipeline pipeline) {
1590 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1591
Nadav Gevaf0808442021-05-21 13:51:25 -04001592 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001593 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001594
Sam Walls0961ec02020-03-31 16:39:15 +01001595 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001596 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001597 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001598 if (pipeline_state) {
1599 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001600 assert(cb_node);
1601 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001602
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001603 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001604 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001605
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001606 const auto* blend_state = pipeline_state->ColorBlendState();
1607 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001608
1609 if (blend_state) {
1610 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001611 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001612 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1613 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001614 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001615 }
1616 }
1617 }
1618
1619 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001620 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001621
1622 if (stencil_state && stencil_state->depthTestEnable) {
1623 switch (stencil_state->depthCompareOp) {
1624 case VK_COMPARE_OP_EQUAL:
1625 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1626 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001627 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001628 break;
1629 default:
1630 break;
1631 }
1632 }
Sam Walls0961ec02020-03-31 16:39:15 +01001633 }
1634 }
1635}
1636
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001637static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1638 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1639 const auto& subpass_info = createInfo.pSubpasses[subpass];
1640 if (subpass_info.pResolveAttachments) {
1641 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1642 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1643 }
1644 }
1645 }
1646
1647 return false;
1648}
1649
Attilio Provenzano02859b22020-02-27 14:17:28 +00001650static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1651 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001652 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001653
1654 // If an attachment is ever used as a color attachment,
1655 // resolve attachment or depth stencil attachment,
1656 // it needs to exist on tile at some point.
1657
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001658 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1659 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001660 }
1661
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001662 if (subpass_info.pResolveAttachments) {
1663 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1664 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1665 }
1666 }
1667
1668 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001669 }
1670
1671 return false;
1672}
1673
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001674static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1675 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1676 return false;
1677 }
1678
1679 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001680 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001681
1682 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1683 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1684 return true;
1685 }
1686 }
1687 }
1688
1689 return false;
1690}
1691
Attilio Provenzano02859b22020-02-27 14:17:28 +00001692bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1693 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1694 bool skip = false;
1695
1696 if (!pRenderPassBegin) {
1697 return skip;
1698 }
1699
Gareth Webbdc6549a2021-06-16 03:52:24 +01001700 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1701 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1702 "This render pass has a zero-size render area. It cannot write to any attachments, "
1703 "and can only be used for side effects such as layout transitions.");
1704 }
1705
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001706 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001707 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001708 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001709 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001710 if (rpabi) {
1711 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1712 }
1713 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001714 // Check if any attachments have LOAD operation on them
1715 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001716 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001717
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001718 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001719 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001720 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001721 }
1722
1723 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001724 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001725 }
1726
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001727 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001728
1729 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001730 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1731 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001732 }
1733
1734 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00001735 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
1736 skip |=
1737 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00001738 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00001739 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001740 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00001741 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
1742 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
1743 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1744 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1745 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001746 }
1747 }
paul-lunarg7089e272022-06-20 22:19:37 +02001748
1749 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
1750
1751 bool clearing = false;
1752
1753 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1754 const auto& attachment = rp_state->createInfo.pAttachments[att];
1755
1756 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1757 clearing = true;
1758 break;
1759 }
1760 }
1761
1762 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
1763 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
1764 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
1765 skip |= LogWarning(
1766 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
1767 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
1768 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02001769 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02001770 }
paul-lunarga0a149c2022-06-23 16:18:51 +02001771
1772 // Check if there are more clearValues than attachments
1773 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
1774 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
1775 // This could signal a bug and there seems to be no reason for this to happen on purpose.
1776 skip |= LogWarning(
1777 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
1778 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
1779 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
1780 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
1781 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001782 }
1783
1784 return skip;
1785}
1786
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001787void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1788 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001789 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001790 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1791 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001792 }
1793}
1794
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001795void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1796 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001797 // If we're viewing a 3D slice, ignore base array layer.
1798 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001799 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 +02001800
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001801 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001802 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001803 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1804 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001805
1806 for (uint32_t layer = 0; layer < array_layers; layer++) {
1807 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001808 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1809 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001810 }
1811 }
1812}
1813
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001814void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1815 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1816 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001817 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001818
1819 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001820 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001821 }
1822}
1823
paul-lunarg5eb52062022-06-27 18:57:15 +02001824void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1825 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
1826 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
1827 const CMD_BUFFER_STATE&) -> bool {
1828 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
1829 return false;
1830 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001831}
1832
LawG44d414ba2022-02-23 15:35:41 +00001833void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001834 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001835 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001836 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001837 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 -07001838 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001839 LogPerformanceWarning(
1840 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00001841 "%s %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 +02001842 "image was used, it was written to with STORE_OP_STORE. "
1843 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1844 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00001845 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001846 } 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 +02001847 LogPerformanceWarning(
1848 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00001849 "%s %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 +02001850 "image was used, it was written to with vkCmdClear*Image(). "
1851 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00001852 "tile-based architectures.",
1853 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001854 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001855 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1856 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001857 const char *last_cmd = nullptr;
1858 const char *vuid = nullptr;
1859 const char *suggestion = nullptr;
1860
1861 switch (last_usage) {
1862 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1863 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1864 last_cmd = "vkCmdBlitImage";
1865 suggestion =
1866 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1867 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1868 "which avoids the memory roundtrip.";
1869 break;
1870 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1871 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1872 last_cmd = "vkCmdClear*Image";
1873 suggestion =
1874 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1875 "tile-based architectures. "
1876 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1877 break;
1878 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1879 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1880 last_cmd = "vkCmdCopy*Image";
1881 suggestion =
1882 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1883 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1884 "which avoids the memory roundtrip.";
1885 break;
1886 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1887 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1888 last_cmd = "vkCmdResolveImage";
1889 suggestion =
1890 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1891 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1892 "which avoids the memory roundtrip.";
1893 break;
1894 default:
1895 break;
1896 }
1897
1898 LogPerformanceWarning(
1899 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00001900 "%s %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 +01001901 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00001902 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
1903 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001904 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001905}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001906
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001907void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1908 uint32_t array_layer, uint32_t mip_level) {
1909 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02001910
1911 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
1912 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
1913 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
1914 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
1915 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
1916 "result in undefined behaviour.");
1917 }
1918
LawG44d414ba2022-02-23 15:35:41 +00001919 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
1920 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001921 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001922}
1923
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001924void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1925 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1926 cb.queue_submit_functions_after_render_pass.end());
1927 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001928}
1929
1930void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1931 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001932 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1933 if (cb_node) {
1934 AddDeferredQueueOperations(*cb_node);
1935 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001936}
1937
1938void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1939 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001940 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1941 if (cb_node) {
1942 AddDeferredQueueOperations(*cb_node);
1943 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001944}
1945
1946void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1947 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001948 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1949 if (cb_node) {
1950 AddDeferredQueueOperations(*cb_node);
1951 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001952}
1953
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001954void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1955 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001956 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001957 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001958 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1959}
1960
1961void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1962 const VkRenderPassBeginInfo* pRenderPassBegin,
1963 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1964 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1965 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1966}
1967
1968void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1969 const VkRenderPassBeginInfo* pRenderPassBegin,
1970 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1971 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1972 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1973}
1974
1975void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001976
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001977 if (!pRenderPassBegin) {
1978 return;
1979 }
1980
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001981 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001982
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001983 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001984 if (rp_state) {
1985 // Check load ops
1986 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001987 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001988
1989 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1990 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1991 continue;
1992 }
1993
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001994 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001995
1996 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1997 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001998 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001999 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
2000 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002001 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002002 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002003 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002004 }
2005
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002006 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002007 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002008
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002009 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002010 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2011 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002012 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002013 }
2014 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002015 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002016 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002017
Jeremy Gebben9f537102021-10-05 16:37:12 -06002018 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002019 }
2020
2021 // Check store ops
2022 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002023 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002024
2025 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2026 continue;
2027 }
2028
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002029 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002030
2031 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2032 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002033 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002034 }
2035
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002036 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002037
Jeremy Gebben9f537102021-10-05 16:37:12 -06002038 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002039 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002040 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2041 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002042 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002043 }
2044 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002045 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002046 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002047
Jeremy Gebben9f537102021-10-05 16:37:12 -06002048 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002049 }
2050 }
2051}
2052
Attilio Provenzano02859b22020-02-27 14:17:28 +00002053bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2054 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002055 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2056 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002057 return skip;
2058}
2059
2060bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2061 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002062 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002063 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2064 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002065 return skip;
2066}
2067
2068bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002069 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002070 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2071 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002072 return skip;
2073}
2074
Sam Walls0961ec02020-03-31 16:39:15 +01002075void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2076 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002077 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002078 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002079 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2080 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002081 assert(cb);
2082 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002083 render_pass_state.touchesAttachments.clear();
2084 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002085 render_pass_state.numDrawCallsDepthOnly = 0;
2086 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2087 render_pass_state.colorAttachment = false;
2088 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002089 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002090 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002091
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002092 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002093
2094 // track depth / color attachment usage within the renderpass
2095 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2096 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002097 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002098
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002099 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002100 }
2101}
2102
2103void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2104 VkSubpassContents contents) {
2105 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2106 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2107}
2108
2109void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2110 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2111 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2112 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2113}
2114
2115void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2116 const VkRenderPassBeginInfo* pRenderPassBegin,
2117 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2118 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2119 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2120}
2121
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002122// Generic function to handle validation for all CmdDraw* type functions
2123bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2124 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002125 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002126 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002127 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2128 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002129 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002130
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002131 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002132 if (pipeline_state && pipeline_state->vertex_input_state &&
2133 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002134 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002135 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002136 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002137 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2138 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002139 }
2140 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002141
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002142 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002143 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002144 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002145 if (rp_state) {
2146 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2147 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002148 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002149 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002150 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2151 const auto* raster_state = pipe->RasterizationState();
2152 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2153 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002154 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2155 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2156 }
2157 }
2158 }
2159 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002160 }
2161 return skip;
2162}
2163
Sam Walls0961ec02020-03-31 16:39:15 +01002164void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002165 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002166 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002167 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002168 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002169 }
2170
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002171 if (cb_node->render_pass_state.drawTouchAttachments) {
2172 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2173 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002174 }
2175 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002176 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002177 }
2178}
2179
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002180void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2181 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002182 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2183 // depth prepass warnings First find the lowest enabled draw count
2184 uint32_t lowestEnabledMinDrawCount = 0;
2185 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2186 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2187 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2188
2189 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002190 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2191 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002192 }
2193}
2194
Camden5b184be2019-08-13 07:50:19 -06002195bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002196 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002197 bool skip = false;
2198
2199 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002200 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2201 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002202 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002203 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002204
2205 return skip;
2206}
2207
Sam Walls0961ec02020-03-31 16:39:15 +01002208void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2209 uint32_t firstVertex, uint32_t firstInstance) {
2210 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2211 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2212}
2213
Camden5b184be2019-08-13 07:50:19 -06002214bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002215 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002216 bool skip = false;
2217
2218 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002219 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2220 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002221 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002222 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2223
Attilio Provenzano02859b22020-02-27 14:17:28 +00002224 // Check if we reached the limit for small indexed draw calls.
2225 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002226 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002227 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002228 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00002229 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002230 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00002231 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002232 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2233 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00002234 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
2235 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002236 }
2237
Sam Walls8e77e4f2020-03-16 20:47:40 +00002238 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002239 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002240 }
2241
2242 return skip;
2243}
2244
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002245bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002246 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2247 bool skip = false;
2248
2249 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002250
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002251 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2252 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002253
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002254 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002255 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002256 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2257 const void* ib_mem = ib_mem_state.p_driver_data;
2258 bool primitive_restart_enable = false;
2259
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002260 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002261 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002262 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002263
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002264 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2265 if (ia_state) {
2266 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002267 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002268
2269 // 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 -06002270 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002271 uint32_t scan_stride;
2272 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2273 scan_stride = sizeof(uint8_t);
2274 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2275 scan_stride = sizeof(uint16_t);
2276 } else {
2277 scan_stride = sizeof(uint32_t);
2278 }
2279
2280 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2281 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2282
2283 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2284 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2285 // irrespective of whether or not they're part of the draw call.
2286
2287 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2288 uint32_t min_index = ~0u;
2289 // start with maximum as 0 and adjust to indices in the buffer
2290 uint32_t max_index = 0u;
2291
2292 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2293 // for the given index buffer
2294 uint32_t vertex_shade_count = 0;
2295
2296 PostTransformLRUCacheModel post_transform_cache;
2297
2298 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2299 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2300 // target architecture.
2301 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2302 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2303 post_transform_cache.resize(32);
2304
2305 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2306 uint32_t scan_index;
2307 uint32_t primitive_restart_value;
2308 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2309 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2310 primitive_restart_value = 0xFF;
2311 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2312 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2313 primitive_restart_value = 0xFFFF;
2314 } else {
2315 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2316 primitive_restart_value = 0xFFFFFFFF;
2317 }
2318
2319 max_index = std::max(max_index, scan_index);
2320 min_index = std::min(min_index, scan_index);
2321
2322 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2323 bool in_cache = post_transform_cache.query_cache(scan_index);
2324 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2325 if (!in_cache) vertex_shade_count++;
2326 }
2327 }
2328
2329 // 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 +01002330 // 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
2331 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002332
2333 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002334 skip |=
2335 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2336 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2337 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2338 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2339 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2340 VendorSpecificTag(kBPVendorArm),
2341 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002342 return skip;
2343 }
2344
2345 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2346 // 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 +01002347 const size_t refs_per_bucket = 64;
2348 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2349
2350 const uint32_t n_indices = max_index - min_index + 1;
2351 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2352 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2353
2354 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2355 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002356
2357 // To avoid using too much memory, we run over the indices again.
2358 // Knowing the size from the last scan allows us to record index usage with bitsets
2359 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2360 uint32_t scan_index;
2361 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2362 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2363 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2364 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2365 } else {
2366 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2367 }
2368 // keep track of the set of all indices used to reference vertices in the draw call
2369 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002370 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2371 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002372 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2373 }
2374
2375 uint32_t vertex_reference_count = 0;
2376 for (const auto& bitset : vertex_reference_buckets) {
2377 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2378 }
2379
2380 // 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 -07002381 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002382 // 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 -07002383 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002384
2385 if (utilization < 0.5f) {
2386 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2387 "%s The indices which were specified for the draw call only utilise approximately "
2388 "%.02f%% of the bound vertex buffer.",
2389 VendorSpecificTag(kBPVendorArm), utilization);
2390 }
2391
2392 if (cache_hit_rate <= 0.5f) {
2393 skip |=
2394 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2395 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2396 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2397 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2398 "recently shaded vertices.",
2399 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2400 }
2401 }
2402
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002403 return skip;
2404}
2405
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002406bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2407 const VkCommandBuffer* pCommandBuffers) const {
2408 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002409 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002410 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002411 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002412 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002413 continue;
2414 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002415 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002416 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002417 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2418 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002419 }
2420 }
2421 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002422
2423 if (VendorCheckEnabled(kBPVendorAMD)) {
2424 if (commandBufferCount > 0) {
2425 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2426 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2427 VendorSpecificTag(kBPVendorAMD));
2428 }
2429 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002430 return skip;
2431}
2432
2433void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2434 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002435 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2436
2437 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2438 if (!primary) {
2439 return;
2440 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002441
2442 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002443 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2444 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002445 continue;
2446 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002447
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002448 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2449 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2450 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2451 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002452 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002453 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002454 }
2455 }
2456
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002457 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2458 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002459 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002460
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002461 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2462 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002463 }
2464
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002465}
2466
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002467void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2468 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002469 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002470 auto itr =
2471 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2472 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002473
2474 if (itr != state.touchesAttachments.end()) {
2475 itr->aspects |= aspects;
2476 } else {
2477 state.touchesAttachments.push_back({ fb_attachment, aspects });
2478 }
2479}
2480
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002481void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002482 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2483 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002484 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002485 // If we observe a full clear before any other access to a frame buffer attachment,
2486 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002487 auto itr =
2488 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2489 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002490
2491 uint32_t new_aspects = aspects;
2492 if (itr != state.touchesAttachments.end()) {
2493 new_aspects = aspects & ~itr->aspects;
2494 itr->aspects |= aspects;
2495 } else {
2496 state.touchesAttachments.push_back({ fb_attachment, aspects });
2497 }
2498
2499 if (new_aspects == 0) {
2500 return;
2501 }
2502
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002503 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002504 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2505 // CmdExecuteCommands.
2506 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2507 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2508 }
2509}
2510
2511void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2512 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2513 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002514 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2515
2516 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2517 auto* rp_state = cmd_state->activeRenderPass.get();
2518 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002519 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2520
2521 if (rectCount == 0 || !rp_state) {
2522 return;
2523 }
2524
2525 if (!is_secondary && !fb_state) {
2526 return;
2527 }
2528
2529 // 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 -07002530 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002531
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06002532 if (!rp_state->UsesDynamicRendering()) {
ziga-lunarg885c6542022-03-07 01:08:25 +01002533 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2534 for (uint32_t i = 0; i < attachmentCount; i++) {
2535 auto& attachment = pClearAttachments[i];
2536 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2537 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002538
ziga-lunarg885c6542022-03-07 01:08:25 +01002539 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2540 if (subpass.pDepthStencilAttachment) {
2541 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2542 }
2543 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2544 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002545 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002546
ziga-lunarg885c6542022-03-07 01:08:25 +01002547 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2548 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002549 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002550 aspects, rectCount, pRects);
2551 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002552 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002553 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002554 }
2555 }
2556 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002557}
2558
Attilio Provenzano02859b22020-02-27 14:17:28 +00002559void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2560 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2561 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2562 firstInstance);
2563
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002564 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002565 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2566 cmd_state->small_indexed_draw_call_count++;
2567 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002568
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002569 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002570}
2571
Sam Walls0961ec02020-03-31 16:39:15 +01002572void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2573 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2574 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2575 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2576}
2577
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002578bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2579 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2580 uint32_t maxDrawCount, uint32_t stride) const {
2581 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2582
2583 return skip;
2584}
2585
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002586bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2587 VkDeviceSize offset, VkBuffer countBuffer,
2588 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2589 uint32_t stride) const {
2590 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002591
2592 return skip;
2593}
2594
2595bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002596 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002597 bool skip = false;
2598
2599 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002600 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2601 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002602 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002603 }
2604
2605 return skip;
2606}
2607
Sam Walls0961ec02020-03-31 16:39:15 +01002608void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2609 uint32_t count, uint32_t stride) {
2610 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2611 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2612}
2613
Camden5b184be2019-08-13 07:50:19 -06002614bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002615 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002616 bool skip = false;
2617
2618 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002619 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2620 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002621 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002622 }
2623
2624 return skip;
2625}
2626
Sam Walls0961ec02020-03-31 16:39:15 +01002627void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2628 uint32_t count, uint32_t stride) {
2629 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2630 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2631}
2632
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002633void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2634 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002635 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002636 // For bindless scenarios, we should not attempt to track descriptor set state.
2637 // It is highly uncertain which resources are actually bound.
2638 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002639 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2640 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002641 continue;
2642 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002643
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002644 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002645 VkImageView image_view{VK_NULL_HANDLE};
2646
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002647 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02002648 if (!descriptor) {
2649 continue;
2650 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002651 switch (descriptor->GetClass()) {
2652 case cvdescriptorset::DescriptorClass::Image: {
2653 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2654 image_view = image_descriptor->GetImageView();
2655 }
2656 break;
2657 }
2658 case cvdescriptorset::DescriptorClass::ImageSampler: {
2659 if (const auto image_sampler_descriptor =
2660 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2661 image_view = image_sampler_descriptor->GetImageView();
2662 }
2663 break;
2664 }
2665 default:
2666 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002667 }
2668
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002669 if (image_view) {
2670 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2671 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2672 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002673 }
2674 }
2675 }
2676 }
2677}
2678
2679void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2680 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002681 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2682 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002683}
2684
2685void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2686 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002687 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2688 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002689}
2690
2691void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2692 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002693 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2694 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002695}
2696
Camden5b184be2019-08-13 07:50:19 -06002697bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002698 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002699 bool skip = false;
2700
2701 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002702 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2703 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2704 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2705 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002706 }
2707
2708 return skip;
2709}
Camden83a9c372019-08-14 11:41:38 -06002710
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002711bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2712 bool skip = false;
2713 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2714 skip |= ValidateCmdEndRenderPass(commandBuffer);
2715 return skip;
2716}
2717
2718bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2719 bool skip = false;
2720 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2721 skip |= ValidateCmdEndRenderPass(commandBuffer);
2722 return skip;
2723}
2724
Sam Walls0961ec02020-03-31 16:39:15 +01002725bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2726 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002727 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002728 skip |= ValidateCmdEndRenderPass(commandBuffer);
2729 return skip;
2730}
2731
2732bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2733 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002734 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002735
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002736 if (cmd == nullptr) return skip;
2737 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002738
LawG4b21485c2022-02-28 13:46:48 +00002739 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
2740 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2741 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2742 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
2743 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
2744
2745 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01002746 bool uses_depth =
2747 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01002748 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00002749
Sam Walls0961ec02020-03-31 16:39:15 +01002750 if (uses_depth) {
2751 skip |= LogPerformanceWarning(
2752 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00002753 "%s %s: Depth pre-passes may be in use. In general, this is not recommended in tile-based deferred "
LawG4b21485c2022-02-28 13:46:48 +00002754 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
2755 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
2756 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
2757 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01002758 }
2759
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002760 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2761
LawG40da9c3d2022-03-01 09:51:01 +00002762 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002763 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2764 // it is redundant to have it be part of the render pass.
2765 // Only consider it redundant if it will actually consume bandwidth, i.e.
2766 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2767 // as is using pure input attachments.
2768 // CLEAR -> STORE might be considered a "useful" thing to do, but
2769 // the optimal thing to do is to defer the clear until you're actually
2770 // going to render to the image.
2771
2772 uint32_t num_attachments = rp->createInfo.attachmentCount;
2773 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002774 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2775 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002776 continue;
2777 }
2778
2779 auto& attachment = rp->createInfo.pAttachments[i];
2780
2781 VkImageAspectFlags bandwidth_aspects = 0;
2782
2783 if (!FormatIsStencilOnly(attachment.format) &&
2784 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2785 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2786 if (FormatHasDepth(attachment.format)) {
2787 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2788 } else {
2789 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2790 }
2791 }
2792
2793 if (FormatHasStencil(attachment.format) &&
2794 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2795 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2796 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2797 }
2798
2799 if (!bandwidth_aspects) {
2800 continue;
2801 }
2802
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002803 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002804 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002805 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002806 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002807 untouched_aspects &= ~itr->aspects;
2808 }
2809
2810 if (untouched_aspects) {
2811 skip |= LogPerformanceWarning(
2812 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00002813 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002814 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00002815 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the "
LawG4015be1c2022-03-01 10:37:52 +00002816 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00002817 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002818 }
2819 }
2820 }
2821
Sam Walls0961ec02020-03-31 16:39:15 +01002822 return skip;
2823}
2824
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002825void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002826 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2827 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002828}
2829
2830void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002831 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2832 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002833}
2834
Camden Stocker9c051442019-11-06 14:28:43 -08002835bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2836 const char* api_name) const {
2837 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002838 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002839
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002840 if (bp_pd_state) {
2841 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2842 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2843 "Potential problem with calling %s() without first retrieving properties from "
2844 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2845 api_name);
2846 }
Camden Stocker9c051442019-11-06 14:28:43 -08002847 }
2848
2849 return skip;
2850}
2851
Camden83a9c372019-08-14 11:41:38 -06002852bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002853 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002854 bool skip = false;
2855
Camden Stocker9c051442019-11-06 14:28:43 -08002856 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002857
Camden Stocker9c051442019-11-06 14:28:43 -08002858 return skip;
2859}
2860
2861bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2862 uint32_t planeIndex,
2863 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2864 bool skip = false;
2865
2866 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2867
2868 return skip;
2869}
2870
2871bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2872 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2873 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2874 bool skip = false;
2875
2876 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002877
2878 return skip;
2879}
Camden05de2d42019-08-19 10:23:56 -06002880
2881bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002882 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002883 bool skip = false;
2884
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002885 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002886
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002887 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002888 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002889 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002890 skip |=
2891 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2892 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2893 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002894 }
Camden05de2d42019-08-19 10:23:56 -06002895
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002896 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2897 skip |= LogWarning(
2898 device, kVUID_BestPractices_Swapchain_InvalidCount,
2899 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002900 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002901 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2902 }
2903 }
2904
Camden05de2d42019-08-19 10:23:56 -06002905 return skip;
2906}
2907
2908// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002909bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002910 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002911 const CALL_STATE call_state,
2912 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002913 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002914 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2915 if (UNCALLED == call_state) {
2916 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002917 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002918 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2919 "recommended "
2920 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2921 caller_name, caller_name);
2922 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002923 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2924 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002925 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2926 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2927 ". It is recommended to instead receive all the properties by calling %s with "
2928 "pQueueFamilyPropertyCount that was "
2929 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002930 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002931 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002932 }
2933
2934 return skip;
2935}
2936
Jeff Bolz5c801d12019-10-09 10:38:45 -05002937bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2938 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002939 bool skip = false;
2940
2941 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002942 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002943 if (!as_state->memory_requirements_checked) {
2944 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2945 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2946 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002947 skip |= LogWarning(
2948 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002949 "vkBindAccelerationStructureMemoryNV(): "
2950 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2951 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2952 }
2953 }
2954
2955 return skip;
2956}
2957
Camden05de2d42019-08-19 10:23:56 -06002958bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2959 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002960 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002961 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002962 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002963 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002964 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2965 "vkGetPhysicalDeviceQueueFamilyProperties()");
2966 }
2967 return false;
Camden05de2d42019-08-19 10:23:56 -06002968}
2969
Mike Schuchardt2df08912020-12-15 16:28:09 -08002970bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2971 uint32_t* pQueueFamilyPropertyCount,
2972 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002973 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002974 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002975 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002976 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2977 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2978 }
2979 return false;
Camden05de2d42019-08-19 10:23:56 -06002980}
2981
Jeff Bolz5c801d12019-10-09 10:38:45 -05002982bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002983 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002984 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002985 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002986 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002987 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2988 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2989 }
2990 return false;
Camden05de2d42019-08-19 10:23:56 -06002991}
2992
2993bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2994 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002995 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002996 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002997 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002998 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002999 bool skip = false;
3000 if (call_state == UNCALLED) {
3001 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
3002 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003003 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
3004 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
3005 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06003006 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003007 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003008 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
3009 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
3010 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
3011 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003012 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06003013 }
3014 }
3015 return skip;
3016}
Camden Stocker23cc47d2019-09-03 14:53:57 -06003017
3018bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003019 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003020 bool skip = false;
3021
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003022 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3023 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06003024 // 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 -07003025 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003026 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
3027 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07003028 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06003029 // 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 -07003030 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
3031 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003032 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003033 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003034 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003035 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003036 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003037 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3038 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3039 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003040 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003041 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3042 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003043 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003044 }
3045 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003046 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003047 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003048 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003049 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3050 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003051 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003052 }
3053 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003054 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3055 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003056 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003057 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003058 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003059 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003060 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003061 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3062 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3063 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003064 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003065 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3066 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003067 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003068 }
3069 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003070 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003071 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003072 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003073 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3074 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003075 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003076 }
3077 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3078 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003079 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003080 }
3081 }
3082 }
3083 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003084 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
3085 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003086 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003087 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003088 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3089 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003090 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003091 }
3092 }
3093 }
3094
Rodrigo Locatti7ab778d2022-03-09 18:57:15 -03003095 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3096 auto queue_state = Get<QUEUE_STATE>(queue);
3097 if (queue_state && queue_state->queueFamilyProperties.queueFlags != (VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT)) {
3098 skip |= LogPerformanceWarning(queue, kVUID_BestPractices_QueueBindSparse_NotAsync,
3099 "vkQueueBindSparse() issued on queue %s. All binds should happen on an asynchronous copy "
3100 "queue to hide the OS scheduling and submit costs.",
3101 report_data->FormatHandle(queue).c_str());
3102 }
3103 }
3104
Camden Stocker23cc47d2019-09-03 14:53:57 -06003105 return skip;
3106}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003107
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003108void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3109 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003110 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003111 return;
3112 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003113
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003114 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3115 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3116 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3117 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003118 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003119 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003120 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003121 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003122 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3123 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3124 image_state->sparse_metadata_bound = true;
3125 }
3126 }
3127 }
3128 }
3129}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003130
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003131bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003132 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003133 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003134 // We don't know the accurate render area in a secondary,
3135 // so assume we clear the entire frame buffer.
3136 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3137 return true;
3138 }
3139
3140 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3141 for (uint32_t i = 0; i < rectCount; i++) {
3142 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003143 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003144 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3145 return true;
3146 }
3147 }
3148
3149 return false;
3150}
3151
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003152bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
3153 VkImageAspectFlags aspects, bool secondary) const {
3154 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003155 bool skip = false;
3156
3157 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3158 return skip;
3159 }
3160
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003161 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003162
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003163 auto attachment_itr =
3164 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3165 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003166
3167 // Only report aspects which haven't been touched yet.
3168 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003169 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003170 new_aspects &= ~attachment_itr->aspects;
3171 }
3172
3173 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09003174 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003175 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003176 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003177 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3178 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003179 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003180 }
3181
3182 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3183 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3184 skip |= LogPerformanceWarning(
3185 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3186 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3187 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3188 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003189 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003190 }
3191
3192 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3193 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003194 skip |=
3195 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3196 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3197 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3198 "it is more efficient.",
3199 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003200 }
3201
3202 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3203 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003204 skip |=
3205 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3206 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3207 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3208 "it is more efficient.",
3209 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003210 }
3211
3212 return skip;
3213}
3214
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003215bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003216 const VkClearAttachment* pAttachments, uint32_t rectCount,
3217 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003218 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003219 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003220 if (!cb_node) return skip;
3221
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003222 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3223 // Defer checks to ExecuteCommands.
3224 return skip;
3225 }
3226
3227 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003228 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003229 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003230 }
3231
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003232 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3233 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003234 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003235 if (rp) {
3236 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3237
3238 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003239 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003240
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003241 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3242 uint32_t color_attachment = attachment.colorAttachment;
3243 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003244 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003245 }
3246
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003247 if (subpass.pDepthStencilAttachment &&
3248 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003249 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003250 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003251 }
3252 }
3253 }
3254
Nadav Gevaf0808442021-05-21 13:51:25 -04003255 if (VendorCheckEnabled(kBPVendorAMD)) {
3256 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3257 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3258 bool black_check = false;
3259 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3260 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3261 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3262 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3263 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3264
3265 bool white_check = false;
3266 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3267 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3268 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3269 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3270 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3271
3272 if (black_check && white_check) {
3273 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3274 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3275 "Consider changing to one of the following:"
3276 "RGBA(0, 0, 0, 0) "
3277 "RGBA(0, 0, 0, 1) "
3278 "RGBA(1, 1, 1, 0) "
3279 "RGBA(1, 1, 1, 1)",
3280 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3281 }
3282 } else {
3283 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3284 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3285 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3286 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3287 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3288 "attachment %" PRId32 " is not a fast clear value."
3289 "Consider changing to one of the following:"
3290 "D=0.0f, S=0"
3291 "D=1.0f, S=0",
3292 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3293 }
3294 }
3295 }
3296 }
3297
Camden Stockerf55721f2019-09-09 11:04:49 -06003298 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003299}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003300
3301bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3302 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3303 const VkImageResolve* pRegions) const {
3304 bool skip = false;
3305
3306 skip |= VendorCheckEnabled(kBPVendorArm) &&
3307 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3308 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3309 "This is a very slow and extremely bandwidth intensive path. "
3310 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3311 VendorSpecificTag(kBPVendorArm));
3312
3313 return skip;
3314}
3315
Jeff Leger178b1e52020-10-05 12:22:23 -04003316bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3317 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3318 bool skip = false;
3319
3320 skip |= VendorCheckEnabled(kBPVendorArm) &&
3321 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3322 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3323 "This is a very slow and extremely bandwidth intensive path. "
3324 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3325 VendorSpecificTag(kBPVendorArm));
3326
3327 return skip;
3328}
3329
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003330bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3331 const VkResolveImageInfo2* pResolveImageInfo) const {
3332 bool skip = false;
3333
3334 skip |= VendorCheckEnabled(kBPVendorArm) &&
3335 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3336 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3337 "This is a very slow and extremely bandwidth intensive path. "
3338 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3339 VendorSpecificTag(kBPVendorArm));
3340
3341 return skip;
3342}
3343
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003344void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3345 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3346 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003347 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003348 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003349 auto src = Get<bp_state::Image>(srcImage);
3350 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003351
3352 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003353 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3354 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003355 }
3356}
3357
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003358void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3359 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003360 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003361 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003362 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3363 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003364 uint32_t regionCount = pResolveImageInfo->regionCount;
3365
3366 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003367 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3368 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003369 }
3370}
3371
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003372void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3373 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003374 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003375 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003376 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3377 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003378 uint32_t regionCount = pResolveImageInfo->regionCount;
3379
3380 for (uint32_t i = 0; i < regionCount; i++) {
3381 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3382 pResolveImageInfo->pRegions[i].srcSubresource);
3383 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3384 pResolveImageInfo->pRegions[i].dstSubresource);
3385 }
3386}
3387
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003388void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3389 const VkClearColorValue* pColor, uint32_t rangeCount,
3390 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003391 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003392 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003393 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003394
3395 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003396 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003397 }
3398}
3399
3400void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3401 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3402 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003403 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003404 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003405 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003406
3407 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003408 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003409 }
3410}
3411
3412void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3413 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3414 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003415 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003416 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003417 auto src = Get<bp_state::Image>(srcImage);
3418 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003419
3420 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003421 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3422 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003423 }
3424}
3425
3426void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3427 VkImageLayout dstImageLayout, uint32_t regionCount,
3428 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003429 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003430 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003431 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003432
3433 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003434 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003435 }
3436}
3437
3438void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3439 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003440 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003441 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003442 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003443
3444 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003445 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003446 }
3447}
3448
3449void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3450 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3451 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003452 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003453 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003454 auto src = Get<bp_state::Image>(srcImage);
3455 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003456
3457 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003458 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3459 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003460 }
3461}
3462
Attilio Provenzano02859b22020-02-27 14:17:28 +00003463bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3464 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3465 bool skip = false;
3466
3467 if (VendorCheckEnabled(kBPVendorArm)) {
3468 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3469 skip |= LogPerformanceWarning(
3470 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3471 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3472 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3473 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003474 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003475 }
3476
3477 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3478 skip |= LogPerformanceWarning(
3479 device, kVUID_BestPractices_CreateSampler_LodClamping,
3480 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3481 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3482 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3483 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3484 }
3485
3486 if (pCreateInfo->mipLodBias != 0.0f) {
3487 skip |=
3488 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3489 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3490 "descriptors being created and may cause reduced performance.",
3491 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3492 }
3493
3494 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3495 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3496 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3497 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3498 skip |= LogPerformanceWarning(
3499 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3500 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3501 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3502 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3503 VendorSpecificTag(kBPVendorArm));
3504 }
3505
3506 if (pCreateInfo->unnormalizedCoordinates) {
3507 skip |= LogPerformanceWarning(
3508 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3509 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3510 "descriptors being created and may cause reduced performance.",
3511 VendorSpecificTag(kBPVendorArm));
3512 }
3513
3514 if (pCreateInfo->anisotropyEnable) {
3515 skip |= LogPerformanceWarning(
3516 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3517 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3518 "and may cause reduced performance.",
3519 VendorSpecificTag(kBPVendorArm));
3520 }
3521 }
3522
3523 return skip;
3524}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003525
Nadav Gevaf0808442021-05-21 13:51:25 -04003526void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3527 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3528 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3529 void* cgpl_state) {
3530 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3531 pPipelines);
3532 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003533 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003534}
3535
3536bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3537 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3538 const VkCopyDescriptorSet* pDescriptorCopies) const {
3539 bool skip = false;
3540 if (VendorCheckEnabled(kBPVendorAMD)) {
3541 if (descriptorCopyCount > 0) {
3542 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3543 "%s Performance warning: copying descriptor sets is not recommended",
3544 VendorSpecificTag(kBPVendorAMD));
3545 }
3546 }
3547
3548 return skip;
3549}
3550
3551bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3552 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3553 const VkAllocationCallbacks* pAllocator,
3554 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3555 bool skip = false;
3556 if (VendorCheckEnabled(kBPVendorAMD)) {
3557 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3558 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3559 "vkUpdateDescriptorSet instead",
3560 VendorSpecificTag(kBPVendorAMD));
3561 }
3562
3563 return skip;
3564}
3565
3566bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3567 const VkClearColorValue* pColor, uint32_t rangeCount,
3568 const VkImageSubresourceRange* pRanges) const {
3569 bool skip = false;
3570 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003571 skip |= LogPerformanceWarning(
3572 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003573 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3574 "vkCmdClearAttachments instead",
3575 VendorSpecificTag(kBPVendorAMD));
3576 }
3577
3578 return skip;
3579}
3580
3581bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3582 VkImageLayout imageLayout,
3583 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3584 const VkImageSubresourceRange* pRanges) const {
3585 bool skip = false;
3586 if (VendorCheckEnabled(kBPVendorAMD)) {
3587 skip |= LogPerformanceWarning(
3588 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3589 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3590 "vkCmdClearAttachments instead",
3591 VendorSpecificTag(kBPVendorAMD));
3592 }
3593
3594 return skip;
3595}
3596
3597bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3598 const VkAllocationCallbacks* pAllocator,
3599 VkPipelineLayout* pPipelineLayout) const {
3600 bool skip = false;
3601 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003602 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003603 // Descriptor sets cost 1 DWORD each.
3604 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3605 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3606 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3607 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3608 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003609 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003610 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003611 }
3612
3613 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3614 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3615 }
3616
3617 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3618 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3619 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3620 "Descriptor sets cost 1 DWORD each. "
3621 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3622 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3623 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3624 VendorSpecificTag(kBPVendorAMD));
3625 }
3626 }
3627
3628 return skip;
3629}
3630
3631bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3632 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3633 const VkImageCopy* pRegions) const {
3634 bool skip = false;
3635 std::stringstream src_image_hex;
3636 std::stringstream dst_image_hex;
3637 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3638 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3639
3640 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003641 auto src_state = Get<IMAGE_STATE>(srcImage);
3642 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003643
3644 if (src_state && dst_state) {
3645 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3646 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3647 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3648 skip |=
3649 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3650 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3651 "image (vkCmdCopyImageToBuffer) "
3652 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3653 "copies when converting between linear and optimal images",
3654 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3655 }
3656 }
3657 }
3658
3659 return skip;
3660}
3661
3662bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3663 VkPipeline pipeline) const {
3664 bool skip = false;
3665
3666 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003667 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003668 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3669 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3670 "for example, by sorting draw calls by pipeline.",
3671 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3672 }
3673 }
3674
3675 return skip;
3676}
3677
3678void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3679 VkFence fence, VkResult result) {
3680 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003681 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003682}
3683
3684bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3685 bool skip = false;
3686
3687 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003688 auto num = num_queue_submissions_.load();
3689 if (num > kNumberOfSubmissionWarningLimitAMD) {
3690 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3691 "%s Performance warning: command buffers submitted %" PRId32
3692 " times this frame. Submitting command buffers has a CPU "
3693 "and GPU overhead. Submit fewer times to incur less overhead.",
3694 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003695 }
3696 }
3697
3698 return skip;
3699}
3700
3701void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3702 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3703 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3704 uint32_t bufferMemoryBarrierCount,
3705 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3706 uint32_t imageMemoryBarrierCount,
3707 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003708 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003709}
3710
3711bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3712 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3713 bool skip = false;
3714 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003715 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003716 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3717 "%s Performance warning: High number of vkSemaphore objects created."
3718 "Minimize the amount of queue synchronization that is used. "
3719 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3720 VendorSpecificTag(kBPVendorAMD));
3721 }
3722 }
3723
3724 return skip;
3725}
3726
3727bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3728 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3729 bool skip = false;
3730 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003731 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003732 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3733 "%s Performance warning: High number of VkFence objects created."
3734 "Minimize the amount of CPU-GPU synchronization that is used. "
3735 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3736 VendorSpecificTag(kBPVendorAMD));
3737 }
3738 }
3739
3740 return skip;
3741}
3742
Sam Walls8e77e4f2020-03-16 20:47:40 +00003743void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3744
3745bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3746 // look for a cache hit
3747 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3748 if (hit != _entries.end()) {
3749 // mark the cache hit as being most recently used
3750 hit->age = iteration++;
3751 return true;
3752 }
3753
3754 // if there's no cache hit, we need to model the entry being inserted into the cache
3755 CacheEntry new_entry = {value, iteration};
3756 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3757 // if there is still space left in the cache, use the next available slot
3758 *(_entries.begin() + iteration) = new_entry;
3759 } else {
3760 // otherwise replace the least recently used cache entry
3761 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3762 *lru = new_entry;
3763 }
3764 iteration++;
3765 return false;
3766}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003767
3768bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3769 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003770 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003771 bool skip = false;
3772 if (swapchain_data && swapchain_data->images.size() == 0) {
3773 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3774 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3775 "vkGetSwapchainImagesKHR after swapchain creation.");
3776 }
3777 return skip;
3778}
3779
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003780void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3781 if (no_pointer) {
3782 if (UNCALLED == call_state) {
3783 call_state = QUERY_COUNT;
3784 }
3785 } else { // Save queue family properties
3786 call_state = QUERY_DETAILS;
3787 }
3788}
3789
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003790void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3791 uint32_t* pQueueFamilyPropertyCount,
3792 VkQueueFamilyProperties* pQueueFamilyProperties) {
3793 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3794 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003795 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003796 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003797 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3798 nullptr == pQueueFamilyProperties);
3799 }
3800}
3801
3802void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3803 uint32_t* pQueueFamilyPropertyCount,
3804 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3805 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3806 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003807 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003808 if (bp_pd_state) {
3809 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3810 nullptr == pQueueFamilyProperties);
3811 }
3812}
3813
3814void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3815 uint32_t* pQueueFamilyPropertyCount,
3816 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3817 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3818 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003819 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003820 if (bp_pd_state) {
3821 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3822 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003823 }
3824}
3825
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003826void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3827 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003828 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003829 if (bp_pd_state) {
3830 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3831 }
3832}
3833
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003834void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3835 VkPhysicalDeviceFeatures2* pFeatures) {
3836 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003837 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003838 if (bp_pd_state) {
3839 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3840 }
3841}
3842
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003843void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3844 VkPhysicalDeviceFeatures2* pFeatures) {
3845 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003846 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003847 if (bp_pd_state) {
3848 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3849 }
3850}
3851
3852void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3853 VkSurfaceKHR surface,
3854 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3855 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003856 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003857 if (bp_pd_state) {
3858 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3859 }
3860}
3861
3862void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3863 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3864 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003865 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003866 if (bp_pd_state) {
3867 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3868 }
3869}
3870
3871void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3872 VkSurfaceKHR surface,
3873 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3874 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003875 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003876 if (bp_pd_state) {
3877 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3878 }
3879}
3880
3881void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3882 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3883 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003884 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003885 if (bp_pd_data) {
3886 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3887
3888 if (*pPresentModeCount) {
3889 if (call_state < QUERY_COUNT) {
3890 call_state = QUERY_COUNT;
3891 }
3892 }
3893 if (pPresentModes) {
3894 if (call_state < QUERY_DETAILS) {
3895 call_state = QUERY_DETAILS;
3896 }
3897 }
3898 }
3899}
3900
3901void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3902 uint32_t* pSurfaceFormatCount,
3903 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003904 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003905 if (bp_pd_data) {
3906 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3907
3908 if (*pSurfaceFormatCount) {
3909 if (call_state < QUERY_COUNT) {
3910 call_state = QUERY_COUNT;
3911 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003912 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003913 }
3914 if (pSurfaceFormats) {
3915 if (call_state < QUERY_DETAILS) {
3916 call_state = QUERY_DETAILS;
3917 }
3918 }
3919 }
3920}
3921
3922void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3923 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3924 uint32_t* pSurfaceFormatCount,
3925 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003926 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003927 if (bp_pd_data) {
3928 if (*pSurfaceFormatCount) {
3929 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3930 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3931 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003932 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003933 }
3934 if (pSurfaceFormats) {
3935 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3936 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3937 }
3938 }
3939 }
3940}
3941
3942void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3943 uint32_t* pPropertyCount,
3944 VkDisplayPlanePropertiesKHR* pProperties,
3945 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003946 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003947 if (bp_pd_data) {
3948 if (*pPropertyCount) {
3949 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3950 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3951 }
3952 }
3953 if (pProperties) {
3954 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3955 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3956 }
3957 }
3958 }
3959}
3960
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003961void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3962 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3963 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003964 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003965 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3966 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3967 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003968 }
3969 }
3970}
3971
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003972void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3973 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3974
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003975 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003976 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003977 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003978 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003979 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003980 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003981 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003982 }
3983 }
3984 }
3985}