blob: 572da034697cdae9bde886c060b477c3d2ca354e [file] [log] [blame]
Jeremy Gebben610d3a62022-01-01 12:53:17 -07001/* Copyright (c) 2015-2022 The Khronos Group Inc.
2 * Copyright (c) 2015-2022 Valve Corporation
3 * Copyright (c) 2015-2022 LunarG, Inc.
Nadav Geva41c12a22021-05-21 13:14:05 -04004 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
Camdeneaa86ea2019-07-26 11:00:09 -06005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Camden Stocker <camden@lunarg.com>
Nadav Geva41c12a22021-05-21 13:14:05 -040019 * Author: Nadav Geva <nadav.geva@amd.com>
Camdeneaa86ea2019-07-26 11:00:09 -060020 */
21
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070022#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060023#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060024#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010025#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070026#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060027#include "cmd_buffer_state.h"
28#include "device_state.h"
29#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060030
31#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000032#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010033#include <memory>
Camden5b184be2019-08-13 07:50:19 -060034
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037 std::string name;
38};
39
LawG475463092022-02-22 10:45:54 +000040const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {{kBPVendorArm, {vendor_specific_arm, "Arm"}},
41 {kBPVendorAMD, {vendor_specific_amd, "AMD"}},
Rodrigo Locattic779cb32022-02-25 19:26:31 -030042 {kBPVendorIMG, {vendor_specific_img, "IMG"}},
43 {kBPVendorNVIDIA, {vendor_specific_nvidia, "NVIDIA"}}};
Attilio Provenzano19d6a982020-02-27 12:41:41 +000044
Hannes Harnisch607d1d92021-07-10 18:44:56 +020045const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
48 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
49 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
50 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
51};
52
53const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
56 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
57 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
58 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
59};
60
Jeremy Gebben20da7a12022-02-25 14:07:46 -070061ReadLockGuard BestPractices::ReadLock() {
62 if (fine_grained_locking) {
63 return ReadLockGuard(validation_object_mutex, std::defer_lock);
64 } else {
65 return ReadLockGuard(validation_object_mutex);
66 }
67}
68
69WriteLockGuard BestPractices::WriteLock() {
70 if (fine_grained_locking) {
71 return WriteLockGuard(validation_object_mutex, std::defer_lock);
72 } else {
73 return WriteLockGuard(validation_object_mutex);
74 }
75}
76
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060077std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
78 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060079 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -070080 return std::static_pointer_cast<CMD_BUFFER_STATE>(std::make_shared<bp_state::CommandBuffer>(this, cb, pCreateInfo, pool));
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060081}
82
Jeremy Gebben20da7a12022-02-25 14:07:46 -070083bp_state::CommandBuffer::CommandBuffer(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
84 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060085 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
86
Attilio Provenzano19d6a982020-02-27 12:41:41 +000087bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070088 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060089 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000090 return true;
91 }
92 }
93 return false;
94}
95
96const char* VendorSpecificTag(BPVendorFlags vendors) {
97 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070098 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000099
100 auto res = tag_map.find(vendors);
101 if (res == tag_map.end()) {
102 // Build the vendor tag string
103 std::stringstream vendor_tag;
104
105 vendor_tag << "[";
106 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700107 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000108 if (vendors & vendor.first) {
109 if (!first_vendor) {
110 vendor_tag << ", ";
111 }
112 vendor_tag << vendor.second.name;
113 first_vendor = false;
114 }
115 }
116 vendor_tag << "]";
117
118 tag_map[vendors] = vendor_tag.str();
119 res = tag_map.find(vendors);
120 }
121
122 return res->second.c_str();
123}
124
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700125const char* DepReasonToString(ExtDeprecationReason reason) {
126 switch (reason) {
127 case kExtPromoted:
128 return "promoted to";
129 break;
130 case kExtObsoleted:
131 return "obsoleted by";
132 break;
133 case kExtDeprecated:
134 return "deprecated by";
135 break;
136 default:
137 return "";
138 break;
139 }
140}
141
142bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
143 const char* vuid) const {
144 bool skip = false;
145 auto dep_info_it = deprecated_extensions.find(extension_name);
146 if (dep_info_it != deprecated_extensions.end()) {
147 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600148 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700149 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
150 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700151 skip |=
152 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
153 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600154 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700155 if (dep_info.target.length() == 0) {
156 skip |= LogWarning(instance, vuid,
157 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
158 "without replacement.",
159 api_name, extension_name);
160 } else {
161 skip |= LogWarning(instance, vuid,
162 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
163 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
164 }
165 }
166 }
167 return skip;
168}
169
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200170bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
171{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700172 bool skip = false;
173 auto dep_info_it = special_use_extensions.find(extension_name);
174
175 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200176 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
177 "and it is strongly recommended that it be otherwise avoided.";
178 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800179
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700180 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800181 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
182 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700183 }
184 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200185 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
186 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700187 }
188 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200189 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
190 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700191 }
192 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200193 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
194 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700195 }
196 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200197 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700198 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200199 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700200 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700201 }
202 return skip;
203}
204
Camden5b184be2019-08-13 07:50:19 -0600205bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500206 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600207 bool skip = false;
208
209 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
210 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800211 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700212 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
213 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600214 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600215 uint32_t specified_version =
216 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
217 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700218 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200219 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600220 }
221
222 return skip;
223}
224
Camden5b184be2019-08-13 07:50:19 -0600225bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500226 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600227 bool skip = false;
228
229 // get API version of physical device passed when creating device.
230 VkPhysicalDeviceProperties physical_device_properties{};
231 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500232 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600233
234 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600235 if (api_version > device_api_version) {
236 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600237 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600238
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700239 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
240 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
241 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600242 }
243
Rodrigo Locattic2d5cf42022-03-01 18:05:26 -0300244 std::vector<std::string> extensions;
245 {
246 uint32_t property_count = 0;
247 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, nullptr) == VK_SUCCESS) {
248 std::vector<VkExtensionProperties> property_list(property_count);
249 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, property_list.data()) == VK_SUCCESS) {
250 extensions.reserve(property_list.size());
251 for (const VkExtensionProperties& properties : property_list) {
252 extensions.push_back(properties.extensionName);
253 }
254 }
255 }
256 }
257
Camden5b184be2019-08-13 07:50:19 -0600258 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300259 const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
260
261 if (white_list(extension_name, kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800262 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700263 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300264 extension_name);
Camden5b184be2019-08-13 07:50:19 -0600265 }
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300266
267 skip |= ValidateDeprecatedExtensions("CreateDevice", extension_name, api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700268 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300269 skip |= ValidateSpecialUseExtensions("CreateDevice", extension_name, kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600270 }
271
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700272 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600273 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700274 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
275 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600276 }
277
LawG43f848c72022-02-23 09:35:21 +0000278 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
279 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100280 skip |= LogPerformanceWarning(
281 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000282 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100283 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
284 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
285 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000286 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100287 }
288
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300289 const bool enabled_pageable_device_local_memory = IsExtEnabled(device_extensions.vk_ext_pageable_device_local_memory);
290 if (VendorCheckEnabled(kBPVendorNVIDIA) && !enabled_pageable_device_local_memory &&
291 std::find(extensions.begin(), extensions.end(), VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) != extensions.end()) {
292 skip |= LogPerformanceWarning(
293 device, kVUID_BestPractices_CreateDevice_PageableDeviceLocalMemory,
294 "%s vkCreateDevice() called without pageable device local memory. "
295 "Use pageableDeviceLocalMemory from VK_EXT_pageable_device_local_memory when it is available.",
296 VendorSpecificTag(kBPVendorNVIDIA));
297 }
298
Camden5b184be2019-08-13 07:50:19 -0600299 return skip;
300}
301
302bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500303 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600304 bool skip = false;
305
306 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700307 std::stringstream buffer_hex;
308 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600309
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700310 skip |= LogWarning(
311 device, kVUID_BestPractices_SharingModeExclusive,
312 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
313 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700314 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600315 }
316
317 return skip;
318}
319
320bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500321 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600322 bool skip = false;
323
324 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700325 std::stringstream image_hex;
326 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600327
328 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700329 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
330 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
331 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700332 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600333 }
334
ziga-lunarg6df3d102022-03-18 17:02:14 +0100335 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
336 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
337 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
338 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
339 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
340 }
341
LawG4655f59c2022-02-23 13:55:55 +0000342 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000343 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
344 skip |= LogPerformanceWarning(
345 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000346 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000347 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
348 "and do not need to be backed by physical storage. "
349 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000350 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000351 }
352 }
353
LawG4ba113892022-02-23 14:39:02 +0000354 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
355 skip |= LogPerformanceWarning(
356 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
357 "%s vkCreateImage(): Trying to create an image with %u samples. "
358 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
359 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
360 }
361
362 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
363 skip |= LogPerformanceWarning(
364 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
365 "%s vkCreateImage(): Trying to create an image with %u samples. "
366 "The device may not have full support for true multisampling for images with more than %u samples. "
367 "XT devices support up to 8 samples, XE up to 4 samples.",
368 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
369 }
370
LawG4db16f802022-03-21 17:33:39 +0000371 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
372 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
373 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
374 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
375 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
376 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
377 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
378 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
379 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
380 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
381 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
382 VendorSpecificTag(kBPVendorIMG));
383 }
384
Nadav Gevaf0808442021-05-21 13:51:25 -0400385 if (VendorCheckEnabled(kBPVendorAMD)) {
386 std::stringstream image_hex;
387 image_hex << "0x" << std::hex << HandleToUint64(pImage);
388
389 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
390 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
391 skip |= LogPerformanceWarning(device,
392 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
393 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
394 "Using a SHARING_MODE_CONCURRENT "
395 "is not recommended with color and depth targets",
396 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
397 }
398
399 if ((pCreateInfo->usage &
400 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
401 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
402 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
403 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
404 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
405 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
406 }
407
408 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
409 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
410 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
411 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
412 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
413 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
414 }
415 }
416
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300417 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
418 std::stringstream image_hex;
419 image_hex << "0x" << std::hex << HandleToUint64(pImage);
420
421 if (pCreateInfo->tiling == VK_IMAGE_TILING_LINEAR) {
422 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateImage_TilingLinear,
423 "%s Performance warning: image (%s) is created with tiling VK_IMAGE_TILING_LINEAR. "
424 "Use VK_IMAGE_TILING_OPTIMAL instead.",
425 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
426 }
Rodrigo Locatti3290c2b2022-03-09 18:25:56 -0300427
428 if (pCreateInfo->format == VK_FORMAT_D32_SFLOAT || pCreateInfo->format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
429 skip |= LogPerformanceWarning(
430 device, kVUID_BestPractices_CreateImage_Depth32Format,
431 "%s Performance warning: image (%s) is created with a 32-bit depth format. Use VK_FORMAT_D24_UNORM_S8_UINT or "
432 "VK_FORMAT_D16_UNORM instead, unless the extra precision is needed.",
433 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
434 }
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300435 }
436
Camden5b184be2019-08-13 07:50:19 -0600437 return skip;
438}
439
440bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500441 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600442 bool skip = false;
443
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600444 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600445 if (bp_pd_state) {
446 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
447 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
448 "vkCreateSwapchainKHR() called before getting surface capabilities from "
449 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
450 }
Camden83a9c372019-08-14 11:41:38 -0600451
Shannon McPherson73e58c82021-03-05 17:14:26 -0700452 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
453 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600454 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
455 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
456 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
457 }
Camden83a9c372019-08-14 11:41:38 -0600458
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600459 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
460 skip |= LogWarning(
461 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
462 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
463 }
Camden83a9c372019-08-14 11:41:38 -0600464 }
465
Camden5b184be2019-08-13 07:50:19 -0600466 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700467 skip |=
468 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600469 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700470 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
471 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600472 }
473
ziga-lunarg79beba62022-03-30 01:17:30 +0200474 const auto present_mode = pCreateInfo->presentMode;
475 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
476 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100477 skip |= LogPerformanceWarning(
478 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
479 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
480 ", which means double buffering is going "
481 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
482 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
483 "3 to use triple buffering to maximize performance in such cases.",
484 pCreateInfo->minImageCount);
485 }
486
Szilard Pappd5f0f812020-06-22 09:01:29 +0100487 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
488 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
489 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
490 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
491 "Presentation modes which are not FIFO will present the latest available frame and discard other "
492 "frame(s) if any.",
493 VendorSpecificTag(kBPVendorArm));
494 }
495
Camden5b184be2019-08-13 07:50:19 -0600496 return skip;
497}
498
499bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
500 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500501 const VkAllocationCallbacks* pAllocator,
502 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600503 bool skip = false;
504
505 for (uint32_t i = 0; i < swapchainCount; i++) {
506 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700507 skip |= LogWarning(
508 device, kVUID_BestPractices_SharingModeExclusive,
509 "Warning: A shared swapchain (index %" PRIu32
510 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
511 "queues (queueFamilyIndexCount of %" PRIu32 ").",
512 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600513 }
514 }
515
516 return skip;
517}
518
519bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500520 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600521 bool skip = false;
522
523 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
524 VkFormat format = pCreateInfo->pAttachments[i].format;
525 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
526 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
527 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700528 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
529 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
530 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
531 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
532 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600533 }
534 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700535 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
536 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
537 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
538 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
539 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600540 }
541 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000542
543 const auto& attachment = pCreateInfo->pAttachments[i];
544 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
545 bool access_requires_memory =
546 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
547
548 if (FormatHasStencil(format)) {
549 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
550 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
551 }
552
553 if (access_requires_memory) {
554 skip |= LogPerformanceWarning(
555 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
556 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
557 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
558 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
559 i, static_cast<uint32_t>(attachment.samples));
560 }
561 }
Camden5b184be2019-08-13 07:50:19 -0600562 }
563
564 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
565 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
566 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
567 }
568
569 return skip;
570}
571
Tony-LunarG767180f2020-04-23 14:03:59 -0600572bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
573 const VkImageView* image_views) const {
574 bool skip = false;
575
576 // Check for non-transient attachments that should be transient and vice versa
577 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200578 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600579 bool attachment_should_be_transient =
580 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
581
582 if (FormatHasStencil(attachment.format)) {
583 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
584 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
585 }
586
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600587 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600588 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600589 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600590
591 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
592
593 // The check for an image that should not be transient applies to all GPUs
594 if (!attachment_should_be_transient && image_is_transient) {
595 skip |= LogPerformanceWarning(
596 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
597 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
598 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
599 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
600 i);
601 }
602
603 bool supports_lazy = false;
604 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
605 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
606 supports_lazy = true;
607 }
608 }
609
610 // The check for an image that should be transient only applies to GPUs supporting
611 // lazily allocated memory
612 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
613 skip |= LogPerformanceWarning(
614 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
615 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
616 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
617 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
618 i);
619 }
620 }
621 }
622 return skip;
623}
624
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000625bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
626 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
627 bool skip = false;
628
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600629 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800630 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600631 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000632 }
633
634 return skip;
635}
636
Sam Wallse746d522020-03-16 21:20:23 +0000637bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
638 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
639 bool skip = false;
640 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
641
642 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700643 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000644 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
645 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700646 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000647 skip |= LogPerformanceWarning(
648 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
649 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
650 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
651 VendorSpecificTag(kBPVendorArm));
652 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200653
654 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
655 // Track number of descriptorSets allowable in this pool
656 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
657 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
658 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
659 ". This pool only has %" PRIu32 " descriptorSets remaining.",
660 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
661 pool_state->GetAvailableSets());
662 }
663 }
Sam Wallse746d522020-03-16 21:20:23 +0000664 }
665
666 return skip;
667}
668
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600669void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
670 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000671 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700672 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
673 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000674 // we record successful allocations by subtracting the allocation count from the last recorded free count
675 const auto alloc_count = pAllocateInfo->descriptorSetCount;
676 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700677 if (pool_state->freed_count > alloc_count) {
678 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700679 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700680 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700681 }
Sam Wallse746d522020-03-16 21:20:23 +0000682 }
683 }
684}
685
686void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
687 const VkDescriptorSet* pDescriptorSets, VkResult result) {
688 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
689 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700690 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000691 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700692 if (pool_state) {
693 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000694 }
695 }
696}
697
Camden5b184be2019-08-13 07:50:19 -0600698bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500699 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600700 bool skip = false;
701
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700702 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700703 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
704 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600705 }
706
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000707 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
708 skip |= LogPerformanceWarning(
709 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600710 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
711 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000712 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
713 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
714 }
715
Rodrigo Locattie4f8d522022-03-15 16:30:49 -0300716 if (VendorCheckEnabled(kBPVendorNVIDIA) && !device_extensions.vk_ext_pageable_device_local_memory &&
717 !LvlFindInChain<VkMemoryPriorityAllocateInfoEXT>(pAllocateInfo->pNext)) {
718 skip |= LogPerformanceWarning(
719 device, kVUID_BestPractices_AllocateMemory_SetPriority,
720 "%s Use VkMemoryPriorityAllocateInfoEXT to provide the operating system information on the allocations that "
721 "should stay in video memory and which should be demoted first when video memory is limited. "
722 "The highest priority should be given to GPU-written resources like color attachments, depth attachments, "
723 "storage images, and buffers written from the GPU.",
724 VendorSpecificTag(kBPVendorNVIDIA));
725 }
726
Camden83a9c372019-08-14 11:41:38 -0600727 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
728
729 return skip;
730}
731
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600732void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
733 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
734 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700735 if (result != VK_SUCCESS) {
736 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
737 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800738 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700739 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600740 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700741 return;
742 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700743}
Camden Stocker9738af92019-10-16 13:54:03 -0700744
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600745void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
746 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700747 auto error = std::find(error_codes.begin(), error_codes.end(), result);
748 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000749 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
750 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
751
752 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
753 if (common_failure != common_failure_codes.end()) {
754 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
755 } else {
756 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
757 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700758 return;
759 }
760 auto success = std::find(success_codes.begin(), success_codes.end(), result);
761 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600762 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
763 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500764 }
765}
766
Jeff Bolz5c801d12019-10-09 10:38:45 -0500767bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
768 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700769 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600770 bool skip = false;
771
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700772 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600773
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700774 for (const auto& item : mem_info->ObjectBindings()) {
775 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600776 LogObjectList objlist(device);
777 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600778 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600779 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 -0600780 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600781 }
782
Camden5b184be2019-08-13 07:50:19 -0600783 return skip;
784}
785
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000786bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600787 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700788 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600789
sfricke-samsunge2441192019-11-06 14:07:57 -0800790 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700791 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
792 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
793 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600794 }
795
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700796 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000797
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300798 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000799 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
800 skip |= LogPerformanceWarning(
801 device, kVUID_BestPractices_SmallDedicatedAllocation,
802 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600803 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
804 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000805 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
806 }
807
Camden Stockerb603cc82019-09-03 10:09:02 -0600808 return skip;
809}
810
811bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500812 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600813 bool skip = false;
814 const char* api_name = "BindBufferMemory()";
815
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000816 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600817
818 return skip;
819}
820
821bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500822 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600823 char api_name[64];
824 bool skip = false;
825
826 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200827 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000828 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600829 }
830
831 return skip;
832}
Camden Stockerb603cc82019-09-03 10:09:02 -0600833
834bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500835 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600836 char api_name[64];
837 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600838
Camden Stocker8b798ab2019-09-03 10:33:28 -0600839 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200840 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000841 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600842 }
843
844 return skip;
845}
846
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000847bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600848 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700849 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600850
sfricke-samsung71bc6572020-04-29 15:49:43 -0700851 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600852 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700853 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
854 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
855 api_name, report_data->FormatHandle(image).c_str());
856 }
857 } else {
858 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
859 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600860 }
861
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700862 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000863
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600864 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000865 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
866 skip |= LogPerformanceWarning(
867 device, kVUID_BestPractices_SmallDedicatedAllocation,
868 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600869 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
870 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000871 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
872 }
873
874 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
875 // make sure this type is actually used.
876 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
877 // (i.e.most tile - based renderers)
878 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
879 bool supports_lazy = false;
880 uint32_t suggested_type = 0;
881
882 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600883 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000884 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
885 supports_lazy = true;
886 suggested_type = i;
887 break;
888 }
889 }
890 }
891
892 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
893
894 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
895 skip |= LogPerformanceWarning(
896 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600897 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000898 "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 -0600899 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600900 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000901 }
902 }
903
Camden Stocker8b798ab2019-09-03 10:33:28 -0600904 return skip;
905}
906
907bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500908 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600909 bool skip = false;
910 const char* api_name = "vkBindImageMemory()";
911
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000912 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600913
914 return skip;
915}
916
917bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500918 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600919 char api_name[64];
920 bool skip = false;
921
922 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200923 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700924 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600925 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
926 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600927 }
928
929 return skip;
930}
931
932bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500933 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600934 char api_name[64];
935 bool skip = false;
936
937 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200938 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000939 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600940 }
941
942 return skip;
943}
Camden83a9c372019-08-14 11:41:38 -0600944
Attilio Provenzano02859b22020-02-27 14:17:28 +0000945static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
946 switch (format) {
947 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
948 case VK_FORMAT_R16_SFLOAT:
949 case VK_FORMAT_R16G16_SFLOAT:
950 case VK_FORMAT_R16G16B16_SFLOAT:
951 case VK_FORMAT_R16G16B16A16_SFLOAT:
952 case VK_FORMAT_R32_SFLOAT:
953 case VK_FORMAT_R32G32_SFLOAT:
954 case VK_FORMAT_R32G32B32_SFLOAT:
955 case VK_FORMAT_R32G32B32A32_SFLOAT:
956 return false;
957
958 default:
959 return true;
960 }
961}
962
963bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
964 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
965 bool skip = false;
966
967 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700968 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000969
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700970 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
971 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
972 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000973 return skip;
974 }
975
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600976 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200977 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000978
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200979 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
980 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
981
982 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200983 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000984 uint32_t att = subpass.pColorAttachments[j].attachment;
985
986 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
987 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
988 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
989 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
990 "color attachment #%u makes use "
991 "of a format which cannot be blended at full throughput when using MSAA.",
992 VendorSpecificTag(kBPVendorArm), i, j);
993 }
994 }
995 }
996 }
997
998 return skip;
999}
1000
Nadav Gevaf0808442021-05-21 13:51:25 -04001001void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1002 const VkComputePipelineCreateInfo* pCreateInfos,
1003 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1004 VkResult result, void* pipe_state) {
1005 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001006 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -04001007}
1008
Camden5b184be2019-08-13 07:50:19 -06001009bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1010 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001011 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001012 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001013 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1014 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +01001015 if (skip) {
1016 return skip;
1017 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001018 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001019
1020 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001021 skip |= LogPerformanceWarning(
1022 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1023 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
1024 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001025 }
1026
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001027 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001028 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001029
Tony-LunarGb6a2daf2022-07-29 11:30:55 -06001030 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 +02001031 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001032 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001033 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
1034 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001035 count++;
1036 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001037 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001038 if (count > kMaxInstancedVertexBuffers) {
1039 skip |= LogPerformanceWarning(
1040 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
1041 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
1042 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
1043 count, kMaxInstancedVertexBuffers);
1044 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001045 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001046
Szilard Pappaaf2da32020-06-22 10:37:35 +01001047 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1048 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001049 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1050 VendorCheckEnabled(kBPVendorArm)) {
1051 skip |= LogPerformanceWarning(
1052 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1053 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1054 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1055 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1056 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1057 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001058 }
1059
Attilio Provenzano02859b22020-02-27 14:17:28 +00001060 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001061 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001062 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001063 auto prev_pipeline = pipeline_cache_.load();
1064 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001065 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
1066 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
1067 "improve cache hit rate", VendorSpecificTag(kBPVendorAMD));
1068 }
1069
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001070 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001071 skip |=
1072 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1073 "%s Performance warning: Too many pipelines created, consider consolidation",
1074 VendorSpecificTag(kBPVendorAMD));
1075 }
1076
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001077 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001078 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1079 "%s Performance warning: Use of primitive restart is not recommended",
1080 VendorSpecificTag(kBPVendorAMD));
1081 }
1082
1083 // TODO: this might be too aggressive of a check
1084 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1085 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1086 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1087 VendorSpecificTag(kBPVendorAMD));
1088 }
1089 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001090
Camden5b184be2019-08-13 07:50:19 -06001091 return skip;
1092}
1093
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001094static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1095 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1096 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001097 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001098 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001099 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001100
1101 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1102
1103 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1104 // are only non-null if they are enabled.
1105 if (create_info.pColorBlendState) {
1106 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1107 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1108 for (uint32_t j = 0; j < num_color_attachments; j++) {
1109 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1110 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1111 if (attachment != VK_ATTACHMENT_UNUSED) {
1112 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1113 }
1114 }
1115 }
1116 }
1117
1118 if (create_info.pDepthStencilState &&
1119 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1120 create_info.pDepthStencilState->stencilTestEnable)) {
1121 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1122 if (attachment != VK_ATTACHMENT_UNUSED) {
1123 VkImageAspectFlags aspects = 0;
1124 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1125 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1126 }
1127 if (create_info.pDepthStencilState->stencilTestEnable) {
1128 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1129 }
1130 result.push_back({attachment, aspects});
1131 }
1132 }
1133 return result;
1134}
1135
1136bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1137 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1138 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1139 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1140 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1141
1142std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1143 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1144 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1145 return std::static_pointer_cast<PIPELINE_STATE>(
1146 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001147}
1148
Sam Walls0961ec02020-03-31 16:39:15 +01001149void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1150 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1151 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1152 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001153 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001154 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001155}
1156
Camden5b184be2019-08-13 07:50:19 -06001157bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1158 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001159 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001160 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001161 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1162 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001163
1164 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001165 skip |= LogPerformanceWarning(
1166 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1167 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1168 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001169 }
1170
Nadav Gevaf0808442021-05-21 13:51:25 -04001171 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001172 auto prev_pipeline = pipeline_cache_.load();
1173 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1174 skip |= LogPerformanceWarning(
1175 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1176 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001177 "improve cache hit rate",
1178 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001179 }
1180 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001181
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001182 for (uint32_t i = 0; i < createInfoCount; i++) {
1183 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1184 if (VendorCheckEnabled(kBPVendorArm)) {
1185 skip |= ValidateCreateComputePipelineArm(createInfo);
1186 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001187
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001188 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1189 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1190 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1191 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1192 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1193 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1194 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1195 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1196 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001197 }
1198 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001199 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001200 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001201
1202 return skip;
1203}
1204
1205bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1206 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001207 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001208 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001209 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1210 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001211
1212 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001213 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001214
1215 uint32_t thread_count = x * y * z;
1216
1217 // Generate a priori warnings about work group sizes.
1218 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1219 skip |= LogPerformanceWarning(
1220 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1221 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1222 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1223 "groups with less than %u threads, especially when using barrier() or shared memory.",
1224 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1225 }
1226
1227 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1228 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1229 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1230 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1231 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1232 "%u, %u) is not aligned to %u "
1233 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1234 "leave threads idle on the shader "
1235 "core.",
1236 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1237 kThreadGroupDispatchCountAlignmentArm);
1238 }
1239
sfricke-samsungef15e482022-01-26 11:32:49 -08001240 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1241 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001242
1243 unsigned dimensions = 0;
1244 if (x > 1) dimensions++;
1245 if (y > 1) dimensions++;
1246 if (z > 1) dimensions++;
1247 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1248 dimensions = std::max(dimensions, 1u);
1249
1250 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1251 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1252 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1253 bool accesses_2d = false;
1254 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001255 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001256 if (dim < 0) continue;
1257 auto spvdim = spv::Dim(dim);
1258 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1259 }
1260
1261 if (accesses_2d && dimensions < 2) {
1262 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1263 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1264 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1265 "exhibiting poor spatial locality with respect to one or more shader resources.",
1266 VendorSpecificTag(kBPVendorArm), x, y, z);
1267 }
1268
Camden5b184be2019-08-13 07:50:19 -06001269 return skip;
1270}
1271
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001272bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001273 bool skip = false;
1274
1275 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001276 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1277 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001278 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001279 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1280 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001281 }
1282
1283 return skip;
1284}
1285
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001286bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1287 bool skip = false;
1288
1289 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1290 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1291 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1292 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1293 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1294 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1295 }
1296
1297 return skip;
1298}
1299
1300bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1301 bool skip = false;
1302 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1303
1304 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1305 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1306
1307 return skip;
1308}
1309
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001310void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001311 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1312 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1313 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1314 LogPerformanceWarning(
1315 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1316 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1317 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1318 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1319 "convenient opportunity.",
1320 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1321 }
1322 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001323
1324 // AMD best practice
1325 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001326 num_queue_submissions_ = 0;
1327 num_barriers_objects_ = 0;
1328 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001329}
1330
Jeff Bolz5c801d12019-10-09 10:38:45 -05001331bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1332 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001333 bool skip = false;
1334
1335 for (uint32_t submit = 0; submit < submitCount; submit++) {
1336 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1337 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1338 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001339 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1340 skip |=
1341 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1342 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1343 submit, submit);
1344 }
1345 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1346 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1347 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1348 submit, submit);
1349 }
Camden5b184be2019-08-13 07:50:19 -06001350 }
1351
1352 return skip;
1353}
1354
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001355bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1356 VkFence fence) const {
1357 bool skip = false;
1358
1359 for (uint32_t submit = 0; submit < submitCount; submit++) {
1360 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1361 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1362 }
1363 }
1364
1365 return skip;
1366}
1367
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001368bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1369 VkFence fence) const {
1370 bool skip = false;
1371
1372 for (uint32_t submit = 0; submit < submitCount; submit++) {
1373 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1374 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1375 }
1376 }
1377
1378 return skip;
1379}
1380
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001381bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1382 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1383 bool skip = false;
1384
1385 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1386 skip |= LogPerformanceWarning(
1387 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1388 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1389 "pool instead.");
1390 }
1391
1392 return skip;
1393}
1394
1395bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1396 const VkCommandBufferBeginInfo* pBeginInfo) const {
1397 bool skip = false;
1398
1399 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1400 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1401 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1402 }
1403
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001404 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1405 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001406 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1407 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1408 VendorSpecificTag(kBPVendorArm));
1409 }
1410
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001411 return skip;
1412}
1413
Jeff Bolz5c801d12019-10-09 10:38:45 -05001414bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001415 bool skip = false;
1416
1417 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1418
1419 return skip;
1420}
1421
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001422bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1423 const VkDependencyInfoKHR* pDependencyInfo) const {
1424 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1425}
1426
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001427bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1428 const VkDependencyInfo* pDependencyInfo) const {
1429 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1430}
1431
Jeff Bolz5c801d12019-10-09 10:38:45 -05001432bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1433 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001434 bool skip = false;
1435
1436 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1437
1438 return skip;
1439}
1440
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001441bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1442 VkPipelineStageFlags2KHR stageMask) const {
1443 bool skip = false;
1444
1445 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1446
1447 return skip;
1448}
1449
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001450bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1451 VkPipelineStageFlags2 stageMask) const {
1452 bool skip = false;
1453
1454 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1455
1456 return skip;
1457}
1458
Camden5b184be2019-08-13 07:50:19 -06001459bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1460 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1461 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1462 uint32_t bufferMemoryBarrierCount,
1463 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1464 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001465 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001466 bool skip = false;
1467
1468 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1469 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1470
1471 return skip;
1472}
1473
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001474bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1475 const VkDependencyInfoKHR* pDependencyInfos) const {
1476 bool skip = false;
1477 for (uint32_t i = 0; i < eventCount; i++) {
1478 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1479 }
1480
1481 return skip;
1482}
1483
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001484bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1485 const VkDependencyInfo* pDependencyInfos) const {
1486 bool skip = false;
1487 for (uint32_t i = 0; i < eventCount; i++) {
1488 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1489 }
1490
1491 return skip;
1492}
1493
Camden5b184be2019-08-13 07:50:19 -06001494bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1495 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1496 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1497 uint32_t bufferMemoryBarrierCount,
1498 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1499 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001500 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001501 bool skip = false;
1502
1503 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1504 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1505
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001506 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1507 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1508 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1509 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1510 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1511 "may be discarded, but the newLayout is %s, which is read only.",
1512 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1513 }
1514 }
1515
Nadav Gevaf0808442021-05-21 13:51:25 -04001516 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001517 auto num = num_barriers_objects_.load();
1518 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001519 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001520 "%s Performance warning: In this frame, %" PRIu32
1521 " barriers were already submitted. Barriers have a high cost and can "
1522 "stall the GPU. "
1523 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1524 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001525 }
1526
1527 std::array<VkImageLayout, 3> read_layouts = {
1528 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1529 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1530 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1531 };
1532
1533 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1534 // read to read barriers
1535 auto found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].oldLayout);
1536 bool old_is_read_layout = found != read_layouts.end();
1537 found = std::find(read_layouts.begin(), read_layouts.end(), pImageMemoryBarriers[i].newLayout);
1538 bool new_is_read_layout = found != read_layouts.end();
1539 if (old_is_read_layout && new_is_read_layout) {
1540 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
1541 "%s Performance warning: Don't issue read-to-read barriers. Get the resource in the right state the first "
1542 "time you use it.",
1543 VendorSpecificTag(kBPVendorAMD));
1544 }
1545
1546 // general with no storage
1547 if (pImageMemoryBarriers[i].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
1548 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1549 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1550 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1551 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1552 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1553 VendorSpecificTag(kBPVendorAMD));
1554 }
1555 }
1556 }
1557 }
1558
Camden5b184be2019-08-13 07:50:19 -06001559 return skip;
1560}
1561
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001562bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1563 const VkDependencyInfoKHR* pDependencyInfo) const {
1564 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1565}
1566
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001567bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1568 const VkDependencyInfo* pDependencyInfo) const {
1569 return CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1570}
1571
Camden5b184be2019-08-13 07:50:19 -06001572bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001573 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001574 bool skip = false;
1575
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001576 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1577
1578 return skip;
1579}
1580
1581bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1582 VkQueryPool queryPool, uint32_t query) const {
1583 bool skip = false;
1584
1585 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001586
1587 return skip;
1588}
1589
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001590bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1591 VkQueryPool queryPool, uint32_t query) const {
1592 bool skip = false;
1593
1594 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1595
1596 return skip;
1597}
1598
Sam Walls0961ec02020-03-31 16:39:15 +01001599void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1600 VkPipeline pipeline) {
1601 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1602
Nadav Gevaf0808442021-05-21 13:51:25 -04001603 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001604 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001605
Sam Walls0961ec02020-03-31 16:39:15 +01001606 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001607 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001608 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001609 if (pipeline_state) {
1610 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001611 assert(cb_node);
1612 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001613
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001614 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001615 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001616
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001617 const auto* blend_state = pipeline_state->ColorBlendState();
1618 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001619
1620 if (blend_state) {
1621 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001622 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001623 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1624 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001625 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001626 }
1627 }
1628 }
1629
1630 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001631 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001632
1633 if (stencil_state && stencil_state->depthTestEnable) {
1634 switch (stencil_state->depthCompareOp) {
1635 case VK_COMPARE_OP_EQUAL:
1636 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1637 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001638 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001639 break;
1640 default:
1641 break;
1642 }
1643 }
Sam Walls0961ec02020-03-31 16:39:15 +01001644 }
1645 }
1646}
1647
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001648static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1649 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1650 const auto& subpass_info = createInfo.pSubpasses[subpass];
1651 if (subpass_info.pResolveAttachments) {
1652 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1653 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1654 }
1655 }
1656 }
1657
1658 return false;
1659}
1660
Attilio Provenzano02859b22020-02-27 14:17:28 +00001661static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1662 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001663 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001664
1665 // If an attachment is ever used as a color attachment,
1666 // resolve attachment or depth stencil attachment,
1667 // it needs to exist on tile at some point.
1668
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001669 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1670 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001671 }
1672
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001673 if (subpass_info.pResolveAttachments) {
1674 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1675 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1676 }
1677 }
1678
1679 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001680 }
1681
1682 return false;
1683}
1684
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001685static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1686 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1687 return false;
1688 }
1689
1690 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001691 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001692
1693 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1694 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1695 return true;
1696 }
1697 }
1698 }
1699
1700 return false;
1701}
1702
Attilio Provenzano02859b22020-02-27 14:17:28 +00001703bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1704 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1705 bool skip = false;
1706
1707 if (!pRenderPassBegin) {
1708 return skip;
1709 }
1710
Gareth Webbdc6549a2021-06-16 03:52:24 +01001711 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1712 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1713 "This render pass has a zero-size render area. It cannot write to any attachments, "
1714 "and can only be used for side effects such as layout transitions.");
1715 }
1716
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001717 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001718 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001719 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001720 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001721 if (rpabi) {
1722 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1723 }
1724 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001725 // Check if any attachments have LOAD operation on them
1726 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001727 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001728
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001729 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001730 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001731 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001732 }
1733
1734 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001735 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001736 }
1737
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001738 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001739
1740 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001741 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1742 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001743 }
1744
1745 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00001746 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
1747 skip |=
1748 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00001749 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00001750 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04001751 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00001752 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
1753 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
1754 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1755 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1756 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001757 }
1758 }
paul-lunarg7089e272022-06-20 22:19:37 +02001759
1760 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
1761
1762 bool clearing = false;
1763
1764 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
1765 const auto& attachment = rp_state->createInfo.pAttachments[att];
1766
1767 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1768 clearing = true;
1769 break;
1770 }
1771 }
1772
1773 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
1774 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
1775 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
1776 skip |= LogWarning(
1777 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
1778 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
1779 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02001780 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02001781 }
paul-lunarga0a149c2022-06-23 16:18:51 +02001782
1783 // Check if there are more clearValues than attachments
1784 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
1785 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
1786 // This could signal a bug and there seems to be no reason for this to happen on purpose.
1787 skip |= LogWarning(
1788 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
1789 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
1790 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
1791 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
1792 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001793 }
1794
1795 return skip;
1796}
1797
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001798void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1799 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001800 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001801 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
1802 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001803 }
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 VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001808 // If we're viewing a 3D slice, ignore base array layer.
1809 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001810 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 +02001811
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001812 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001813 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001814 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
1815 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001816
1817 for (uint32_t layer = 0; layer < array_layers; layer++) {
1818 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001819 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1820 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001821 }
1822 }
1823}
1824
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001825void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1826 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
1827 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001828 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001829
1830 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001831 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001832 }
1833}
1834
paul-lunarg5eb52062022-06-27 18:57:15 +02001835void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
1836 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
1837 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
1838 const CMD_BUFFER_STATE&) -> bool {
1839 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
1840 return false;
1841 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001842}
1843
LawG44d414ba2022-02-23 15:35:41 +00001844void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001845 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001846 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001847 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001848 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 -07001849 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001850 LogPerformanceWarning(
1851 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00001852 "%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 +02001853 "image was used, it was written to with STORE_OP_STORE. "
1854 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1855 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00001856 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001857 } 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 +02001858 LogPerformanceWarning(
1859 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00001860 "%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 +02001861 "image was used, it was written to with vkCmdClear*Image(). "
1862 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00001863 "tile-based architectures.",
1864 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001865 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001866 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1867 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001868 const char *last_cmd = nullptr;
1869 const char *vuid = nullptr;
1870 const char *suggestion = nullptr;
1871
1872 switch (last_usage) {
1873 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1874 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1875 last_cmd = "vkCmdBlitImage";
1876 suggestion =
1877 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1878 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1879 "which avoids the memory roundtrip.";
1880 break;
1881 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1882 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1883 last_cmd = "vkCmdClear*Image";
1884 suggestion =
1885 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1886 "tile-based architectures. "
1887 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1888 break;
1889 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1890 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1891 last_cmd = "vkCmdCopy*Image";
1892 suggestion =
1893 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1894 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1895 "which avoids the memory roundtrip.";
1896 break;
1897 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1898 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1899 last_cmd = "vkCmdResolveImage";
1900 suggestion =
1901 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1902 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1903 "which avoids the memory roundtrip.";
1904 break;
1905 default:
1906 break;
1907 }
1908
1909 LogPerformanceWarning(
1910 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00001911 "%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 +01001912 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00001913 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
1914 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001915 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001916}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001917
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001918void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
1919 uint32_t array_layer, uint32_t mip_level) {
1920 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02001921
1922 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
1923 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
1924 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
1925 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
1926 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
1927 "result in undefined behaviour.");
1928 }
1929
LawG44d414ba2022-02-23 15:35:41 +00001930 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
1931 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001932 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001933}
1934
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001935void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
1936 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
1937 cb.queue_submit_functions_after_render_pass.end());
1938 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001939}
1940
1941void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1942 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001943 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1944 if (cb_node) {
1945 AddDeferredQueueOperations(*cb_node);
1946 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001947}
1948
1949void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1950 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001951 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1952 if (cb_node) {
1953 AddDeferredQueueOperations(*cb_node);
1954 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001955}
1956
1957void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1958 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001959 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1960 if (cb_node) {
1961 AddDeferredQueueOperations(*cb_node);
1962 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001963}
1964
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001965void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1966 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001967 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001968 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001969 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1970}
1971
1972void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1973 const VkRenderPassBeginInfo* pRenderPassBegin,
1974 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1975 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1976 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1977}
1978
1979void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1980 const VkRenderPassBeginInfo* pRenderPassBegin,
1981 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1982 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1983 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1984}
1985
1986void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001987
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001988 if (!pRenderPassBegin) {
1989 return;
1990 }
1991
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001992 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001993
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001994 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001995 if (rp_state) {
1996 // Check load ops
1997 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001998 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001999
2000 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
2001 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2002 continue;
2003 }
2004
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002005 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002006
2007 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
2008 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002009 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002010 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
2011 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002012 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002013 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002014 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002015 }
2016
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002017 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002018 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002019
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002020 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002021 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2022 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002023 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002024 }
2025 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002026 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002027 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002028
Jeremy Gebben9f537102021-10-05 16:37:12 -06002029 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002030 }
2031
2032 // Check store ops
2033 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002034 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002035
2036 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2037 continue;
2038 }
2039
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002040 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002041
2042 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2043 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002044 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002045 }
2046
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002047 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002048
Jeremy Gebben9f537102021-10-05 16:37:12 -06002049 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002050 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002051 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2052 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002053 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002054 }
2055 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002056 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002057 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002058
Jeremy Gebben9f537102021-10-05 16:37:12 -06002059 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002060 }
2061 }
2062}
2063
Attilio Provenzano02859b22020-02-27 14:17:28 +00002064bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2065 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002066 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2067 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002068 return skip;
2069}
2070
2071bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2072 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002073 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002074 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2075 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002076 return skip;
2077}
2078
2079bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002080 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002081 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2082 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002083 return skip;
2084}
2085
Sam Walls0961ec02020-03-31 16:39:15 +01002086void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2087 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002088 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002089 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002090 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2091 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002092 assert(cb);
2093 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002094 render_pass_state.touchesAttachments.clear();
2095 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002096 render_pass_state.numDrawCallsDepthOnly = 0;
2097 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2098 render_pass_state.colorAttachment = false;
2099 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002100 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002101 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002102
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002103 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002104
2105 // track depth / color attachment usage within the renderpass
2106 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2107 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002108 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002109
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002110 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002111 }
2112}
2113
2114void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2115 VkSubpassContents contents) {
2116 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2117 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2118}
2119
2120void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2121 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2122 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2123 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2124}
2125
2126void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2127 const VkRenderPassBeginInfo* pRenderPassBegin,
2128 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2129 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2130 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2131}
2132
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002133// Generic function to handle validation for all CmdDraw* type functions
2134bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2135 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002136 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002137 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002138 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2139 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002140 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002141
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002142 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002143 if (pipeline_state && pipeline_state->vertex_input_state &&
2144 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002145 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002146 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002147 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002148 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2149 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002150 }
2151 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002152
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002153 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002154 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002155 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002156 if (rp_state) {
2157 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2158 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002159 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002160 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002161 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2162 const auto* raster_state = pipe->RasterizationState();
2163 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2164 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002165 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2166 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2167 }
2168 }
2169 }
2170 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002171 }
2172 return skip;
2173}
2174
Sam Walls0961ec02020-03-31 16:39:15 +01002175void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002176 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002177 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002178 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002179 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002180 }
2181
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002182 if (cb_node->render_pass_state.drawTouchAttachments) {
2183 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2184 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002185 }
2186 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002187 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002188 }
2189}
2190
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002191void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2192 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002193 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2194 // depth prepass warnings First find the lowest enabled draw count
2195 uint32_t lowestEnabledMinDrawCount = 0;
2196 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2197 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2198 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2199
2200 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002201 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2202 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002203 }
2204}
2205
Camden5b184be2019-08-13 07:50:19 -06002206bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002207 uint32_t firstVertex, 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 vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002213 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002214 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06002215
2216 return skip;
2217}
2218
Sam Walls0961ec02020-03-31 16:39:15 +01002219void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2220 uint32_t firstVertex, uint32_t firstInstance) {
2221 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
2222 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
2223}
2224
Camden5b184be2019-08-13 07:50:19 -06002225bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002226 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06002227 bool skip = false;
2228
2229 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002230 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
2231 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06002232 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002233 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
2234
Attilio Provenzano02859b22020-02-27 14:17:28 +00002235 // Check if we reached the limit for small indexed draw calls.
2236 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002237 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002238 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002239 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00002240 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002241 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00002242 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00002243 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
2244 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00002245 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
2246 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002247 }
2248
Sam Walls8e77e4f2020-03-16 20:47:40 +00002249 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002250 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002251 }
2252
2253 return skip;
2254}
2255
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002256bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00002257 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
2258 bool skip = false;
2259
2260 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00002261
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002262 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
2263 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002264
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002265 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002266 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00002267 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
2268 const void* ib_mem = ib_mem_state.p_driver_data;
2269 bool primitive_restart_enable = false;
2270
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002271 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002272 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002273 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002274
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002275 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
2276 if (ia_state) {
2277 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002278 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00002279
2280 // 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 -06002281 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00002282 uint32_t scan_stride;
2283 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2284 scan_stride = sizeof(uint8_t);
2285 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2286 scan_stride = sizeof(uint16_t);
2287 } else {
2288 scan_stride = sizeof(uint32_t);
2289 }
2290
2291 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
2292 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
2293
2294 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
2295 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
2296 // irrespective of whether or not they're part of the draw call.
2297
2298 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2299 uint32_t min_index = ~0u;
2300 // start with maximum as 0 and adjust to indices in the buffer
2301 uint32_t max_index = 0u;
2302
2303 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2304 // for the given index buffer
2305 uint32_t vertex_shade_count = 0;
2306
2307 PostTransformLRUCacheModel post_transform_cache;
2308
2309 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2310 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2311 // target architecture.
2312 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2313 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2314 post_transform_cache.resize(32);
2315
2316 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2317 uint32_t scan_index;
2318 uint32_t primitive_restart_value;
2319 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2320 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2321 primitive_restart_value = 0xFF;
2322 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2323 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2324 primitive_restart_value = 0xFFFF;
2325 } else {
2326 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2327 primitive_restart_value = 0xFFFFFFFF;
2328 }
2329
2330 max_index = std::max(max_index, scan_index);
2331 min_index = std::min(min_index, scan_index);
2332
2333 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2334 bool in_cache = post_transform_cache.query_cache(scan_index);
2335 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2336 if (!in_cache) vertex_shade_count++;
2337 }
2338 }
2339
2340 // 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 +01002341 // 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
2342 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002343
2344 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002345 skip |=
2346 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2347 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2348 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2349 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2350 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2351 VendorSpecificTag(kBPVendorArm),
2352 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002353 return skip;
2354 }
2355
2356 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2357 // 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 +01002358 const size_t refs_per_bucket = 64;
2359 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2360
2361 const uint32_t n_indices = max_index - min_index + 1;
2362 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2363 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2364
2365 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2366 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002367
2368 // To avoid using too much memory, we run over the indices again.
2369 // Knowing the size from the last scan allows us to record index usage with bitsets
2370 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2371 uint32_t scan_index;
2372 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2373 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2374 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2375 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2376 } else {
2377 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2378 }
2379 // keep track of the set of all indices used to reference vertices in the draw call
2380 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002381 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2382 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002383 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2384 }
2385
2386 uint32_t vertex_reference_count = 0;
2387 for (const auto& bitset : vertex_reference_buckets) {
2388 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2389 }
2390
2391 // 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 -07002392 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002393 // 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 -07002394 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002395
2396 if (utilization < 0.5f) {
2397 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2398 "%s The indices which were specified for the draw call only utilise approximately "
2399 "%.02f%% of the bound vertex buffer.",
2400 VendorSpecificTag(kBPVendorArm), utilization);
2401 }
2402
2403 if (cache_hit_rate <= 0.5f) {
2404 skip |=
2405 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2406 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2407 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2408 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2409 "recently shaded vertices.",
2410 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2411 }
2412 }
2413
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002414 return skip;
2415}
2416
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002417bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2418 const VkCommandBuffer* pCommandBuffers) const {
2419 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002420 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002421 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002422 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002423 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002424 continue;
2425 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002426 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002427 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002428 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
2429 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002430 }
2431 }
2432 }
Nadav Gevaf0808442021-05-21 13:51:25 -04002433
2434 if (VendorCheckEnabled(kBPVendorAMD)) {
2435 if (commandBufferCount > 0) {
2436 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
2437 "%s Performance warning: Use of secondary command buffers is not recommended. ",
2438 VendorSpecificTag(kBPVendorAMD));
2439 }
2440 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002441 return skip;
2442}
2443
2444void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2445 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002446 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2447
2448 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2449 if (!primary) {
2450 return;
2451 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002452
2453 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002454 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
2455 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002456 continue;
2457 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002458
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002459 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
2460 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
2461 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
2462 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002463 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002464 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002465 }
2466 }
2467
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002468 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
2469 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002470 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002471
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002472 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
2473 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002474 }
2475
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002476}
2477
Rodrigo Locatti7d716e12022-03-09 19:15:17 -03002478bool BestPractices::PreCallValidateCmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer,
2479 const VkAccelerationStructureInfoNV* pInfo,
2480 VkBuffer instanceData, VkDeviceSize instanceOffset,
2481 VkBool32 update, VkAccelerationStructureNV dst,
2482 VkAccelerationStructureNV src, VkBuffer scratch,
2483 VkDeviceSize scratchOffset) const {
2484 return ValidateBuildAccelerationStructure(commandBuffer);
2485}
2486
2487bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresIndirectKHR(
2488 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
2489 const VkDeviceAddress* pIndirectDeviceAddresses, const uint32_t* pIndirectStrides,
2490 const uint32_t* const* ppMaxPrimitiveCounts) const {
2491 return ValidateBuildAccelerationStructure(commandBuffer);
2492}
2493
2494bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresKHR(
2495 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
2496 const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const {
2497 return ValidateBuildAccelerationStructure(commandBuffer);
2498}
2499
2500bool BestPractices::ValidateBuildAccelerationStructure(VkCommandBuffer commandBuffer) const {
2501 bool skip = false;
2502 auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
2503 assert(cb_node);
2504
2505 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2506 if ((cb_node->GetQueueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) {
2507 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_AccelerationStructure_NotAsync,
2508 "%s Performance warning: Prefer building acceleration structures on an asynchronous "
2509 "compute queue, instead of using the universal graphics queue.",
2510 VendorSpecificTag(kBPVendorNVIDIA));
2511 }
2512 }
2513
2514 return skip;
2515}
2516
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002517void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2518 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002519 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002520 auto itr =
2521 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2522 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002523
2524 if (itr != state.touchesAttachments.end()) {
2525 itr->aspects |= aspects;
2526 } else {
2527 state.touchesAttachments.push_back({ fb_attachment, aspects });
2528 }
2529}
2530
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002531void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002532 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
2533 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002534 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002535 // If we observe a full clear before any other access to a frame buffer attachment,
2536 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002537 auto itr =
2538 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
2539 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002540
2541 uint32_t new_aspects = aspects;
2542 if (itr != state.touchesAttachments.end()) {
2543 new_aspects = aspects & ~itr->aspects;
2544 itr->aspects |= aspects;
2545 } else {
2546 state.touchesAttachments.push_back({ fb_attachment, aspects });
2547 }
2548
2549 if (new_aspects == 0) {
2550 return;
2551 }
2552
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002553 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002554 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2555 // CmdExecuteCommands.
2556 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2557 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2558 }
2559}
2560
2561void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2562 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2563 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002564 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
2565
2566 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2567 auto* rp_state = cmd_state->activeRenderPass.get();
2568 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002569 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2570
2571 if (rectCount == 0 || !rp_state) {
2572 return;
2573 }
2574
2575 if (!is_secondary && !fb_state) {
2576 return;
2577 }
2578
2579 // 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 -07002580 bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002581
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06002582 if (!rp_state->UsesDynamicRendering()) {
ziga-lunarg885c6542022-03-07 01:08:25 +01002583 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2584 for (uint32_t i = 0; i < attachmentCount; i++) {
2585 auto& attachment = pClearAttachments[i];
2586 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2587 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002588
ziga-lunarg885c6542022-03-07 01:08:25 +01002589 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2590 if (subpass.pDepthStencilAttachment) {
2591 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2592 }
2593 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2594 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002595 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002596
ziga-lunarg885c6542022-03-07 01:08:25 +01002597 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2598 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002599 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01002600 aspects, rectCount, pRects);
2601 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002602 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01002603 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002604 }
2605 }
2606 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002607}
2608
Attilio Provenzano02859b22020-02-27 14:17:28 +00002609void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2610 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2611 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2612 firstInstance);
2613
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002614 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002615 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2616 cmd_state->small_indexed_draw_call_count++;
2617 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002618
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002619 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002620}
2621
Sam Walls0961ec02020-03-31 16:39:15 +01002622void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2623 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2624 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2625 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2626}
2627
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002628bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2629 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2630 uint32_t maxDrawCount, uint32_t stride) const {
2631 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2632
2633 return skip;
2634}
2635
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002636bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2637 VkDeviceSize offset, VkBuffer countBuffer,
2638 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2639 uint32_t stride) const {
2640 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002641
2642 return skip;
2643}
2644
2645bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002646 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002647 bool skip = false;
2648
2649 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002650 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2651 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002652 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002653 }
2654
2655 return skip;
2656}
2657
Sam Walls0961ec02020-03-31 16:39:15 +01002658void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2659 uint32_t count, uint32_t stride) {
2660 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2661 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2662}
2663
Camden5b184be2019-08-13 07:50:19 -06002664bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002665 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002666 bool skip = false;
2667
2668 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002669 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2670 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002671 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002672 }
2673
2674 return skip;
2675}
2676
Sam Walls0961ec02020-03-31 16:39:15 +01002677void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2678 uint32_t count, uint32_t stride) {
2679 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2680 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2681}
2682
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002683void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
2684 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002685 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002686 // For bindless scenarios, we should not attempt to track descriptor set state.
2687 // It is highly uncertain which resources are actually bound.
2688 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002689 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2690 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002691 continue;
2692 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002693
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002694 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002695 VkImageView image_view{VK_NULL_HANDLE};
2696
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002697 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02002698 if (!descriptor) {
2699 continue;
2700 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002701 switch (descriptor->GetClass()) {
2702 case cvdescriptorset::DescriptorClass::Image: {
2703 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2704 image_view = image_descriptor->GetImageView();
2705 }
2706 break;
2707 }
2708 case cvdescriptorset::DescriptorClass::ImageSampler: {
2709 if (const auto image_sampler_descriptor =
2710 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2711 image_view = image_sampler_descriptor->GetImageView();
2712 }
2713 break;
2714 }
2715 default:
2716 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002717 }
2718
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002719 if (image_view) {
2720 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
2721 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
2722 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002723 }
2724 }
2725 }
2726 }
2727}
2728
2729void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2730 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002731 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2732 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002733}
2734
2735void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2736 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002737 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2738 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002739}
2740
2741void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2742 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002743 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2744 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002745}
2746
Camden5b184be2019-08-13 07:50:19 -06002747bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002748 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002749 bool skip = false;
2750
2751 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002752 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2753 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2754 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2755 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002756 }
2757
2758 return skip;
2759}
Camden83a9c372019-08-14 11:41:38 -06002760
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002761bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2762 bool skip = false;
2763 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2764 skip |= ValidateCmdEndRenderPass(commandBuffer);
2765 return skip;
2766}
2767
2768bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2769 bool skip = false;
2770 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2771 skip |= ValidateCmdEndRenderPass(commandBuffer);
2772 return skip;
2773}
2774
Sam Walls0961ec02020-03-31 16:39:15 +01002775bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2776 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002777 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002778 skip |= ValidateCmdEndRenderPass(commandBuffer);
2779 return skip;
2780}
2781
2782bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2783 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002784 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002785
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002786 if (cmd == nullptr) return skip;
2787 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01002788
LawG4b21485c2022-02-28 13:46:48 +00002789 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
2790 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2791 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2792 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
2793 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
2794
2795 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01002796 bool uses_depth =
2797 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01002798 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00002799
Sam Walls0961ec02020-03-31 16:39:15 +01002800 if (uses_depth) {
2801 skip |= LogPerformanceWarning(
2802 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00002803 "%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 +00002804 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
2805 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
2806 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
2807 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01002808 }
2809
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002810 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2811
LawG40da9c3d2022-03-01 09:51:01 +00002812 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002813 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2814 // it is redundant to have it be part of the render pass.
2815 // Only consider it redundant if it will actually consume bandwidth, i.e.
2816 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2817 // as is using pure input attachments.
2818 // CLEAR -> STORE might be considered a "useful" thing to do, but
2819 // the optimal thing to do is to defer the clear until you're actually
2820 // going to render to the image.
2821
2822 uint32_t num_attachments = rp->createInfo.attachmentCount;
2823 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002824 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2825 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002826 continue;
2827 }
2828
2829 auto& attachment = rp->createInfo.pAttachments[i];
2830
2831 VkImageAspectFlags bandwidth_aspects = 0;
2832
2833 if (!FormatIsStencilOnly(attachment.format) &&
2834 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2835 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2836 if (FormatHasDepth(attachment.format)) {
2837 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2838 } else {
2839 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2840 }
2841 }
2842
2843 if (FormatHasStencil(attachment.format) &&
2844 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2845 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2846 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2847 }
2848
2849 if (!bandwidth_aspects) {
2850 continue;
2851 }
2852
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002853 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002854 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002855 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002856 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002857 untouched_aspects &= ~itr->aspects;
2858 }
2859
2860 if (untouched_aspects) {
2861 skip |= LogPerformanceWarning(
2862 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00002863 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002864 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00002865 "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 +00002866 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00002867 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002868 }
2869 }
2870 }
2871
Sam Walls0961ec02020-03-31 16:39:15 +01002872 return skip;
2873}
2874
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002875void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002876 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2877 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002878}
2879
2880void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002881 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2882 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002883}
2884
Camden Stocker9c051442019-11-06 14:28:43 -08002885bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2886 const char* api_name) const {
2887 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002888 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002889
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002890 if (bp_pd_state) {
2891 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2892 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2893 "Potential problem with calling %s() without first retrieving properties from "
2894 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2895 api_name);
2896 }
Camden Stocker9c051442019-11-06 14:28:43 -08002897 }
2898
2899 return skip;
2900}
2901
Camden83a9c372019-08-14 11:41:38 -06002902bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002903 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002904 bool skip = false;
2905
Camden Stocker9c051442019-11-06 14:28:43 -08002906 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002907
Camden Stocker9c051442019-11-06 14:28:43 -08002908 return skip;
2909}
2910
2911bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2912 uint32_t planeIndex,
2913 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2914 bool skip = false;
2915
2916 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2917
2918 return skip;
2919}
2920
2921bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2922 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2923 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2924 bool skip = false;
2925
2926 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002927
2928 return skip;
2929}
Camden05de2d42019-08-19 10:23:56 -06002930
2931bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002932 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002933 bool skip = false;
2934
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002935 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002936
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002937 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002938 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002939 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002940 skip |=
2941 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2942 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2943 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002944 }
Camden05de2d42019-08-19 10:23:56 -06002945
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002946 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2947 skip |= LogWarning(
2948 device, kVUID_BestPractices_Swapchain_InvalidCount,
2949 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04002950 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002951 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2952 }
2953 }
2954
Camden05de2d42019-08-19 10:23:56 -06002955 return skip;
2956}
2957
2958// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002959bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002960 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002961 const CALL_STATE call_state,
2962 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002963 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002964 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2965 if (UNCALLED == call_state) {
2966 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002967 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002968 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2969 "recommended "
2970 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2971 caller_name, caller_name);
2972 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002973 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
2974 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002975 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2976 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2977 ". It is recommended to instead receive all the properties by calling %s with "
2978 "pQueueFamilyPropertyCount that was "
2979 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06002980 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002981 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002982 }
2983
2984 return skip;
2985}
2986
Jeff Bolz5c801d12019-10-09 10:38:45 -05002987bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2988 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002989 bool skip = false;
2990
2991 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002992 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002993 if (!as_state->memory_requirements_checked) {
2994 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2995 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2996 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002997 skip |= LogWarning(
2998 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002999 "vkBindAccelerationStructureMemoryNV(): "
3000 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
3001 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
3002 }
3003 }
3004
3005 return skip;
3006}
3007
Camden05de2d42019-08-19 10:23:56 -06003008bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3009 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003010 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003011 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003012 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003013 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003014 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3015 "vkGetPhysicalDeviceQueueFamilyProperties()");
3016 }
3017 return false;
Camden05de2d42019-08-19 10:23:56 -06003018}
3019
Mike Schuchardt2df08912020-12-15 16:28:09 -08003020bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3021 uint32_t* pQueueFamilyPropertyCount,
3022 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003023 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003024 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003025 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003026 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3027 "vkGetPhysicalDeviceQueueFamilyProperties2()");
3028 }
3029 return false;
Camden05de2d42019-08-19 10:23:56 -06003030}
3031
Jeff Bolz5c801d12019-10-09 10:38:45 -05003032bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08003033 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003034 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003035 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003036 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003037 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3038 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
3039 }
3040 return false;
Camden05de2d42019-08-19 10:23:56 -06003041}
3042
3043bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3044 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003045 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06003046 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003047 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003048 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06003049 bool skip = false;
3050 if (call_state == UNCALLED) {
3051 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
3052 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003053 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
3054 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
3055 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06003056 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003057 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003058 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
3059 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
3060 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
3061 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003062 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06003063 }
3064 }
3065 return skip;
3066}
Camden Stocker23cc47d2019-09-03 14:53:57 -06003067
3068bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003069 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003070 bool skip = false;
3071
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003072 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3073 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06003074 // 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 -07003075 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003076 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
3077 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07003078 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06003079 // 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 -07003080 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
3081 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003082 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003083 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003084 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003085 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003086 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003087 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3088 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3089 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003090 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003091 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3092 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003093 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003094 }
3095 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003096 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003097 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003098 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003099 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
3100 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003101 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003102 }
3103 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003104 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3105 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003106 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003107 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003108 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003109 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06003110 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003111 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
3112 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
3113 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003114 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003115 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3116 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003117 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003118 }
3119 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003120 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003121 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003122 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003123 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
3124 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003125 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003126 }
3127 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3128 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003129 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003130 }
3131 }
3132 }
3133 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003134 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
3135 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06003136 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003137 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003138 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
3139 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06003140 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06003141 }
3142 }
3143 }
3144
Rodrigo Locatti7ab778d2022-03-09 18:57:15 -03003145 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3146 auto queue_state = Get<QUEUE_STATE>(queue);
3147 if (queue_state && queue_state->queueFamilyProperties.queueFlags != (VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT)) {
3148 skip |= LogPerformanceWarning(queue, kVUID_BestPractices_QueueBindSparse_NotAsync,
3149 "vkQueueBindSparse() issued on queue %s. All binds should happen on an asynchronous copy "
3150 "queue to hide the OS scheduling and submit costs.",
3151 report_data->FormatHandle(queue).c_str());
3152 }
3153 }
3154
Camden Stocker23cc47d2019-09-03 14:53:57 -06003155 return skip;
3156}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003157
Mark Lobodzinski84101d72020-04-24 09:43:48 -06003158void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
3159 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003160 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07003161 return;
3162 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003163
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003164 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
3165 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
3166 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
3167 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04003168 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003169 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003170 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003171 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05003172 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
3173 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
3174 image_state->sparse_metadata_bound = true;
3175 }
3176 }
3177 }
3178 }
3179}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003180
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003181bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003182 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003183 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003184 // We don't know the accurate render area in a secondary,
3185 // so assume we clear the entire frame buffer.
3186 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
3187 return true;
3188 }
3189
3190 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
3191 for (uint32_t i = 0; i < rectCount; i++) {
3192 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003193 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003194 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
3195 return true;
3196 }
3197 }
3198
3199 return false;
3200}
3201
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003202bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
3203 VkImageAspectFlags aspects, bool secondary) const {
3204 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003205 bool skip = false;
3206
3207 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
3208 return skip;
3209 }
3210
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003211 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003212
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003213 auto attachment_itr =
3214 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
3215 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003216
3217 // Only report aspects which haven't been touched yet.
3218 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003219 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003220 new_aspects &= ~attachment_itr->aspects;
3221 }
3222
3223 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09003224 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003225 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003226 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02003227 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
3228 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003229 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003230 }
3231
3232 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
3233 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
3234 skip |= LogPerformanceWarning(
3235 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3236 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
3237 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3238 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003239 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003240 }
3241
3242 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
3243 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003244 skip |=
3245 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3246 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
3247 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3248 "it is more efficient.",
3249 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003250 }
3251
3252 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
3253 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003254 skip |=
3255 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
3256 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
3257 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
3258 "it is more efficient.",
3259 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003260 }
3261
3262 return skip;
3263}
3264
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003265bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06003266 const VkClearAttachment* pAttachments, uint32_t rectCount,
3267 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003268 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003269 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003270 if (!cb_node) return skip;
3271
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003272 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
3273 // Defer checks to ExecuteCommands.
3274 return skip;
3275 }
3276
3277 // Only care about full clears, partial clears might have legitimate uses.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003278 if (!ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects)) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003279 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003280 }
3281
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003282 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
3283 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06003284 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003285 if (rp) {
3286 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
3287
3288 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003289 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003290
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003291 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
3292 uint32_t color_attachment = attachment.colorAttachment;
3293 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003294 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003295 }
3296
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003297 if (subpass.pDepthStencilAttachment &&
3298 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003299 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003300 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00003301 }
3302 }
3303 }
3304
Nadav Gevaf0808442021-05-21 13:51:25 -04003305 if (VendorCheckEnabled(kBPVendorAMD)) {
3306 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
3307 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
3308 bool black_check = false;
3309 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
3310 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
3311 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
3312 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3313 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3314
3315 bool white_check = false;
3316 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
3317 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
3318 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
3319 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
3320 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
3321
3322 if (black_check && white_check) {
3323 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3324 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
3325 "Consider changing to one of the following:"
3326 "RGBA(0, 0, 0, 0) "
3327 "RGBA(0, 0, 0, 1) "
3328 "RGBA(1, 1, 1, 0) "
3329 "RGBA(1, 1, 1, 1)",
3330 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3331 }
3332 } else {
3333 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
3334 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
3335 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
3336 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
3337 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
3338 "attachment %" PRId32 " is not a fast clear value."
3339 "Consider changing to one of the following:"
3340 "D=0.0f, S=0"
3341 "D=1.0f, S=0",
3342 VendorSpecificTag(kBPVendorAMD), attachment_idx);
3343 }
3344 }
3345 }
3346 }
3347
Camden Stockerf55721f2019-09-09 11:04:49 -06003348 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07003349}
Attilio Provenzano02859b22020-02-27 14:17:28 +00003350
3351bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3352 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3353 const VkImageResolve* pRegions) const {
3354 bool skip = false;
3355
3356 skip |= VendorCheckEnabled(kBPVendorArm) &&
3357 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
3358 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
3359 "This is a very slow and extremely bandwidth intensive path. "
3360 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3361 VendorSpecificTag(kBPVendorArm));
3362
3363 return skip;
3364}
3365
Jeff Leger178b1e52020-10-05 12:22:23 -04003366bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3367 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
3368 bool skip = false;
3369
3370 skip |= VendorCheckEnabled(kBPVendorArm) &&
3371 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
3372 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
3373 "This is a very slow and extremely bandwidth intensive path. "
3374 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3375 VendorSpecificTag(kBPVendorArm));
3376
3377 return skip;
3378}
3379
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003380bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
3381 const VkResolveImageInfo2* pResolveImageInfo) const {
3382 bool skip = false;
3383
3384 skip |= VendorCheckEnabled(kBPVendorArm) &&
3385 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
3386 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
3387 "This is a very slow and extremely bandwidth intensive path. "
3388 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
3389 VendorSpecificTag(kBPVendorArm));
3390
3391 return skip;
3392}
3393
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003394void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3395 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3396 const VkImageResolve* 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, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3404 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003405 }
3406}
3407
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003408void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3409 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003410 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003411 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003412 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3413 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003414 uint32_t regionCount = pResolveImageInfo->regionCount;
3415
3416 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003417 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3418 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003419 }
3420}
3421
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003422void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
3423 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003424 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003425 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003426 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
3427 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07003428 uint32_t regionCount = pResolveImageInfo->regionCount;
3429
3430 for (uint32_t i = 0; i < regionCount; i++) {
3431 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
3432 pResolveImageInfo->pRegions[i].srcSubresource);
3433 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
3434 pResolveImageInfo->pRegions[i].dstSubresource);
3435 }
3436}
3437
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003438void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3439 const VkClearColorValue* pColor, uint32_t rangeCount,
3440 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003441 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003442 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003443 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003444
3445 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003446 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003447 }
3448}
3449
3450void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3451 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3452 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003453 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003454 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003455 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003456
3457 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003458 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003459 }
3460}
3461
3462void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3463 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3464 const VkImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003465 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003466 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003467 auto src = Get<bp_state::Image>(srcImage);
3468 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003469
3470 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003471 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3472 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003473 }
3474}
3475
3476void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3477 VkImageLayout dstImageLayout, uint32_t regionCount,
3478 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003479 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003480 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003481 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003482
3483 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003484 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003485 }
3486}
3487
3488void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3489 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003490 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003491 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003492 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003493
3494 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003495 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003496 }
3497}
3498
3499void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3500 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3501 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003502 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003503 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003504 auto src = Get<bp_state::Image>(srcImage);
3505 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003506
3507 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003508 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3509 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003510 }
3511}
3512
Attilio Provenzano02859b22020-02-27 14:17:28 +00003513bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3514 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3515 bool skip = false;
3516
3517 if (VendorCheckEnabled(kBPVendorArm)) {
3518 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3519 skip |= LogPerformanceWarning(
3520 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3521 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3522 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3523 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003524 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003525 }
3526
3527 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3528 skip |= LogPerformanceWarning(
3529 device, kVUID_BestPractices_CreateSampler_LodClamping,
3530 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3531 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3532 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3533 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3534 }
3535
3536 if (pCreateInfo->mipLodBias != 0.0f) {
3537 skip |=
3538 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3539 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3540 "descriptors being created and may cause reduced performance.",
3541 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3542 }
3543
3544 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3545 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3546 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3547 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3548 skip |= LogPerformanceWarning(
3549 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3550 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3551 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3552 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3553 VendorSpecificTag(kBPVendorArm));
3554 }
3555
3556 if (pCreateInfo->unnormalizedCoordinates) {
3557 skip |= LogPerformanceWarning(
3558 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3559 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3560 "descriptors being created and may cause reduced performance.",
3561 VendorSpecificTag(kBPVendorArm));
3562 }
3563
3564 if (pCreateInfo->anisotropyEnable) {
3565 skip |= LogPerformanceWarning(
3566 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3567 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3568 "and may cause reduced performance.",
3569 VendorSpecificTag(kBPVendorArm));
3570 }
3571 }
3572
3573 return skip;
3574}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003575
Nadav Gevaf0808442021-05-21 13:51:25 -04003576void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
3577 const VkGraphicsPipelineCreateInfo* pCreateInfos,
3578 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
3579 void* cgpl_state) {
3580 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
3581 pPipelines);
3582 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003583 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003584}
3585
3586bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
3587 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
3588 const VkCopyDescriptorSet* pDescriptorCopies) const {
3589 bool skip = false;
3590 if (VendorCheckEnabled(kBPVendorAMD)) {
3591 if (descriptorCopyCount > 0) {
3592 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
3593 "%s Performance warning: copying descriptor sets is not recommended",
3594 VendorSpecificTag(kBPVendorAMD));
3595 }
3596 }
3597
3598 return skip;
3599}
3600
3601bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
3602 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
3603 const VkAllocationCallbacks* pAllocator,
3604 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
3605 bool skip = false;
3606 if (VendorCheckEnabled(kBPVendorAMD)) {
3607 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
3608 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
3609 "vkUpdateDescriptorSet instead",
3610 VendorSpecificTag(kBPVendorAMD));
3611 }
3612
3613 return skip;
3614}
3615
3616bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3617 const VkClearColorValue* pColor, uint32_t rangeCount,
3618 const VkImageSubresourceRange* pRanges) const {
3619 bool skip = false;
3620 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08003621 skip |= LogPerformanceWarning(
3622 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04003623 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3624 "vkCmdClearAttachments instead",
3625 VendorSpecificTag(kBPVendorAMD));
3626 }
3627
3628 return skip;
3629}
3630
3631bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
3632 VkImageLayout imageLayout,
3633 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3634 const VkImageSubresourceRange* pRanges) const {
3635 bool skip = false;
3636 if (VendorCheckEnabled(kBPVendorAMD)) {
3637 skip |= LogPerformanceWarning(
3638 device, kVUID_BestPractices_ClearAttachment_ClearImage,
3639 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
3640 "vkCmdClearAttachments instead",
3641 VendorSpecificTag(kBPVendorAMD));
3642 }
3643
3644 return skip;
3645}
3646
3647bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
3648 const VkAllocationCallbacks* pAllocator,
3649 VkPipelineLayout* pPipelineLayout) const {
3650 bool skip = false;
3651 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003652 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04003653 // Descriptor sets cost 1 DWORD each.
3654 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
3655 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
3656 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
3657 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
3658 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06003659 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003660 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04003661 }
3662
3663 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
3664 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
3665 }
3666
3667 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
3668 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
3669 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
3670 "Descriptor sets cost 1 DWORD each. "
3671 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
3672 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
3673 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
3674 VendorSpecificTag(kBPVendorAMD));
3675 }
3676 }
3677
3678 return skip;
3679}
3680
3681bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3682 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3683 const VkImageCopy* pRegions) const {
3684 bool skip = false;
3685 std::stringstream src_image_hex;
3686 std::stringstream dst_image_hex;
3687 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
3688 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
3689
3690 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003691 auto src_state = Get<IMAGE_STATE>(srcImage);
3692 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04003693
3694 if (src_state && dst_state) {
3695 VkImageTiling src_Tiling = src_state->createInfo.tiling;
3696 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
3697 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
3698 skip |=
3699 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
3700 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
3701 "image (vkCmdCopyImageToBuffer) "
3702 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
3703 "copies when converting between linear and optimal images",
3704 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
3705 }
3706 }
3707 }
3708
3709 return skip;
3710}
3711
3712bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
3713 VkPipeline pipeline) const {
3714 bool skip = false;
3715
3716 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003717 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003718 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
3719 "%s Performance warning: Pipeline %s was bound twice in the frame. Keep pipeline state changes to a minimum,"
3720 "for example, by sorting draw calls by pipeline.",
3721 VendorSpecificTag(kBPVendorAMD), report_data->FormatHandle(pipeline).c_str());
3722 }
3723 }
3724
3725 return skip;
3726}
3727
3728void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
3729 VkFence fence, VkResult result) {
3730 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003731 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04003732}
3733
3734bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
3735 bool skip = false;
3736
3737 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003738 auto num = num_queue_submissions_.load();
3739 if (num > kNumberOfSubmissionWarningLimitAMD) {
3740 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
3741 "%s Performance warning: command buffers submitted %" PRId32
3742 " times this frame. Submitting command buffers has a CPU "
3743 "and GPU overhead. Submit fewer times to incur less overhead.",
3744 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04003745 }
3746 }
3747
3748 return skip;
3749}
3750
3751void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
3752 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
3753 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
3754 uint32_t bufferMemoryBarrierCount,
3755 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
3756 uint32_t imageMemoryBarrierCount,
3757 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003758 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Nadav Gevaf0808442021-05-21 13:51:25 -04003759}
3760
3761bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
3762 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
3763 bool skip = false;
3764 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003765 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003766 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
3767 "%s Performance warning: High number of vkSemaphore objects created."
3768 "Minimize the amount of queue synchronization that is used. "
3769 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
3770 VendorSpecificTag(kBPVendorAMD));
3771 }
3772 }
3773
3774 return skip;
3775}
3776
3777bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
3778 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
3779 bool skip = false;
3780 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003781 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04003782 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
3783 "%s Performance warning: High number of VkFence objects created."
3784 "Minimize the amount of CPU-GPU synchronization that is used. "
3785 "Semaphores and fences have overhead.Each fence has a CPU and GPU cost with it.",
3786 VendorSpecificTag(kBPVendorAMD));
3787 }
3788 }
3789
3790 return skip;
3791}
3792
Sam Walls8e77e4f2020-03-16 20:47:40 +00003793void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3794
3795bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3796 // look for a cache hit
3797 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3798 if (hit != _entries.end()) {
3799 // mark the cache hit as being most recently used
3800 hit->age = iteration++;
3801 return true;
3802 }
3803
3804 // if there's no cache hit, we need to model the entry being inserted into the cache
3805 CacheEntry new_entry = {value, iteration};
3806 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3807 // if there is still space left in the cache, use the next available slot
3808 *(_entries.begin() + iteration) = new_entry;
3809 } else {
3810 // otherwise replace the least recently used cache entry
3811 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3812 *lru = new_entry;
3813 }
3814 iteration++;
3815 return false;
3816}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003817
3818bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3819 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003820 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003821 bool skip = false;
3822 if (swapchain_data && swapchain_data->images.size() == 0) {
3823 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3824 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3825 "vkGetSwapchainImagesKHR after swapchain creation.");
3826 }
3827 return skip;
3828}
3829
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003830void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3831 if (no_pointer) {
3832 if (UNCALLED == call_state) {
3833 call_state = QUERY_COUNT;
3834 }
3835 } else { // Save queue family properties
3836 call_state = QUERY_DETAILS;
3837 }
3838}
3839
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003840void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3841 uint32_t* pQueueFamilyPropertyCount,
3842 VkQueueFamilyProperties* pQueueFamilyProperties) {
3843 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3844 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003845 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003846 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003847 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3848 nullptr == pQueueFamilyProperties);
3849 }
3850}
3851
3852void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3853 uint32_t* pQueueFamilyPropertyCount,
3854 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3855 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3856 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003857 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003858 if (bp_pd_state) {
3859 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3860 nullptr == pQueueFamilyProperties);
3861 }
3862}
3863
3864void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3865 uint32_t* pQueueFamilyPropertyCount,
3866 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3867 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3868 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003869 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003870 if (bp_pd_state) {
3871 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3872 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003873 }
3874}
3875
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003876void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3877 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003878 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003879 if (bp_pd_state) {
3880 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3881 }
3882}
3883
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003884void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3885 VkPhysicalDeviceFeatures2* pFeatures) {
3886 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003887 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003888 if (bp_pd_state) {
3889 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3890 }
3891}
3892
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003893void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3894 VkPhysicalDeviceFeatures2* pFeatures) {
3895 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003896 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003897 if (bp_pd_state) {
3898 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3899 }
3900}
3901
3902void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3903 VkSurfaceKHR surface,
3904 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3905 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003906 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003907 if (bp_pd_state) {
3908 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3909 }
3910}
3911
3912void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3913 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3914 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003915 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003916 if (bp_pd_state) {
3917 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3918 }
3919}
3920
3921void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3922 VkSurfaceKHR surface,
3923 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3924 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003925 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003926 if (bp_pd_state) {
3927 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3928 }
3929}
3930
3931void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3932 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3933 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003934 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003935 if (bp_pd_data) {
3936 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3937
3938 if (*pPresentModeCount) {
3939 if (call_state < QUERY_COUNT) {
3940 call_state = QUERY_COUNT;
3941 }
3942 }
3943 if (pPresentModes) {
3944 if (call_state < QUERY_DETAILS) {
3945 call_state = QUERY_DETAILS;
3946 }
3947 }
3948 }
3949}
3950
3951void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3952 uint32_t* pSurfaceFormatCount,
3953 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003954 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003955 if (bp_pd_data) {
3956 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3957
3958 if (*pSurfaceFormatCount) {
3959 if (call_state < QUERY_COUNT) {
3960 call_state = QUERY_COUNT;
3961 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003962 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003963 }
3964 if (pSurfaceFormats) {
3965 if (call_state < QUERY_DETAILS) {
3966 call_state = QUERY_DETAILS;
3967 }
3968 }
3969 }
3970}
3971
3972void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3973 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3974 uint32_t* pSurfaceFormatCount,
3975 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003976 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003977 if (bp_pd_data) {
3978 if (*pSurfaceFormatCount) {
3979 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3980 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3981 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06003982 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003983 }
3984 if (pSurfaceFormats) {
3985 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3986 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3987 }
3988 }
3989 }
3990}
3991
3992void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3993 uint32_t* pPropertyCount,
3994 VkDisplayPlanePropertiesKHR* pProperties,
3995 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003996 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003997 if (bp_pd_data) {
3998 if (*pPropertyCount) {
3999 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
4000 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
4001 }
4002 }
4003 if (pProperties) {
4004 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
4005 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
4006 }
4007 }
4008 }
4009}
4010
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06004011void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
4012 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
4013 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004014 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004015 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
4016 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
4017 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06004018 }
4019 }
4020}
4021
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01004022void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
4023 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
4024
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06004025 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01004026 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02004027 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01004028 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004029 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01004030 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07004031 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01004032 }
4033 }
4034 }
4035}