blob: 02b458f8af750119f95d349a958861ba1acf5ca2 [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 }
427 }
428
Camden5b184be2019-08-13 07:50:19 -0600429 return skip;
430}
431
432bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500433 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600434 bool skip = false;
435
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600436 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600437 if (bp_pd_state) {
438 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
439 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
440 "vkCreateSwapchainKHR() called before getting surface capabilities from "
441 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
442 }
Camden83a9c372019-08-14 11:41:38 -0600443
Shannon McPherson73e58c82021-03-05 17:14:26 -0700444 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
445 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600446 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
447 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
448 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
449 }
Camden83a9c372019-08-14 11:41:38 -0600450
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600451 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
452 skip |= LogWarning(
453 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
454 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
455 }
Camden83a9c372019-08-14 11:41:38 -0600456 }
457
Camden5b184be2019-08-13 07:50:19 -0600458 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700459 skip |=
460 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600461 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700462 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
463 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600464 }
465
ziga-lunarg79beba62022-03-30 01:17:30 +0200466 const auto present_mode = pCreateInfo->presentMode;
467 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
468 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100469 skip |= LogPerformanceWarning(
470 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
471 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
472 ", which means double buffering is going "
473 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
474 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
475 "3 to use triple buffering to maximize performance in such cases.",
476 pCreateInfo->minImageCount);
477 }
478
Szilard Pappd5f0f812020-06-22 09:01:29 +0100479 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
480 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
481 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
482 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
483 "Presentation modes which are not FIFO will present the latest available frame and discard other "
484 "frame(s) if any.",
485 VendorSpecificTag(kBPVendorArm));
486 }
487
Camden5b184be2019-08-13 07:50:19 -0600488 return skip;
489}
490
491bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
492 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500493 const VkAllocationCallbacks* pAllocator,
494 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600495 bool skip = false;
496
497 for (uint32_t i = 0; i < swapchainCount; i++) {
498 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700499 skip |= LogWarning(
500 device, kVUID_BestPractices_SharingModeExclusive,
501 "Warning: A shared swapchain (index %" PRIu32
502 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
503 "queues (queueFamilyIndexCount of %" PRIu32 ").",
504 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600505 }
506 }
507
508 return skip;
509}
510
511bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500512 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600513 bool skip = false;
514
515 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
516 VkFormat format = pCreateInfo->pAttachments[i].format;
517 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
518 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
519 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700520 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
521 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
522 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
523 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
524 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600525 }
526 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700527 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
528 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
529 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
530 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
531 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600532 }
533 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000534
535 const auto& attachment = pCreateInfo->pAttachments[i];
536 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
537 bool access_requires_memory =
538 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
539
540 if (FormatHasStencil(format)) {
541 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
542 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
543 }
544
545 if (access_requires_memory) {
546 skip |= LogPerformanceWarning(
547 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
548 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
549 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
550 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
551 i, static_cast<uint32_t>(attachment.samples));
552 }
553 }
Camden5b184be2019-08-13 07:50:19 -0600554 }
555
556 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
557 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
558 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
559 }
560
561 return skip;
562}
563
Tony-LunarG767180f2020-04-23 14:03:59 -0600564bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
565 const VkImageView* image_views) const {
566 bool skip = false;
567
568 // Check for non-transient attachments that should be transient and vice versa
569 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200570 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600571 bool attachment_should_be_transient =
572 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
573
574 if (FormatHasStencil(attachment.format)) {
575 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
576 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
577 }
578
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600579 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600580 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600581 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600582
583 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
584
585 // The check for an image that should not be transient applies to all GPUs
586 if (!attachment_should_be_transient && image_is_transient) {
587 skip |= LogPerformanceWarning(
588 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
589 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
590 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
591 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
592 i);
593 }
594
595 bool supports_lazy = false;
596 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
597 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
598 supports_lazy = true;
599 }
600 }
601
602 // The check for an image that should be transient only applies to GPUs supporting
603 // lazily allocated memory
604 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
605 skip |= LogPerformanceWarning(
606 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
607 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
608 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
609 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
610 i);
611 }
612 }
613 }
614 return skip;
615}
616
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000617bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
618 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
619 bool skip = false;
620
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600621 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800622 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600623 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000624 }
625
626 return skip;
627}
628
Sam Wallse746d522020-03-16 21:20:23 +0000629bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
630 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
631 bool skip = false;
632 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
633
634 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700635 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000636 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
637 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700638 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000639 skip |= LogPerformanceWarning(
640 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
641 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
642 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
643 VendorSpecificTag(kBPVendorArm));
644 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200645
646 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
647 // Track number of descriptorSets allowable in this pool
648 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
649 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
650 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
651 ". This pool only has %" PRIu32 " descriptorSets remaining.",
652 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
653 pool_state->GetAvailableSets());
654 }
655 }
Sam Wallse746d522020-03-16 21:20:23 +0000656 }
657
658 return skip;
659}
660
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600661void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
662 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000663 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700664 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
665 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000666 // we record successful allocations by subtracting the allocation count from the last recorded free count
667 const auto alloc_count = pAllocateInfo->descriptorSetCount;
668 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700669 if (pool_state->freed_count > alloc_count) {
670 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700671 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700672 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700673 }
Sam Wallse746d522020-03-16 21:20:23 +0000674 }
675 }
676}
677
678void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
679 const VkDescriptorSet* pDescriptorSets, VkResult result) {
680 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
681 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700682 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000683 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700684 if (pool_state) {
685 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000686 }
687 }
688}
689
Camden5b184be2019-08-13 07:50:19 -0600690bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500691 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600692 bool skip = false;
693
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700694 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700695 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
696 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600697 }
698
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000699 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
700 skip |= LogPerformanceWarning(
701 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600702 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
703 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000704 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
705 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
706 }
707
Camden83a9c372019-08-14 11:41:38 -0600708 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
709
710 return skip;
711}
712
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600713void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
714 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
715 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700716 if (result != VK_SUCCESS) {
717 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
718 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800719 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700720 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600721 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700722 return;
723 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700724}
Camden Stocker9738af92019-10-16 13:54:03 -0700725
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600726void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
727 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700728 auto error = std::find(error_codes.begin(), error_codes.end(), result);
729 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000730 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
731 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
732
733 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
734 if (common_failure != common_failure_codes.end()) {
735 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
736 } else {
737 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
738 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700739 return;
740 }
741 auto success = std::find(success_codes.begin(), success_codes.end(), result);
742 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600743 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
744 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500745 }
746}
747
Jeff Bolz5c801d12019-10-09 10:38:45 -0500748bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
749 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700750 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600751 bool skip = false;
752
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700753 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600754
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700755 for (const auto& item : mem_info->ObjectBindings()) {
756 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600757 LogObjectList objlist(device);
758 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600759 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600760 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 -0600761 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600762 }
763
Camden5b184be2019-08-13 07:50:19 -0600764 return skip;
765}
766
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000767bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600768 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700769 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600770
sfricke-samsunge2441192019-11-06 14:07:57 -0800771 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700772 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
773 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
774 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600775 }
776
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700777 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000778
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300779 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000780 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
781 skip |= LogPerformanceWarning(
782 device, kVUID_BestPractices_SmallDedicatedAllocation,
783 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600784 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
785 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000786 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
787 }
788
Camden Stockerb603cc82019-09-03 10:09:02 -0600789 return skip;
790}
791
792bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500793 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600794 bool skip = false;
795 const char* api_name = "BindBufferMemory()";
796
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000797 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600798
799 return skip;
800}
801
802bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500803 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600804 char api_name[64];
805 bool skip = false;
806
807 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200808 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000809 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600810 }
811
812 return skip;
813}
Camden Stockerb603cc82019-09-03 10:09:02 -0600814
815bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500816 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600817 char api_name[64];
818 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600819
Camden Stocker8b798ab2019-09-03 10:33:28 -0600820 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200821 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000822 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600823 }
824
825 return skip;
826}
827
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000828bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600829 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700830 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600831
sfricke-samsung71bc6572020-04-29 15:49:43 -0700832 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600833 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700834 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
835 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
836 api_name, report_data->FormatHandle(image).c_str());
837 }
838 } else {
839 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
840 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600841 }
842
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700843 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000844
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600845 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000846 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
847 skip |= LogPerformanceWarning(
848 device, kVUID_BestPractices_SmallDedicatedAllocation,
849 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600850 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
851 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000852 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
853 }
854
855 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
856 // make sure this type is actually used.
857 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
858 // (i.e.most tile - based renderers)
859 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
860 bool supports_lazy = false;
861 uint32_t suggested_type = 0;
862
863 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600864 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000865 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
866 supports_lazy = true;
867 suggested_type = i;
868 break;
869 }
870 }
871 }
872
873 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
874
875 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
876 skip |= LogPerformanceWarning(
877 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600878 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000879 "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 -0600880 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600881 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000882 }
883 }
884
Camden Stocker8b798ab2019-09-03 10:33:28 -0600885 return skip;
886}
887
888bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500889 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600890 bool skip = false;
891 const char* api_name = "vkBindImageMemory()";
892
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000893 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600894
895 return skip;
896}
897
898bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500899 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600900 char api_name[64];
901 bool skip = false;
902
903 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200904 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700905 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600906 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
907 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600908 }
909
910 return skip;
911}
912
913bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500914 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600915 char api_name[64];
916 bool skip = false;
917
918 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200919 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000920 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600921 }
922
923 return skip;
924}
Camden83a9c372019-08-14 11:41:38 -0600925
Attilio Provenzano02859b22020-02-27 14:17:28 +0000926static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
927 switch (format) {
928 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
929 case VK_FORMAT_R16_SFLOAT:
930 case VK_FORMAT_R16G16_SFLOAT:
931 case VK_FORMAT_R16G16B16_SFLOAT:
932 case VK_FORMAT_R16G16B16A16_SFLOAT:
933 case VK_FORMAT_R32_SFLOAT:
934 case VK_FORMAT_R32G32_SFLOAT:
935 case VK_FORMAT_R32G32B32_SFLOAT:
936 case VK_FORMAT_R32G32B32A32_SFLOAT:
937 return false;
938
939 default:
940 return true;
941 }
942}
943
944bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
945 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
946 bool skip = false;
947
948 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700949 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000950
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700951 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
952 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
953 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000954 return skip;
955 }
956
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600957 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200958 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000959
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200960 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
961 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
962
963 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200964 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000965 uint32_t att = subpass.pColorAttachments[j].attachment;
966
967 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
968 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
969 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
970 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
971 "color attachment #%u makes use "
972 "of a format which cannot be blended at full throughput when using MSAA.",
973 VendorSpecificTag(kBPVendorArm), i, j);
974 }
975 }
976 }
977 }
978
979 return skip;
980}
981
Nadav Gevaf0808442021-05-21 13:51:25 -0400982void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
983 const VkComputePipelineCreateInfo* pCreateInfos,
984 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
985 VkResult result, void* pipe_state) {
986 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700987 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -0400988}
989
Camden5b184be2019-08-13 07:50:19 -0600990bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
991 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600992 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500993 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600994 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
995 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +0100996 if (skip) {
997 return skip;
998 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600999 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001000
1001 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001002 skip |= LogPerformanceWarning(
1003 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1004 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
1005 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001006 }
1007
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001008 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001009 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001010
Tony-LunarGb6a2daf2022-07-29 11:30:55 -06001011 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 +02001012 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001013 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001014 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
1015 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001016 count++;
1017 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001018 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001019 if (count > kMaxInstancedVertexBuffers) {
1020 skip |= LogPerformanceWarning(
1021 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
1022 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
1023 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
1024 count, kMaxInstancedVertexBuffers);
1025 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001026 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001027
Szilard Pappaaf2da32020-06-22 10:37:35 +01001028 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1029 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001030 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1031 VendorCheckEnabled(kBPVendorArm)) {
1032 skip |= LogPerformanceWarning(
1033 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1034 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1035 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1036 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1037 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1038 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001039 }
1040
Attilio Provenzano02859b22020-02-27 14:17:28 +00001041 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001042 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001043 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001044 auto prev_pipeline = pipeline_cache_.load();
1045 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001046 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1047 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1048 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1049 }
1050
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001051 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001052 skip |=
1053 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1054 "%s Performance warning: Too many pipelines created, consider consolidation",
1055 VendorSpecificTag(kBPVendorAMD));
1056 }
1057
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001058 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001059 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1060 "%s Performance warning: Use of primitive restart is not recommended",
1061 VendorSpecificTag(kBPVendorAMD));
1062 }
1063
1064 // TODO: this might be too aggressive of a check
1065 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1066 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1067 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1068 VendorSpecificTag(kBPVendorAMD));
1069 }
1070 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001071
Camden5b184be2019-08-13 07:50:19 -06001072 return skip;
1073}
1074
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001075static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1076 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1077 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001078 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001079 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001080 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001081
1082 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1083
1084 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1085 // are only non-null if they are enabled.
1086 if (create_info.pColorBlendState) {
1087 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1088 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1089 for (uint32_t j = 0; j < num_color_attachments; j++) {
1090 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1091 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1092 if (attachment != VK_ATTACHMENT_UNUSED) {
1093 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1094 }
1095 }
1096 }
1097 }
1098
1099 if (create_info.pDepthStencilState &&
1100 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1101 create_info.pDepthStencilState->stencilTestEnable)) {
1102 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1103 if (attachment != VK_ATTACHMENT_UNUSED) {
1104 VkImageAspectFlags aspects = 0;
1105 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1106 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1107 }
1108 if (create_info.pDepthStencilState->stencilTestEnable) {
1109 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1110 }
1111 result.push_back({attachment, aspects});
1112 }
1113 }
1114 return result;
1115}
1116
1117bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1118 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1119 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1120 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1121 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1122
1123std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1124 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1125 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1126 return std::static_pointer_cast<PIPELINE_STATE>(
1127 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001128}
1129
Sam Walls0961ec02020-03-31 16:39:15 +01001130void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1131 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1132 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1133 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001134 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001135 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001136}
1137
Camden5b184be2019-08-13 07:50:19 -06001138bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1139 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001140 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001141 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001142 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1143 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001144
1145 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001146 skip |= LogPerformanceWarning(
1147 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1148 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1149 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001150 }
1151
Nadav Gevaf0808442021-05-21 13:51:25 -04001152 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001153 auto prev_pipeline = pipeline_cache_.load();
1154 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1155 skip |= LogPerformanceWarning(
1156 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1157 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001158 "improve cache hit rate",
1159 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001160 }
1161 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001162
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001163 for (uint32_t i = 0; i < createInfoCount; i++) {
1164 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1165 if (VendorCheckEnabled(kBPVendorArm)) {
1166 skip |= ValidateCreateComputePipelineArm(createInfo);
1167 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001168
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001169 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1170 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1171 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1172 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1173 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1174 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1175 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1176 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1177 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001178 }
1179 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001180 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001181 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001182
1183 return skip;
1184}
1185
1186bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1187 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001188 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001189 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001190 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1191 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001192
1193 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001194 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001195
1196 uint32_t thread_count = x * y * z;
1197
1198 // Generate a priori warnings about work group sizes.
1199 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1200 skip |= LogPerformanceWarning(
1201 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1202 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1203 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1204 "groups with less than %u threads, especially when using barrier() or shared memory.",
1205 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1206 }
1207
1208 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1209 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1210 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1211 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1212 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1213 "%u, %u) is not aligned to %u "
1214 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1215 "leave threads idle on the shader "
1216 "core.",
1217 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1218 kThreadGroupDispatchCountAlignmentArm);
1219 }
1220
sfricke-samsungef15e482022-01-26 11:32:49 -08001221 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1222 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001223
1224 unsigned dimensions = 0;
1225 if (x > 1) dimensions++;
1226 if (y > 1) dimensions++;
1227 if (z > 1) dimensions++;
1228 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1229 dimensions = std::max(dimensions, 1u);
1230
1231 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1232 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1233 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1234 bool accesses_2d = false;
1235 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001236 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001237 if (dim < 0) continue;
1238 auto spvdim = spv::Dim(dim);
1239 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1240 }
1241
1242 if (accesses_2d && dimensions < 2) {
1243 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1244 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1245 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1246 "exhibiting poor spatial locality with respect to one or more shader resources.",
1247 VendorSpecificTag(kBPVendorArm), x, y, z);
1248 }
1249
Camden5b184be2019-08-13 07:50:19 -06001250 return skip;
1251}
1252
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001253bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001254 bool skip = false;
1255
1256 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001257 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1258 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001259 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001260 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1261 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001262 }
1263
1264 return skip;
1265}
1266
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001267bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1268 bool skip = false;
1269
1270 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1271 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1272 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1273 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1274 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1275 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1276 }
1277
1278 return skip;
1279}
1280
1281bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1282 bool skip = false;
1283 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1284
1285 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1286 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1287
1288 return skip;
1289}
1290
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001291void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001292 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1293 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1294 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1295 LogPerformanceWarning(
1296 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1297 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1298 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1299 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1300 "convenient opportunity.",
1301 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1302 }
1303 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001304
1305 // AMD best practice
1306 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001307 num_queue_submissions_ = 0;
1308 num_barriers_objects_ = 0;
1309 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001310}
1311
Jeff Bolz5c801d12019-10-09 10:38:45 -05001312bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1313 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001314 bool skip = false;
1315
1316 for (uint32_t submit = 0; submit < submitCount; submit++) {
1317 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1318 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1319 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001320 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1321 skip |=
1322 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1323 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1324 submit, submit);
1325 }
1326 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1327 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1328 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1329 submit, submit);
1330 }
Camden5b184be2019-08-13 07:50:19 -06001331 }
1332
1333 return skip;
1334}
1335
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001336bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1337 VkFence fence) const {
1338 bool skip = false;
1339
1340 for (uint32_t submit = 0; submit < submitCount; submit++) {
1341 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1342 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1343 }
1344 }
1345
1346 return skip;
1347}
1348
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001349bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1350 VkFence fence) const {
1351 bool skip = false;
1352
1353 for (uint32_t submit = 0; submit < submitCount; submit++) {
1354 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1355 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1356 }
1357 }
1358
1359 return skip;
1360}
1361
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001362bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1363 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1364 bool skip = false;
1365
1366 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1367 skip |= LogPerformanceWarning(
1368 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1369 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1370 "pool instead.");
1371 }
1372
1373 return skip;
1374}
1375
1376bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1377 const VkCommandBufferBeginInfo* pBeginInfo) const {
1378 bool skip = false;
1379
1380 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1381 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1382 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1383 }
1384
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001385 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1386 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001387 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1388 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1389 VendorSpecificTag(kBPVendorArm));
1390 }
1391
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001392 return skip;
1393}
1394
Jeff Bolz5c801d12019-10-09 10:38:45 -05001395bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001396 bool skip = false;
1397
1398 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1399
1400 return skip;
1401}
1402
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001403bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1404 const VkDependencyInfoKHR* pDependencyInfo) const {
1405 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1406}
1407
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001408bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1409 const VkDependencyInfo* pDependencyInfo) const {
1410 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1411}
1412
Jeff Bolz5c801d12019-10-09 10:38:45 -05001413bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1414 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001415 bool skip = false;
1416
1417 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1418
1419 return skip;
1420}
1421
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001422bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1423 VkPipelineStageFlags2KHR stageMask) const {
1424 bool skip = false;
1425
1426 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1427
1428 return skip;
1429}
1430
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001431bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1432 VkPipelineStageFlags2 stageMask) const {
1433 bool skip = false;
1434
1435 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1436
1437 return skip;
1438}
1439
Camden5b184be2019-08-13 07:50:19 -06001440bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1441 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1442 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1443 uint32_t bufferMemoryBarrierCount,
1444 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1445 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001446 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001447 bool skip = false;
1448
1449 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1450 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1451
1452 return skip;
1453}
1454
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001455bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1456 const VkDependencyInfoKHR* pDependencyInfos) const {
1457 bool skip = false;
1458 for (uint32_t i = 0; i < eventCount; i++) {
1459 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1460 }
1461
1462 return skip;
1463}
1464
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001465bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1466 const VkDependencyInfo* pDependencyInfos) const {
1467 bool skip = false;
1468 for (uint32_t i = 0; i < eventCount; i++) {
1469 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1470 }
1471
1472 return skip;
1473}
1474
Camden5b184be2019-08-13 07:50:19 -06001475bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1476 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1477 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1478 uint32_t bufferMemoryBarrierCount,
1479 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1480 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001481 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001482 bool skip = false;
1483
1484 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1485 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1486
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001487 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1488 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1489 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1490 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1491 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1492 "may be discarded, but the newLayout is %s, which is read only.",
1493 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1494 }
1495 }
1496
Nadav Gevaf0808442021-05-21 13:51:25 -04001497 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001498 auto num = num_barriers_objects_.load();
1499 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001500 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001501 "%s Performance warning: In this frame, %" PRIu32
1502 " barriers were already submitted. Barriers have a high cost and can "
1503 "stall the GPU. "
1504 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1505 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001506 }
1507
1508 std::array<VkImageLayout, 3> read_layouts = {
1509 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1510 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1511 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1512 };
1513
1514 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1515 // read to read barriers
1516 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1517 bool old_is_read_layout = found != read_layouts.end();
1518 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1519 bool new_is_read_layout = found != read_layouts.end();
1520 if (old_is_read_layout && new_is_read_layout) {
1521 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1522 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1523 "time you use it.",
1524 VendorSpecificTag(kBPVendorAMD));
1525 }
1526
1527 // general with no storage
1528 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1529 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1530 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1531 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1532 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1533 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1534 VendorSpecificTag(kBPVendorAMD));
1535 }
1536 }
1537 }
1538 }
1539
Camden5b184be2019-08-13 07:50:19 -06001540 return skip;
1541}
1542
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001543bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1544 const VkDependencyInfoKHR* pDependencyInfo) const {
1545 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1546}
1547
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001548bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1549 const VkDependencyInfo* pDependencyInfo) const {
1550 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1551}
1552
Camden5b184be2019-08-13 07:50:19 -06001553bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001554 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001555 bool skip = false;
1556
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001557 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1558
1559 return skip;
1560}
1561
1562bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1563 VkQueryPool queryPool, uint32_t query) const {
1564 bool skip = false;
1565
1566 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001567
1568 return skip;
1569}
1570
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001571bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1572 VkQueryPool queryPool, uint32_t query) const {
1573 bool skip = false;
1574
1575 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1576
1577 return skip;
1578}
1579
Sam Walls0961ec02020-03-31 16:39:15 +01001580void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1581 VkPipeline pipeline) {
1582 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1583
Nadav Gevaf0808442021-05-21 13:51:25 -04001584 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001585 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001586
Sam Walls0961ec02020-03-31 16:39:15 +01001587 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001588 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001589 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001590 if (pipeline_state) {
1591 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001592 assert(cb_node);
1593 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001594
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001595 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001596 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001597
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001598 const auto* blend_state = pipeline_state->ColorBlendState();
1599 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001600
1601 if (blend_state) {
1602 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001603 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001604 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1605 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001606 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001607 }
1608 }
1609 }
1610
1611 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001612 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001613
1614 if (stencil_state && stencil_state->depthTestEnable) {
1615 switch (stencil_state->depthCompareOp) {
1616 case VK_COMPARE_OP_EQUAL:
1617 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1618 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001619 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001620 break;
1621 default:
1622 break;
1623 }
1624 }
Sam Walls0961ec02020-03-31 16:39:15 +01001625 }
1626 }
1627}
1628
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001629static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1630 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1631 const auto& subpass_info = createInfo.pSubpasses[subpass];
1632 if (subpass_info.pResolveAttachments) {
1633 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1634 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1635 }
1636 }
1637 }
1638
1639 return false;
1640}
1641
Attilio Provenzano02859b22020-02-27 14:17:28 +00001642static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1643 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001644 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001645
1646 // If an attachment is ever used as a color attachment,
1647 // resolve attachment or depth stencil attachment,
1648 // it needs to exist on tile at some point.
1649
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001650 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1651 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001652 }
1653
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001654 if (subpass_info.pResolveAttachments) {
1655 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1656 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1657 }
1658 }
1659
1660 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001661 }
1662
1663 return false;
1664}
1665
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001666static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1667 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1668 return false;
1669 }
1670
1671 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001672 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001673
1674 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1675 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1676 return true;
1677 }
1678 }
1679 }
1680
1681 return false;
1682}
1683
Attilio Provenzano02859b22020-02-27 14:17:28 +00001684bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1685 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1686 bool skip = false;
1687
1688 if (!pRenderPassBegin) {
1689 return skip;
1690 }
1691
Gareth Webbdc6549a2021-06-16 03:52:24 +01001692 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1693 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1694 "This render pass has a zero-size render area. It cannot write to any attachments, "
1695 "and can only be used for side effects such as layout transitions.");
1696 }
1697
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001698 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001699 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001700 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001701 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001702 if (rpabi) {
1703 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1704 }
1705 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001706 // Check if any attachments have LOAD operation on them
1707 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001708 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001709
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001710 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001711 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001712 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001713 }
1714
1715 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001716 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001717 }
1718
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001719 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001720
1721 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001722 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1723 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001724 }
1725
1726 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00001727 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
1728 skip |=
1729 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00001730 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00001731 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001732 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00001733 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
1734 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
1735 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1736 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1737 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001738 }
1739 }
paul-lunarg7089e272022-06-20 22:19:37 +02001740
1741 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
1742
1743 bool clearing = false;
1744
1745 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1746 const auto& attachment = rp_state->createInfo.pAttachments[att];
1747
1748 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1749 clearing = true;
1750 break;
1751 }
1752 }
1753
1754 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
1755 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
1756 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
1757 skip |= LogWarning(
1758 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
1759 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
1760 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02001761 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02001762 }
paul-lunarga0a149c2022-06-23 16:18:51 +02001763
1764 // Check if there are more clearValues than attachments
1765 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
1766 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
1767 // This could signal a bug and there seems to be no reason for this to happen on purpose.
1768 skip |= LogWarning(
1769 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
1770 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
1771 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
1772 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
1773 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001774 }
1775
1776 return skip;
1777}
1778
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001779void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1780 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001781 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001782 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1783 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001784 }
1785}
1786
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001787void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1788 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001789 // If we're viewing a 3D slice, ignore base array layer.
1790 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001791 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 +02001792
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001793 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001794 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001795 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1796 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001797
1798 for (uint32_t layer = 0; layer < array_layers; layer++) {
1799 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001800 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1801 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001802 }
1803 }
1804}
1805
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001806void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1807 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1808 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001809 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001810
1811 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001812 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001813 }
1814}
1815
paul-lunarg5eb52062022-06-27 18:57:15 +02001816void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1817 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
1818 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
1819 const CMD_BUFFER_STATE&) -> bool {
1820 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
1821 return false;
1822 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001823}
1824
LawG44d414ba2022-02-23 15:35:41 +00001825void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001826 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001827 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001828 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001829 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 -07001830 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001831 LogPerformanceWarning(
1832 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00001833 "%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 +02001834 "image was used, it was written to with STORE_OP_STORE. "
1835 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1836 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00001837 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001838 } 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 +02001839 LogPerformanceWarning(
1840 device, kVUID_BestPractices_RenderPass_RedundantClear,
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 vkCmdClear*Image(). "
1843 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00001844 "tile-based architectures.",
1845 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001846 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001847 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1848 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001849 const char *last_cmd = nullptr;
1850 const char *vuid = nullptr;
1851 const char *suggestion = nullptr;
1852
1853 switch (last_usage) {
1854 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1855 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1856 last_cmd = "vkCmdBlitImage";
1857 suggestion =
1858 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1859 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1860 "which avoids the memory roundtrip.";
1861 break;
1862 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1863 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1864 last_cmd = "vkCmdClear*Image";
1865 suggestion =
1866 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1867 "tile-based architectures. "
1868 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1869 break;
1870 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1871 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1872 last_cmd = "vkCmdCopy*Image";
1873 suggestion =
1874 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1875 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1876 "which avoids the memory roundtrip.";
1877 break;
1878 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1879 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1880 last_cmd = "vkCmdResolveImage";
1881 suggestion =
1882 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1883 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1884 "which avoids the memory roundtrip.";
1885 break;
1886 default:
1887 break;
1888 }
1889
1890 LogPerformanceWarning(
1891 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00001892 "%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 +01001893 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00001894 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
1895 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001896 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001897}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001898
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001899void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1900 uint32_t array_layer, uint32_t mip_level) {
1901 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02001902
1903 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
1904 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
1905 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
1906 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
1907 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
1908 "result in undefined behaviour.");
1909 }
1910
LawG44d414ba2022-02-23 15:35:41 +00001911 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
1912 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001913 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001914}
1915
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001916void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1917 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1918 cb.queue_submit_functions_after_render_pass.end());
1919 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001920}
1921
1922void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1923 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001924 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1925 if (cb_node) {
1926 AddDeferredQueueOperations(*cb_node);
1927 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001928}
1929
1930void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1931 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
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::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1939 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(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
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001946void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1947 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001948 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001949 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001950 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1951}
1952
1953void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1954 const VkRenderPassBeginInfo* pRenderPassBegin,
1955 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1956 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1957 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1958}
1959
1960void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1961 const VkRenderPassBeginInfo* pRenderPassBegin,
1962 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1963 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1964 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1965}
1966
1967void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001968
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001969 if (!pRenderPassBegin) {
1970 return;
1971 }
1972
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001973 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001974
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001975 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001976 if (rp_state) {
1977 // Check load ops
1978 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001979 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001980
1981 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1982 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1983 continue;
1984 }
1985
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001986 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001987
1988 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1989 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001990 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001991 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1992 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001993 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001994 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001995 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001996 }
1997
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001998 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06001999 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002000
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002001 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002002 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2003 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002004 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002005 }
2006 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002007 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002008 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002009
Jeremy Gebben9f537102021-10-05 16:37:12 -06002010 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002011 }
2012
2013 // Check store ops
2014 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002015 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002016
2017 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2018 continue;
2019 }
2020
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002021 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002022
2023 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2024 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002025 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002026 }
2027
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002028 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002029
Jeremy Gebben9f537102021-10-05 16:37:12 -06002030 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002031 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002032 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2033 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002034 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002035 }
2036 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002037 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002038 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002039
Jeremy Gebben9f537102021-10-05 16:37:12 -06002040 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002041 }
2042 }
2043}
2044
Attilio Provenzano02859b22020-02-27 14:17:28 +00002045bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2046 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002047 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2048 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002049 return skip;
2050}
2051
2052bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2053 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002054 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002055 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2056 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002057 return skip;
2058}
2059
2060bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002061 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002062 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2063 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002064 return skip;
2065}
2066
Sam Walls0961ec02020-03-31 16:39:15 +01002067void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2068 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002069 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002070 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002071 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2072 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002073 assert(cb);
2074 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002075 render_pass_state.touchesAttachments.clear();
2076 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002077 render_pass_state.numDrawCallsDepthOnly = 0;
2078 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2079 render_pass_state.colorAttachment = false;
2080 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002081 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002082 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002083
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002084 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002085
2086 // track depth / color attachment usage within the renderpass
2087 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2088 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002089 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002090
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002091 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002092 }
2093}
2094
2095void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2096 VkSubpassContents contents) {
2097 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2098 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2099}
2100
2101void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2102 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2103 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2104 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2105}
2106
2107void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2108 const VkRenderPassBeginInfo* pRenderPassBegin,
2109 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2110 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2111 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2112}
2113
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002114// Generic function to handle validation for all CmdDraw* type functions
2115bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2116 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002117 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002118 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002119 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2120 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002121 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002122
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002123 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002124 if (pipeline_state && pipeline_state->vertex_input_state &&
2125 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002126 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002127 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002128 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002129 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2130 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002131 }
2132 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002133
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002134 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002135 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002136 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002137 if (rp_state) {
2138 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2139 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002140 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002141 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002142 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2143 const auto* raster_state = pipe->RasterizationState();
2144 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2145 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002146 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2147 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2148 }
2149 }
2150 }
2151 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002152 }
2153 return skip;
2154}
2155
Sam Walls0961ec02020-03-31 16:39:15 +01002156void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002157 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002158 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002159 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002160 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002161 }
2162
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002163 if (cb_node->render_pass_state.drawTouchAttachments) {
2164 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2165 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002166 }
2167 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002168 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002169 }
2170}
2171
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002172void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2173 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002174 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2175 // depth prepass warnings First find the lowest enabled draw count
2176 uint32_t lowestEnabledMinDrawCount = 0;
2177 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2178 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2179 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2180
2181 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002182 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2183 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002184 }
2185}
2186
Camden5b184be2019-08-13 07:50:19 -06002187bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002188 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002189 bool skip = false;
2190
2191 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002192 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2193 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002194 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002195 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002196
2197 return skip;
2198}
2199
Sam Walls0961ec02020-03-31 16:39:15 +01002200void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2201 uint32_t firstVertex, uint32_t firstInstance) {
2202 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2203 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2204}
2205
Camden5b184be2019-08-13 07:50:19 -06002206bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002207 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002208 bool skip = false;
2209
2210 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002211 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2212 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002213 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002214 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2215
Attilio Provenzano02859b22020-02-27 14:17:28 +00002216 // Check if we reached the limit for small indexed draw calls.
2217 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002218 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002219 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002220 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00002221 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002222 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00002223 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002224 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2225 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00002226 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
2227 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002228 }
2229
Sam Walls8e77e4f2020-03-16 20:47:40 +00002230 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002231 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002232 }
2233
2234 return skip;
2235}
2236
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002237bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002238 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2239 bool skip = false;
2240
2241 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002242
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002243 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2244 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002245
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002246 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002247 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002248 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2249 const void* ib_mem = ib_mem_state.p_driver_data;
2250 bool primitive_restart_enable = false;
2251
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002252 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002253 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002254 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002255
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002256 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2257 if (ia_state) {
2258 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002259 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002260
2261 // 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 -06002262 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002263 uint32_t scan_stride;
2264 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2265 scan_stride = sizeof(uint8_t);
2266 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2267 scan_stride = sizeof(uint16_t);
2268 } else {
2269 scan_stride = sizeof(uint32_t);
2270 }
2271
2272 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2273 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2274
2275 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2276 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2277 // irrespective of whether or not they're part of the draw call.
2278
2279 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2280 uint32_t min_index = ~0u;
2281 // start with maximum as 0 and adjust to indices in the buffer
2282 uint32_t max_index = 0u;
2283
2284 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2285 // for the given index buffer
2286 uint32_t vertex_shade_count = 0;
2287
2288 PostTransformLRUCacheModel post_transform_cache;
2289
2290 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2291 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2292 // target architecture.
2293 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2294 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2295 post_transform_cache.resize(32);
2296
2297 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2298 uint32_t scan_index;
2299 uint32_t primitive_restart_value;
2300 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2301 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2302 primitive_restart_value = 0xFF;
2303 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2304 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2305 primitive_restart_value = 0xFFFF;
2306 } else {
2307 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2308 primitive_restart_value = 0xFFFFFFFF;
2309 }
2310
2311 max_index = std::max(max_index, scan_index);
2312 min_index = std::min(min_index, scan_index);
2313
2314 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2315 bool in_cache = post_transform_cache.query_cache(scan_index);
2316 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2317 if (!in_cache) vertex_shade_count++;
2318 }
2319 }
2320
2321 // 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 +01002322 // 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
2323 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002324
2325 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002326 skip |=
2327 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2328 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2329 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2330 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2331 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2332 VendorSpecificTag(kBPVendorArm),
2333 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002334 return skip;
2335 }
2336
2337 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2338 // 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 +01002339 const size_t refs_per_bucket = 64;
2340 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2341
2342 const uint32_t n_indices = max_index - min_index + 1;
2343 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2344 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2345
2346 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2347 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002348
2349 // To avoid using too much memory, we run over the indices again.
2350 // Knowing the size from the last scan allows us to record index usage with bitsets
2351 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2352 uint32_t scan_index;
2353 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2354 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2355 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2356 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2357 } else {
2358 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2359 }
2360 // keep track of the set of all indices used to reference vertices in the draw call
2361 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002362 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2363 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002364 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2365 }
2366
2367 uint32_t vertex_reference_count = 0;
2368 for (const auto& bitset : vertex_reference_buckets) {
2369 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2370 }
2371
2372 // 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 -07002373 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002374 // 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 -07002375 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002376
2377 if (utilization < 0.5f) {
2378 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2379 "%s The indices which were specified for the draw call only utilise approximately "
2380 "%.02f%% of the bound vertex buffer.",
2381 VendorSpecificTag(kBPVendorArm), utilization);
2382 }
2383
2384 if (cache_hit_rate <= 0.5f) {
2385 skip |=
2386 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2387 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2388 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2389 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2390 "recently shaded vertices.",
2391 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2392 }
2393 }
2394
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002395 return skip;
2396}
2397
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002398bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2399 const VkCommandBuffer* pCommandBuffers) const {
2400 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002401 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002402 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002403 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002404 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002405 continue;
2406 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002407 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002408 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002409 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2410 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002411 }
2412 }
2413 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002414
2415 if (VendorCheckEnabled(kBPVendorAMD)) {
2416 if (commandBufferCount > 0) {
2417 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2418 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2419 VendorSpecificTag(kBPVendorAMD));
2420 }
2421 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002422 return skip;
2423}
2424
2425void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2426 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002427 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2428
2429 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2430 if (!primary) {
2431 return;
2432 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002433
2434 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002435 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2436 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002437 continue;
2438 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002439
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002440 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2441 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2442 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2443 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002444 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002445 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002446 }
2447 }
2448
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002449 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2450 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002451 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002452
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002453 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2454 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002455 }
2456
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002457}
2458
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002459void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2460 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002461 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002462 auto itr =
2463 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2464 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002465
2466 if (itr != state.touchesAttachments.end()) {
2467 itr->aspects |= aspects;
2468 } else {
2469 state.touchesAttachments.push_back({ fb_attachment, aspects });
2470 }
2471}
2472
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002473void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002474 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2475 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002476 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002477 // If we observe a full clear before any other access to a frame buffer attachment,
2478 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002479 auto itr =
2480 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2481 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002482
2483 uint32_t new_aspects = aspects;
2484 if (itr != state.touchesAttachments.end()) {
2485 new_aspects = aspects & ~itr->aspects;
2486 itr->aspects |= aspects;
2487 } else {
2488 state.touchesAttachments.push_back({ fb_attachment, aspects });
2489 }
2490
2491 if (new_aspects == 0) {
2492 return;
2493 }
2494
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002495 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002496 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2497 // CmdExecuteCommands.
2498 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2499 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2500 }
2501}
2502
2503void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2504 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2505 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002506 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2507
2508 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2509 auto* rp_state = cmd_state->activeRenderPass.get();
2510 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002511 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2512
2513 if (rectCount == 0 || !rp_state) {
2514 return;
2515 }
2516
2517 if (!is_secondary && !fb_state) {
2518 return;
2519 }
2520
2521 // 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 -07002522 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002523
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06002524 if (!rp_state->UsesDynamicRendering()) {
ziga-lunarg885c6542022-03-07 01:08:25 +01002525 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2526 for (uint32_t i = 0; i < attachmentCount; i++) {
2527 auto& attachment = pClearAttachments[i];
2528 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2529 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002530
ziga-lunarg885c6542022-03-07 01:08:25 +01002531 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2532 if (subpass.pDepthStencilAttachment) {
2533 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2534 }
2535 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2536 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002537 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002538
ziga-lunarg885c6542022-03-07 01:08:25 +01002539 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2540 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002541 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002542 aspects, rectCount, pRects);
2543 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002544 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002545 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002546 }
2547 }
2548 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002549}
2550
Attilio Provenzano02859b22020-02-27 14:17:28 +00002551void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2552 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2553 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2554 firstInstance);
2555
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002556 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002557 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2558 cmd_state->small_indexed_draw_call_count++;
2559 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002560
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002561 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002562}
2563
Sam Walls0961ec02020-03-31 16:39:15 +01002564void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2565 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2566 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2567 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2568}
2569
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002570bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2571 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2572 uint32_t maxDrawCount, uint32_t stride) const {
2573 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2574
2575 return skip;
2576}
2577
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002578bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2579 VkDeviceSize offset, VkBuffer countBuffer,
2580 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2581 uint32_t stride) const {
2582 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002583
2584 return skip;
2585}
2586
2587bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002588 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002589 bool skip = false;
2590
2591 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002592 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2593 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002594 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002595 }
2596
2597 return skip;
2598}
2599
Sam Walls0961ec02020-03-31 16:39:15 +01002600void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2601 uint32_t count, uint32_t stride) {
2602 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2603 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2604}
2605
Camden5b184be2019-08-13 07:50:19 -06002606bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002607 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002608 bool skip = false;
2609
2610 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002611 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2612 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002613 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002614 }
2615
2616 return skip;
2617}
2618
Sam Walls0961ec02020-03-31 16:39:15 +01002619void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2620 uint32_t count, uint32_t stride) {
2621 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2622 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2623}
2624
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002625void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2626 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002627 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002628 // For bindless scenarios, we should not attempt to track descriptor set state.
2629 // It is highly uncertain which resources are actually bound.
2630 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002631 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2632 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002633 continue;
2634 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002635
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002636 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002637 VkImageView image_view{VK_NULL_HANDLE};
2638
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002639 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02002640 if (!descriptor) {
2641 continue;
2642 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002643 switch (descriptor->GetClass()) {
2644 case cvdescriptorset::DescriptorClass::Image: {
2645 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2646 image_view = image_descriptor->GetImageView();
2647 }
2648 break;
2649 }
2650 case cvdescriptorset::DescriptorClass::ImageSampler: {
2651 if (const auto image_sampler_descriptor =
2652 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2653 image_view = image_sampler_descriptor->GetImageView();
2654 }
2655 break;
2656 }
2657 default:
2658 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002659 }
2660
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002661 if (image_view) {
2662 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2663 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2664 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002665 }
2666 }
2667 }
2668 }
2669}
2670
2671void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2672 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002673 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2674 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002675}
2676
2677void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2678 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002679 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2680 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002681}
2682
2683void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2684 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002685 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2686 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002687}
2688
Camden5b184be2019-08-13 07:50:19 -06002689bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002690 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002691 bool skip = false;
2692
2693 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002694 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2695 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2696 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2697 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002698 }
2699
2700 return skip;
2701}
Camden83a9c372019-08-14 11:41:38 -06002702
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002703bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2704 bool skip = false;
2705 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2706 skip |= ValidateCmdEndRenderPass(commandBuffer);
2707 return skip;
2708}
2709
2710bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2711 bool skip = false;
2712 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2713 skip |= ValidateCmdEndRenderPass(commandBuffer);
2714 return skip;
2715}
2716
Sam Walls0961ec02020-03-31 16:39:15 +01002717bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2718 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002719 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002720 skip |= ValidateCmdEndRenderPass(commandBuffer);
2721 return skip;
2722}
2723
2724bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2725 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002726 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002727
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002728 if (cmd == nullptr) return skip;
2729 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002730
LawG4b21485c2022-02-28 13:46:48 +00002731 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
2732 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2733 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2734 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
2735 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
2736
2737 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01002738 bool uses_depth =
2739 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01002740 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00002741
Sam Walls0961ec02020-03-31 16:39:15 +01002742 if (uses_depth) {
2743 skip |= LogPerformanceWarning(
2744 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00002745 "%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 +00002746 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
2747 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
2748 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
2749 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01002750 }
2751
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002752 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2753
LawG40da9c3d2022-03-01 09:51:01 +00002754 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002755 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2756 // it is redundant to have it be part of the render pass.
2757 // Only consider it redundant if it will actually consume bandwidth, i.e.
2758 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2759 // as is using pure input attachments.
2760 // CLEAR -> STORE might be considered a "useful" thing to do, but
2761 // the optimal thing to do is to defer the clear until you're actually
2762 // going to render to the image.
2763
2764 uint32_t num_attachments = rp->createInfo.attachmentCount;
2765 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002766 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2767 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002768 continue;
2769 }
2770
2771 auto& attachment = rp->createInfo.pAttachments[i];
2772
2773 VkImageAspectFlags bandwidth_aspects = 0;
2774
2775 if (!FormatIsStencilOnly(attachment.format) &&
2776 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2777 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2778 if (FormatHasDepth(attachment.format)) {
2779 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2780 } else {
2781 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2782 }
2783 }
2784
2785 if (FormatHasStencil(attachment.format) &&
2786 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2787 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2788 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2789 }
2790
2791 if (!bandwidth_aspects) {
2792 continue;
2793 }
2794
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002795 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002796 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002797 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002798 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002799 untouched_aspects &= ~itr->aspects;
2800 }
2801
2802 if (untouched_aspects) {
2803 skip |= LogPerformanceWarning(
2804 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00002805 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002806 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00002807 "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 +00002808 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00002809 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002810 }
2811 }
2812 }
2813
Sam Walls0961ec02020-03-31 16:39:15 +01002814 return skip;
2815}
2816
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002817void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002818 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2819 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002820}
2821
2822void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002823 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2824 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002825}
2826
Camden Stocker9c051442019-11-06 14:28:43 -08002827bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2828 const char* api_name) const {
2829 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002830 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002831
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002832 if (bp_pd_state) {
2833 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2834 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2835 "Potential problem with calling %s() without first retrieving properties from "
2836 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2837 api_name);
2838 }
Camden Stocker9c051442019-11-06 14:28:43 -08002839 }
2840
2841 return skip;
2842}
2843
Camden83a9c372019-08-14 11:41:38 -06002844bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002845 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002846 bool skip = false;
2847
Camden Stocker9c051442019-11-06 14:28:43 -08002848 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002849
Camden Stocker9c051442019-11-06 14:28:43 -08002850 return skip;
2851}
2852
2853bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2854 uint32_t planeIndex,
2855 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2856 bool skip = false;
2857
2858 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2859
2860 return skip;
2861}
2862
2863bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2864 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2865 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2866 bool skip = false;
2867
2868 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002869
2870 return skip;
2871}
Camden05de2d42019-08-19 10:23:56 -06002872
2873bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002874 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002875 bool skip = false;
2876
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002877 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002878
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002879 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002880 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002881 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002882 skip |=
2883 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2884 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2885 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002886 }
Camden05de2d42019-08-19 10:23:56 -06002887
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002888 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2889 skip |= LogWarning(
2890 device, kVUID_BestPractices_Swapchain_InvalidCount,
2891 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002892 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002893 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2894 }
2895 }
2896
Camden05de2d42019-08-19 10:23:56 -06002897 return skip;
2898}
2899
2900// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002901bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002902 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002903 const CALL_STATE call_state,
2904 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002905 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002906 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2907 if (UNCALLED == call_state) {
2908 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002909 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002910 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2911 "recommended "
2912 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2913 caller_name, caller_name);
2914 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002915 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2916 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002917 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2918 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2919 ". It is recommended to instead receive all the properties by calling %s with "
2920 "pQueueFamilyPropertyCount that was "
2921 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002922 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002923 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002924 }
2925
2926 return skip;
2927}
2928
Jeff Bolz5c801d12019-10-09 10:38:45 -05002929bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2930 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002931 bool skip = false;
2932
2933 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002934 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002935 if (!as_state->memory_requirements_checked) {
2936 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2937 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2938 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002939 skip |= LogWarning(
2940 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002941 "vkBindAccelerationStructureMemoryNV(): "
2942 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2943 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2944 }
2945 }
2946
2947 return skip;
2948}
2949
Camden05de2d42019-08-19 10:23:56 -06002950bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2951 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002952 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002953 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002954 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002955 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002956 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2957 "vkGetPhysicalDeviceQueueFamilyProperties()");
2958 }
2959 return false;
Camden05de2d42019-08-19 10:23:56 -06002960}
2961
Mike Schuchardt2df08912020-12-15 16:28:09 -08002962bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2963 uint32_t* pQueueFamilyPropertyCount,
2964 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002965 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002966 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002967 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002968 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2969 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2970 }
2971 return false;
Camden05de2d42019-08-19 10:23:56 -06002972}
2973
Jeff Bolz5c801d12019-10-09 10:38:45 -05002974bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002975 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002976 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002977 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002978 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002979 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2980 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2981 }
2982 return false;
Camden05de2d42019-08-19 10:23:56 -06002983}
2984
2985bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2986 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002987 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002988 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002989 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002990 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002991 bool skip = false;
2992 if (call_state == UNCALLED) {
2993 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2994 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002995 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2996 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2997 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002998 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06002999 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003000 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
3001 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
3002 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
3003 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003004 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06003005 }
3006 }
3007 return skip;
3008}
Camden Stocker23cc47d2019-09-03 14:53:57 -06003009
3010bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003011 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003012 bool skip = false;
3013
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003014 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3015 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06003016 // 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 -07003017 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003018 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
3019 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07003020 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06003021 // 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 -07003022 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
3023 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003024 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003025 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003026 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003027 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003028 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003029 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3030 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3031 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003032 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003033 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3034 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003035 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003036 }
3037 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003038 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003039 // 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 "vkGetImageMemoryRequirements() 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 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003046 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3047 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003048 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003049 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003050 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003051 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003052 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003053 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3054 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3055 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003056 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003057 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3058 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003059 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003060 }
3061 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003062 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003063 // 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 "vkGetImageMemoryRequirements() 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 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3070 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003071 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003072 }
3073 }
3074 }
3075 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003076 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
3077 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003078 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003079 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003080 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3081 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003082 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003083 }
3084 }
3085 }
3086
3087 return skip;
3088}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003089
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003090void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3091 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003092 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003093 return;
3094 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003095
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003096 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3097 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3098 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3099 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003100 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003101 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003102 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003103 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003104 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3105 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3106 image_state->sparse_metadata_bound = true;
3107 }
3108 }
3109 }
3110 }
3111}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003112
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003113bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003114 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003115 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003116 // We don't know the accurate render area in a secondary,
3117 // so assume we clear the entire frame buffer.
3118 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3119 return true;
3120 }
3121
3122 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3123 for (uint32_t i = 0; i < rectCount; i++) {
3124 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003125 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003126 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3127 return true;
3128 }
3129 }
3130
3131 return false;
3132}
3133
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003134bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
3135 VkImageAspectFlags aspects, bool secondary) const {
3136 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003137 bool skip = false;
3138
3139 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3140 return skip;
3141 }
3142
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003143 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003144
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003145 auto attachment_itr =
3146 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3147 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003148
3149 // Only report aspects which haven't been touched yet.
3150 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003151 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003152 new_aspects &= ~attachment_itr->aspects;
3153 }
3154
3155 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09003156 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003157 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003158 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003159 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3160 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003161 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003162 }
3163
3164 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3165 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3166 skip |= LogPerformanceWarning(
3167 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3168 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3169 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3170 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003171 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003172 }
3173
3174 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3175 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003176 skip |=
3177 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3178 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3179 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3180 "it is more efficient.",
3181 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003182 }
3183
3184 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3185 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003186 skip |=
3187 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3188 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3189 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3190 "it is more efficient.",
3191 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003192 }
3193
3194 return skip;
3195}
3196
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003197bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003198 const VkClearAttachment* pAttachments, uint32_t rectCount,
3199 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003200 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003201 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003202 if (!cb_node) return skip;
3203
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003204 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3205 // Defer checks to ExecuteCommands.
3206 return skip;
3207 }
3208
3209 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003210 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003211 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003212 }
3213
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003214 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3215 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003216 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003217 if (rp) {
3218 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3219
3220 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003221 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003222
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003223 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3224 uint32_t color_attachment = attachment.colorAttachment;
3225 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003226 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003227 }
3228
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003229 if (subpass.pDepthStencilAttachment &&
3230 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003231 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003232 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003233 }
3234 }
3235 }
3236
Nadav Gevaf0808442021-05-21 13:51:25 -04003237 if (VendorCheckEnabled(kBPVendorAMD)) {
3238 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3239 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3240 bool black_check = false;
3241 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3242 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3243 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3244 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3245 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3246
3247 bool white_check = false;
3248 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3249 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3250 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3251 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3252 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3253
3254 if (black_check && white_check) {
3255 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3256 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3257 "Consider changing to one of the following:"
3258 "RGBA(0, 0, 0, 0) "
3259 "RGBA(0, 0, 0, 1) "
3260 "RGBA(1, 1, 1, 0) "
3261 "RGBA(1, 1, 1, 1)",
3262 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3263 }
3264 } else {
3265 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3266 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3267 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3268 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3269 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3270 "attachment %" PRId32 " is not a fast clear value."
3271 "Consider changing to one of the following:"
3272 "D=0.0f, S=0"
3273 "D=1.0f, S=0",
3274 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3275 }
3276 }
3277 }
3278 }
3279
Camden Stockerf55721f2019-09-09 11:04:49 -06003280 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003281}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003282
3283bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3284 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3285 const VkImageResolve* pRegions) const {
3286 bool skip = false;
3287
3288 skip |= VendorCheckEnabled(kBPVendorArm) &&
3289 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3290 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3291 "This is a very slow and extremely bandwidth intensive path. "
3292 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3293 VendorSpecificTag(kBPVendorArm));
3294
3295 return skip;
3296}
3297
Jeff Leger178b1e52020-10-05 12:22:23 -04003298bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3299 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3300 bool skip = false;
3301
3302 skip |= VendorCheckEnabled(kBPVendorArm) &&
3303 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3304 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3305 "This is a very slow and extremely bandwidth intensive path. "
3306 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3307 VendorSpecificTag(kBPVendorArm));
3308
3309 return skip;
3310}
3311
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003312bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3313 const VkResolveImageInfo2* pResolveImageInfo) const {
3314 bool skip = false;
3315
3316 skip |= VendorCheckEnabled(kBPVendorArm) &&
3317 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3318 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3319 "This is a very slow and extremely bandwidth intensive path. "
3320 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3321 VendorSpecificTag(kBPVendorArm));
3322
3323 return skip;
3324}
3325
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003326void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3327 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3328 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003329 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003330 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003331 auto src = Get<bp_state::Image>(srcImage);
3332 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003333
3334 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003335 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3336 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003337 }
3338}
3339
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003340void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3341 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003342 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003343 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003344 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3345 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003346 uint32_t regionCount = pResolveImageInfo->regionCount;
3347
3348 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003349 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3350 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003351 }
3352}
3353
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003354void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3355 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003356 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003357 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003358 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3359 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003360 uint32_t regionCount = pResolveImageInfo->regionCount;
3361
3362 for (uint32_t i = 0; i < regionCount; i++) {
3363 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3364 pResolveImageInfo->pRegions[i].srcSubresource);
3365 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3366 pResolveImageInfo->pRegions[i].dstSubresource);
3367 }
3368}
3369
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003370void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3371 const VkClearColorValue* pColor, uint32_t rangeCount,
3372 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003373 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003374 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003375 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003376
3377 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003378 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003379 }
3380}
3381
3382void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3383 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3384 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003385 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003386 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003387 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003388
3389 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003390 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003391 }
3392}
3393
3394void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3395 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3396 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003397 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003398 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003399 auto src = Get<bp_state::Image>(srcImage);
3400 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003401
3402 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003403 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3404 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003405 }
3406}
3407
3408void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3409 VkImageLayout dstImageLayout, uint32_t regionCount,
3410 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003411 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003412 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003413 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003414
3415 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003416 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003417 }
3418}
3419
3420void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3421 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003422 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003423 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003424 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003425
3426 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003427 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003428 }
3429}
3430
3431void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3432 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3433 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003434 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003435 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003436 auto src = Get<bp_state::Image>(srcImage);
3437 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003438
3439 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003440 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3441 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003442 }
3443}
3444
Attilio Provenzano02859b22020-02-27 14:17:28 +00003445bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3446 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3447 bool skip = false;
3448
3449 if (VendorCheckEnabled(kBPVendorArm)) {
3450 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3451 skip |= LogPerformanceWarning(
3452 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3453 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3454 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3455 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003456 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003457 }
3458
3459 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3460 skip |= LogPerformanceWarning(
3461 device, kVUID_BestPractices_CreateSampler_LodClamping,
3462 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3463 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3464 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3465 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3466 }
3467
3468 if (pCreateInfo->mipLodBias != 0.0f) {
3469 skip |=
3470 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3471 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3472 "descriptors being created and may cause reduced performance.",
3473 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3474 }
3475
3476 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3477 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3478 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3479 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3480 skip |= LogPerformanceWarning(
3481 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3482 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3483 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3484 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3485 VendorSpecificTag(kBPVendorArm));
3486 }
3487
3488 if (pCreateInfo->unnormalizedCoordinates) {
3489 skip |= LogPerformanceWarning(
3490 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3491 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3492 "descriptors being created and may cause reduced performance.",
3493 VendorSpecificTag(kBPVendorArm));
3494 }
3495
3496 if (pCreateInfo->anisotropyEnable) {
3497 skip |= LogPerformanceWarning(
3498 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3499 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3500 "and may cause reduced performance.",
3501 VendorSpecificTag(kBPVendorArm));
3502 }
3503 }
3504
3505 return skip;
3506}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003507
Nadav Gevaf0808442021-05-21 13:51:25 -04003508void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3509 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3510 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3511 void* cgpl_state) {
3512 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3513 pPipelines);
3514 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003515 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003516}
3517
3518bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3519 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3520 const VkCopyDescriptorSet* pDescriptorCopies) const {
3521 bool skip = false;
3522 if (VendorCheckEnabled(kBPVendorAMD)) {
3523 if (descriptorCopyCount > 0) {
3524 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3525 "%s Performance warning: copying descriptor sets is not recommended",
3526 VendorSpecificTag(kBPVendorAMD));
3527 }
3528 }
3529
3530 return skip;
3531}
3532
3533bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3534 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3535 const VkAllocationCallbacks* pAllocator,
3536 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3537 bool skip = false;
3538 if (VendorCheckEnabled(kBPVendorAMD)) {
3539 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3540 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3541 "vkUpdateDescriptorSet instead",
3542 VendorSpecificTag(kBPVendorAMD));
3543 }
3544
3545 return skip;
3546}
3547
3548bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3549 const VkClearColorValue* pColor, uint32_t rangeCount,
3550 const VkImageSubresourceRange* pRanges) const {
3551 bool skip = false;
3552 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003553 skip |= LogPerformanceWarning(
3554 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003555 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3556 "vkCmdClearAttachments instead",
3557 VendorSpecificTag(kBPVendorAMD));
3558 }
3559
3560 return skip;
3561}
3562
3563bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3564 VkImageLayout imageLayout,
3565 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3566 const VkImageSubresourceRange* pRanges) const {
3567 bool skip = false;
3568 if (VendorCheckEnabled(kBPVendorAMD)) {
3569 skip |= LogPerformanceWarning(
3570 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3571 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3572 "vkCmdClearAttachments instead",
3573 VendorSpecificTag(kBPVendorAMD));
3574 }
3575
3576 return skip;
3577}
3578
3579bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3580 const VkAllocationCallbacks* pAllocator,
3581 VkPipelineLayout* pPipelineLayout) const {
3582 bool skip = false;
3583 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003584 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003585 // Descriptor sets cost 1 DWORD each.
3586 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3587 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3588 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3589 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3590 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003591 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003592 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003593 }
3594
3595 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3596 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3597 }
3598
3599 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3600 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3601 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3602 "Descriptor sets cost 1 DWORD each. "
3603 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3604 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3605 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3606 VendorSpecificTag(kBPVendorAMD));
3607 }
3608 }
3609
3610 return skip;
3611}
3612
3613bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3614 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3615 const VkImageCopy* pRegions) const {
3616 bool skip = false;
3617 std::stringstream src_image_hex;
3618 std::stringstream dst_image_hex;
3619 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3620 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3621
3622 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003623 auto src_state = Get<IMAGE_STATE>(srcImage);
3624 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003625
3626 if (src_state && dst_state) {
3627 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3628 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3629 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3630 skip |=
3631 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3632 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3633 "image (vkCmdCopyImageToBuffer) "
3634 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3635 "copies when converting between linear and optimal images",
3636 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3637 }
3638 }
3639 }
3640
3641 return skip;
3642}
3643
3644bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3645 VkPipeline pipeline) const {
3646 bool skip = false;
3647
3648 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003649 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003650 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3651 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3652 "for example, by sorting draw calls by pipeline.",
3653 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3654 }
3655 }
3656
3657 return skip;
3658}
3659
3660void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3661 VkFence fence, VkResult result) {
3662 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003663 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003664}
3665
3666bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3667 bool skip = false;
3668
3669 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003670 auto num = num_queue_submissions_.load();
3671 if (num > kNumberOfSubmissionWarningLimitAMD) {
3672 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3673 "%s Performance warning: command buffers submitted %" PRId32
3674 " times this frame. Submitting command buffers has a CPU "
3675 "and GPU overhead. Submit fewer times to incur less overhead.",
3676 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003677 }
3678 }
3679
3680 return skip;
3681}
3682
3683void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3684 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3685 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3686 uint32_t bufferMemoryBarrierCount,
3687 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3688 uint32_t imageMemoryBarrierCount,
3689 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003690 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003691}
3692
3693bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3694 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3695 bool skip = false;
3696 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003697 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003698 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3699 "%s Performance warning: High number of vkSemaphore objects created."
3700 "Minimize the amount of queue synchronization that is used. "
3701 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3702 VendorSpecificTag(kBPVendorAMD));
3703 }
3704 }
3705
3706 return skip;
3707}
3708
3709bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3710 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3711 bool skip = false;
3712 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003713 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003714 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3715 "%s Performance warning: High number of VkFence objects created."
3716 "Minimize the amount of CPU-GPU synchronization that is used. "
3717 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3718 VendorSpecificTag(kBPVendorAMD));
3719 }
3720 }
3721
3722 return skip;
3723}
3724
Sam Walls8e77e4f2020-03-16 20:47:40 +00003725void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3726
3727bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3728 // look for a cache hit
3729 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3730 if (hit != _entries.end()) {
3731 // mark the cache hit as being most recently used
3732 hit->age = iteration++;
3733 return true;
3734 }
3735
3736 // if there's no cache hit, we need to model the entry being inserted into the cache
3737 CacheEntry new_entry = {value, iteration};
3738 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3739 // if there is still space left in the cache, use the next available slot
3740 *(_entries.begin() + iteration) = new_entry;
3741 } else {
3742 // otherwise replace the least recently used cache entry
3743 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3744 *lru = new_entry;
3745 }
3746 iteration++;
3747 return false;
3748}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003749
3750bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3751 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003752 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003753 bool skip = false;
3754 if (swapchain_data && swapchain_data->images.size() == 0) {
3755 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3756 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3757 "vkGetSwapchainImagesKHR after swapchain creation.");
3758 }
3759 return skip;
3760}
3761
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003762void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3763 if (no_pointer) {
3764 if (UNCALLED == call_state) {
3765 call_state = QUERY_COUNT;
3766 }
3767 } else { // Save queue family properties
3768 call_state = QUERY_DETAILS;
3769 }
3770}
3771
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003772void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3773 uint32_t* pQueueFamilyPropertyCount,
3774 VkQueueFamilyProperties* pQueueFamilyProperties) {
3775 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3776 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003777 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003778 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003779 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3780 nullptr == pQueueFamilyProperties);
3781 }
3782}
3783
3784void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3785 uint32_t* pQueueFamilyPropertyCount,
3786 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3787 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3788 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003789 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003790 if (bp_pd_state) {
3791 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3792 nullptr == pQueueFamilyProperties);
3793 }
3794}
3795
3796void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3797 uint32_t* pQueueFamilyPropertyCount,
3798 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3799 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3800 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003801 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003802 if (bp_pd_state) {
3803 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3804 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003805 }
3806}
3807
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003808void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3809 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003810 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003811 if (bp_pd_state) {
3812 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3813 }
3814}
3815
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003816void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3817 VkPhysicalDeviceFeatures2* pFeatures) {
3818 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003819 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003820 if (bp_pd_state) {
3821 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3822 }
3823}
3824
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003825void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3826 VkPhysicalDeviceFeatures2* pFeatures) {
3827 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(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
3834void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3835 VkSurfaceKHR surface,
3836 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3837 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003838 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003839 if (bp_pd_state) {
3840 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3841 }
3842}
3843
3844void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3845 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3846 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003847 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003848 if (bp_pd_state) {
3849 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3850 }
3851}
3852
3853void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3854 VkSurfaceKHR surface,
3855 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3856 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003857 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003858 if (bp_pd_state) {
3859 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3860 }
3861}
3862
3863void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3864 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3865 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003866 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003867 if (bp_pd_data) {
3868 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3869
3870 if (*pPresentModeCount) {
3871 if (call_state < QUERY_COUNT) {
3872 call_state = QUERY_COUNT;
3873 }
3874 }
3875 if (pPresentModes) {
3876 if (call_state < QUERY_DETAILS) {
3877 call_state = QUERY_DETAILS;
3878 }
3879 }
3880 }
3881}
3882
3883void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3884 uint32_t* pSurfaceFormatCount,
3885 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003886 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003887 if (bp_pd_data) {
3888 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3889
3890 if (*pSurfaceFormatCount) {
3891 if (call_state < QUERY_COUNT) {
3892 call_state = QUERY_COUNT;
3893 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003894 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003895 }
3896 if (pSurfaceFormats) {
3897 if (call_state < QUERY_DETAILS) {
3898 call_state = QUERY_DETAILS;
3899 }
3900 }
3901 }
3902}
3903
3904void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3905 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3906 uint32_t* pSurfaceFormatCount,
3907 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003908 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003909 if (bp_pd_data) {
3910 if (*pSurfaceFormatCount) {
3911 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3912 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3913 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003914 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003915 }
3916 if (pSurfaceFormats) {
3917 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3918 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3919 }
3920 }
3921 }
3922}
3923
3924void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3925 uint32_t* pPropertyCount,
3926 VkDisplayPlanePropertiesKHR* pProperties,
3927 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003928 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003929 if (bp_pd_data) {
3930 if (*pPropertyCount) {
3931 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3932 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3933 }
3934 }
3935 if (pProperties) {
3936 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3937 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3938 }
3939 }
3940 }
3941}
3942
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003943void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3944 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3945 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003946 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003947 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3948 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3949 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003950 }
3951 }
3952}
3953
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003954void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3955 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3956
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06003957 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003958 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003959 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003960 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003961 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003962 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07003963 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003964 }
3965 }
3966 }
3967}