blob: 1d0b807be777247fefcc46c07e10c458f48a4bc0 [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
Rodrigo Locattie4c08a02022-04-04 18:12:18 -030061static constexpr std::array<VkFormat, 12> kCustomClearColorCompressedFormatsNVIDIA = {
62 VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_A8B8G8R8_UNORM_PACK32,
63 VK_FORMAT_A2R10G10B10_UNORM_PACK32, VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_R16G16B16A16_UNORM,
64 VK_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_SINT,
65 VK_FORMAT_R16G16B16A16_SFLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32,
66};
67
Jeremy Gebben20da7a12022-02-25 14:07:46 -070068ReadLockGuard BestPractices::ReadLock() {
69 if (fine_grained_locking) {
70 return ReadLockGuard(validation_object_mutex, std::defer_lock);
71 } else {
72 return ReadLockGuard(validation_object_mutex);
73 }
74}
75
76WriteLockGuard BestPractices::WriteLock() {
77 if (fine_grained_locking) {
78 return WriteLockGuard(validation_object_mutex, std::defer_lock);
79 } else {
80 return WriteLockGuard(validation_object_mutex);
81 }
82}
83
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060084std::shared_ptr<CMD_BUFFER_STATE> BestPractices::CreateCmdBufferState(VkCommandBuffer cb,
85 const VkCommandBufferAllocateInfo* pCreateInfo,
Jeremy Gebbencd7fa282021-10-27 10:25:32 -060086 const COMMAND_POOL_STATE* pool) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -070087 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 -060088}
89
Jeremy Gebben20da7a12022-02-25 14:07:46 -070090bp_state::CommandBuffer::CommandBuffer(BestPractices* bp, VkCommandBuffer cb, const VkCommandBufferAllocateInfo* pCreateInfo,
91 const COMMAND_POOL_STATE* pool)
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -060092 : CMD_BUFFER_STATE(bp, cb, pCreateInfo, pool) {}
93
Attilio Provenzano19d6a982020-02-27 12:41:41 +000094bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070095 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060096 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000097 return true;
98 }
99 }
100 return false;
101}
102
103const char* VendorSpecificTag(BPVendorFlags vendors) {
104 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700105 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000106
107 auto res = tag_map.find(vendors);
108 if (res == tag_map.end()) {
109 // Build the vendor tag string
110 std::stringstream vendor_tag;
111
112 vendor_tag << "[";
113 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700114 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +0000115 if (vendors & vendor.first) {
116 if (!first_vendor) {
117 vendor_tag << ", ";
118 }
119 vendor_tag << vendor.second.name;
120 first_vendor = false;
121 }
122 }
123 vendor_tag << "]";
124
125 tag_map[vendors] = vendor_tag.str();
126 res = tag_map.find(vendors);
127 }
128
129 return res->second.c_str();
130}
131
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700132const char* DepReasonToString(ExtDeprecationReason reason) {
133 switch (reason) {
134 case kExtPromoted:
135 return "promoted to";
136 break;
137 case kExtObsoleted:
138 return "obsoleted by";
139 break;
140 case kExtDeprecated:
141 return "deprecated by";
142 break;
143 default:
144 return "";
145 break;
146 }
147}
148
149bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
150 const char* vuid) const {
151 bool skip = false;
152 auto dep_info_it = deprecated_extensions.find(extension_name);
153 if (dep_info_it != deprecated_extensions.end()) {
154 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600155 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
Tony-LunarGc30b59f2022-02-15 11:02:36 -0700156 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2)) ||
157 ((dep_info.target.compare("VK_VERSION_1_3") == 0) && (version >= VK_API_VERSION_1_3))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700158 skip |=
159 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
160 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600161 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700162 if (dep_info.target.length() == 0) {
163 skip |= LogWarning(instance, vuid,
164 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
165 "without replacement.",
166 api_name, extension_name);
167 } else {
168 skip |= LogWarning(instance, vuid,
169 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
170 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
171 }
172 }
173 }
174 return skip;
175}
176
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200177bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
178{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700179 bool skip = false;
180 auto dep_info_it = special_use_extensions.find(extension_name);
181
182 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200183 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
184 "and it is strongly recommended that it be otherwise avoided.";
185 auto& special_uses = dep_info_it->second;
sfricke-samsungef15e482022-01-26 11:32:49 -0800186
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700187 if (special_uses.find("cadsupport") != std::string::npos) {
sfricke-samsungef15e482022-01-26 11:32:49 -0800188 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
189 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700190 }
191 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200192 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
193 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700194 }
195 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200196 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
197 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700198 }
199 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200200 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
201 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700202 }
203 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200204 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700205 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200206 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700207 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700208 }
209 return skip;
210}
211
Camden5b184be2019-08-13 07:50:19 -0600212bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500213 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600214 bool skip = false;
215
216 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
217 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800218 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700219 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
220 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600221 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600222 uint32_t specified_version =
223 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
224 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700225 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200226 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600227 }
228
229 return skip;
230}
231
Camden5b184be2019-08-13 07:50:19 -0600232bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500233 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600234 bool skip = false;
235
236 // get API version of physical device passed when creating device.
237 VkPhysicalDeviceProperties physical_device_properties{};
238 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500239 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600240
241 // check api versions and warn if instance api Version is higher than version on device.
Jeremy Gebben404f6ac2021-10-28 12:33:28 -0600242 if (api_version > device_api_version) {
243 std::string inst_api_name = StringAPIVersion(api_version);
Mark Lobodzinski60880782020-08-11 08:02:07 -0600244 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600245
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700246 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
247 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
248 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600249 }
250
Rodrigo Locattic2d5cf42022-03-01 18:05:26 -0300251 std::vector<std::string> extensions;
252 {
253 uint32_t property_count = 0;
254 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, nullptr) == VK_SUCCESS) {
255 std::vector<VkExtensionProperties> property_list(property_count);
256 if (DispatchEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &property_count, property_list.data()) == VK_SUCCESS) {
257 extensions.reserve(property_list.size());
258 for (const VkExtensionProperties& properties : property_list) {
259 extensions.push_back(properties.extensionName);
260 }
261 }
262 }
263 }
264
Camden5b184be2019-08-13 07:50:19 -0600265 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300266 const char *extension_name = pCreateInfo->ppEnabledExtensionNames[i];
267
paul-lunargd8c78082022-08-31 20:00:02 +0200268 uint32_t extension_api_version = std::min(api_version, device_api_version);
paul-lunarg4e0e1df2022-08-31 18:46:21 +0200269
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300270 if (white_list(extension_name, kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800271 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700272 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300273 extension_name);
paul-lunarg4e0e1df2022-08-31 18:46:21 +0200274 extension_api_version = api_version;
Camden5b184be2019-08-13 07:50:19 -0600275 }
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300276
paul-lunarg4e0e1df2022-08-31 18:46:21 +0200277 skip |= ValidateDeprecatedExtensions("CreateDevice", extension_name, extension_api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700278 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300279 skip |= ValidateSpecialUseExtensions("CreateDevice", extension_name, kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600280 }
281
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700282 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600283 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700284 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
285 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600286 }
287
LawG43f848c72022-02-23 09:35:21 +0000288 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
289 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100290 skip |= LogPerformanceWarning(
291 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000292 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100293 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
294 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
295 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000296 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100297 }
298
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300299 const bool enabled_pageable_device_local_memory = IsExtEnabled(device_extensions.vk_ext_pageable_device_local_memory);
300 if (VendorCheckEnabled(kBPVendorNVIDIA) && !enabled_pageable_device_local_memory &&
301 std::find(extensions.begin(), extensions.end(), VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) != extensions.end()) {
302 skip |= LogPerformanceWarning(
303 device, kVUID_BestPractices_CreateDevice_PageableDeviceLocalMemory,
304 "%s vkCreateDevice() called without pageable device local memory. "
305 "Use pageableDeviceLocalMemory from VK_EXT_pageable_device_local_memory when it is available.",
306 VendorSpecificTag(kBPVendorNVIDIA));
307 }
308
Camden5b184be2019-08-13 07:50:19 -0600309 return skip;
310}
311
312bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500313 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600314 bool skip = false;
315
316 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700317 std::stringstream buffer_hex;
318 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600319
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700320 skip |= LogWarning(
321 device, kVUID_BestPractices_SharingModeExclusive,
322 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
323 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700324 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600325 }
326
327 return skip;
328}
329
330bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500331 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600332 bool skip = false;
333
334 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700335 std::stringstream image_hex;
336 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600337
338 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700339 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
340 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
341 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700342 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600343 }
344
ziga-lunarg6df3d102022-03-18 17:02:14 +0100345 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
346 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
347 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
348 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
349 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
350 }
351
LawG4655f59c2022-02-23 13:55:55 +0000352 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000353 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
354 skip |= LogPerformanceWarning(
355 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000356 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000357 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
358 "and do not need to be backed by physical storage. "
359 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000360 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000361 }
362 }
363
LawG4ba113892022-02-23 14:39:02 +0000364 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
365 skip |= LogPerformanceWarning(
366 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
367 "%s vkCreateImage(): Trying to create an image with %u samples. "
368 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
369 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
370 }
371
372 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
373 skip |= LogPerformanceWarning(
374 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
375 "%s vkCreateImage(): Trying to create an image with %u samples. "
376 "The device may not have full support for true multisampling for images with more than %u samples. "
377 "XT devices support up to 8 samples, XE up to 4 samples.",
378 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
379 }
380
LawG4db16f802022-03-21 17:33:39 +0000381 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
382 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
383 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
384 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
385 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
386 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
387 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
388 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
389 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
390 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
391 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
392 VendorSpecificTag(kBPVendorIMG));
393 }
394
Nadav Gevaf0808442021-05-21 13:51:25 -0400395 if (VendorCheckEnabled(kBPVendorAMD)) {
396 std::stringstream image_hex;
397 image_hex << "0x" << std::hex << HandleToUint64(pImage);
398
399 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
400 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
401 skip |= LogPerformanceWarning(device,
402 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
403 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
404 "Using a SHARING_MODE_CONCURRENT "
405 "is not recommended with color and depth targets",
406 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
407 }
408
409 if ((pCreateInfo->usage &
410 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
411 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
412 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
413 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
414 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
415 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
416 }
417
418 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
419 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
420 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
421 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
422 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
423 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
424 }
425 }
426
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300427 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
428 std::stringstream image_hex;
429 image_hex << "0x" << std::hex << HandleToUint64(pImage);
430
431 if (pCreateInfo->tiling == VK_IMAGE_TILING_LINEAR) {
432 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateImage_TilingLinear,
433 "%s Performance warning: image (%s) is created with tiling VK_IMAGE_TILING_LINEAR. "
434 "Use VK_IMAGE_TILING_OPTIMAL instead.",
435 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
436 }
Rodrigo Locatti3290c2b2022-03-09 18:25:56 -0300437
438 if (pCreateInfo->format == VK_FORMAT_D32_SFLOAT || pCreateInfo->format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
439 skip |= LogPerformanceWarning(
440 device, kVUID_BestPractices_CreateImage_Depth32Format,
441 "%s Performance warning: image (%s) is created with a 32-bit depth format. Use VK_FORMAT_D24_UNORM_S8_UINT or "
442 "VK_FORMAT_D16_UNORM instead, unless the extra precision is needed.",
443 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
444 }
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300445 }
446
Camden5b184be2019-08-13 07:50:19 -0600447 return skip;
448}
449
450bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500451 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600452 bool skip = false;
453
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600454 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600455 if (bp_pd_state) {
456 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
457 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
458 "vkCreateSwapchainKHR() called before getting surface capabilities from "
459 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
460 }
Camden83a9c372019-08-14 11:41:38 -0600461
Shannon McPherson73e58c82021-03-05 17:14:26 -0700462 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
463 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600464 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
465 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
466 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
467 }
Camden83a9c372019-08-14 11:41:38 -0600468
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600469 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
470 skip |= LogWarning(
471 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
472 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
473 }
Camden83a9c372019-08-14 11:41:38 -0600474 }
475
Camden5b184be2019-08-13 07:50:19 -0600476 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700477 skip |=
478 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600479 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700480 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
481 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600482 }
483
ziga-lunarg79beba62022-03-30 01:17:30 +0200484 const auto present_mode = pCreateInfo->presentMode;
485 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
486 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100487 skip |= LogPerformanceWarning(
488 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
489 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
490 ", which means double buffering is going "
491 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
492 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
493 "3 to use triple buffering to maximize performance in such cases.",
494 pCreateInfo->minImageCount);
495 }
496
Szilard Pappd5f0f812020-06-22 09:01:29 +0100497 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
498 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
499 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
500 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
501 "Presentation modes which are not FIFO will present the latest available frame and discard other "
502 "frame(s) if any.",
503 VendorSpecificTag(kBPVendorArm));
504 }
505
Camden5b184be2019-08-13 07:50:19 -0600506 return skip;
507}
508
509bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
510 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500511 const VkAllocationCallbacks* pAllocator,
512 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600513 bool skip = false;
514
515 for (uint32_t i = 0; i < swapchainCount; i++) {
516 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700517 skip |= LogWarning(
518 device, kVUID_BestPractices_SharingModeExclusive,
519 "Warning: A shared swapchain (index %" PRIu32
520 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
521 "queues (queueFamilyIndexCount of %" PRIu32 ").",
522 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600523 }
524 }
525
526 return skip;
527}
528
529bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500530 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600531 bool skip = false;
532
533 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
534 VkFormat format = pCreateInfo->pAttachments[i].format;
535 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
536 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
537 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700538 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
539 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
540 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
541 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
542 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600543 }
544 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700545 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
546 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
547 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
548 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
549 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600550 }
551 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000552
553 const auto& attachment = pCreateInfo->pAttachments[i];
554 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
555 bool access_requires_memory =
556 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
557
558 if (FormatHasStencil(format)) {
559 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
560 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
561 }
562
563 if (access_requires_memory) {
564 skip |= LogPerformanceWarning(
565 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
566 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
567 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
568 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
569 i, static_cast<uint32_t>(attachment.samples));
570 }
571 }
Camden5b184be2019-08-13 07:50:19 -0600572 }
573
574 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
575 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
576 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
577 }
578
579 return skip;
580}
581
Tony-LunarG767180f2020-04-23 14:03:59 -0600582bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
583 const VkImageView* image_views) const {
584 bool skip = false;
585
586 // Check for non-transient attachments that should be transient and vice versa
587 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200588 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600589 bool attachment_should_be_transient =
590 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
591
592 if (FormatHasStencil(attachment.format)) {
593 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
594 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
595 }
596
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600597 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600598 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600599 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600600
601 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
602
603 // The check for an image that should not be transient applies to all GPUs
604 if (!attachment_should_be_transient && image_is_transient) {
605 skip |= LogPerformanceWarning(
606 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
607 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
608 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
609 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
610 i);
611 }
612
613 bool supports_lazy = false;
614 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
615 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
616 supports_lazy = true;
617 }
618 }
619
620 // The check for an image that should be transient only applies to GPUs supporting
621 // lazily allocated memory
622 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
623 skip |= LogPerformanceWarning(
624 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
625 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
626 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
627 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
628 i);
629 }
630 }
631 }
632 return skip;
633}
634
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000635bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
636 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
637 bool skip = false;
638
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600639 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800640 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600641 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000642 }
643
644 return skip;
645}
646
Sam Wallse746d522020-03-16 21:20:23 +0000647bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
648 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
649 bool skip = false;
650 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
651
652 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700653 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000654 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
655 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700656 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000657 skip |= LogPerformanceWarning(
658 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
659 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
660 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
661 VendorSpecificTag(kBPVendorArm));
662 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200663
664 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
665 // Track number of descriptorSets allowable in this pool
666 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
667 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
668 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
669 ". This pool only has %" PRIu32 " descriptorSets remaining.",
670 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
671 pool_state->GetAvailableSets());
672 }
673 }
Sam Wallse746d522020-03-16 21:20:23 +0000674 }
675
676 return skip;
677}
678
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600679void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
680 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000681 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700682 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
683 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000684 // we record successful allocations by subtracting the allocation count from the last recorded free count
685 const auto alloc_count = pAllocateInfo->descriptorSetCount;
686 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700687 if (pool_state->freed_count > alloc_count) {
688 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700689 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700690 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700691 }
Sam Wallse746d522020-03-16 21:20:23 +0000692 }
693 }
694}
695
696void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
697 const VkDescriptorSet* pDescriptorSets, VkResult result) {
698 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
699 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700700 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000701 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700702 if (pool_state) {
703 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000704 }
705 }
706}
707
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300708void BestPractices::PreCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
709 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) {
710 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
711 WriteLockGuard guard{memory_free_events_lock_};
712
713 // Release old allocations to avoid overpopulating the container
714 const auto now = std::chrono::high_resolution_clock::now();
715 const auto last_old = std::find_if(memory_free_events_.rbegin(), memory_free_events_.rend(), [now](const MemoryFreeEvent& event) {
716 return now - event.time > kAllocateMemoryReuseTimeThresholdNVIDIA;
717 });
718 memory_free_events_.erase(memory_free_events_.begin(), last_old.base());
719 }
720}
721
Camden5b184be2019-08-13 07:50:19 -0600722bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500723 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600724 bool skip = false;
725
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700726 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700727 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
728 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600729 }
730
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000731 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
732 skip |= LogPerformanceWarning(
733 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600734 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
735 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000736 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
737 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
738 }
739
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300740 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
741 if (!device_extensions.vk_ext_pageable_device_local_memory &&
742 !LvlFindInChain<VkMemoryPriorityAllocateInfoEXT>(pAllocateInfo->pNext)) {
743 skip |= LogPerformanceWarning(
744 device, kVUID_BestPractices_AllocateMemory_SetPriority,
745 "%s Use VkMemoryPriorityAllocateInfoEXT to provide the operating system information on the allocations that "
746 "should stay in video memory and which should be demoted first when video memory is limited. "
747 "The highest priority should be given to GPU-written resources like color attachments, depth attachments, "
748 "storage images, and buffers written from the GPU.",
749 VendorSpecificTag(kBPVendorNVIDIA));
750 }
751
752 {
753 // Size in bytes for an allocation to be considered "compatible"
754 static constexpr VkDeviceSize size_threshold = VkDeviceSize{1} << 20;
755
756 ReadLockGuard guard{memory_free_events_lock_};
757
758 const auto now = std::chrono::high_resolution_clock::now();
759 const VkDeviceSize alloc_size = pAllocateInfo->allocationSize;
760 const uint32_t memory_type_index = pAllocateInfo->memoryTypeIndex;
761 const auto latest_event = std::find_if(memory_free_events_.rbegin(), memory_free_events_.rend(), [&](const MemoryFreeEvent& event) {
762 return (memory_type_index == event.memory_type_index) && (alloc_size <= event.allocation_size) &&
763 (alloc_size - event.allocation_size <= size_threshold) && (now - event.time < kAllocateMemoryReuseTimeThresholdNVIDIA);
764 });
765
766 if (latest_event != memory_free_events_.rend()) {
767 const auto time_delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - latest_event->time);
768 if (time_delta < std::chrono::milliseconds{5}) {
769 skip |=
770 LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_ReuseAllocations,
771 "%s Reuse memory allocations instead of releasing and reallocating. A memory allocation "
772 "has just been released, and it could have been reused in place of this allocation.",
773 VendorSpecificTag(kBPVendorNVIDIA));
774 } else {
775 const uint32_t seconds = static_cast<uint32_t>(time_delta.count() / 1000);
776 const uint32_t milliseconds = static_cast<uint32_t>(time_delta.count() % 1000);
777
778 skip |= LogPerformanceWarning(
779 device, kVUID_BestPractices_AllocateMemory_ReuseAllocations,
780 "%s Reuse memory allocations instead of releasing and reallocating. A memory allocation has been released "
781 "%" PRIu32 ".%03" PRIu32 " seconds ago, and it could have been reused in place of this allocation.",
782 VendorSpecificTag(kBPVendorNVIDIA), seconds, milliseconds);
783 }
784 }
785 }
Rodrigo Locattie4f8d522022-03-15 16:30:49 -0300786 }
787
Camden83a9c372019-08-14 11:41:38 -0600788 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
789
790 return skip;
791}
792
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600793void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
794 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
795 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700796 if (result != VK_SUCCESS) {
797 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
798 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800799 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700800 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600801 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700802 return;
803 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700804}
Camden Stocker9738af92019-10-16 13:54:03 -0700805
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600806void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
807 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700808 auto error = std::find(error_codes.begin(), error_codes.end(), result);
809 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000810 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
811 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
812
813 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
814 if (common_failure != common_failure_codes.end()) {
815 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
816 } else {
817 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
818 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700819 return;
820 }
821 auto success = std::find(success_codes.begin(), success_codes.end(), result);
822 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600823 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
824 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500825 }
826}
827
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300828void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
829 if (memory != VK_NULL_HANDLE && VendorCheckEnabled(kBPVendorNVIDIA)) {
830 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
831
832 // Exclude memory free events on dedicated allocations, or imported/exported allocations.
833 if (!mem_info->IsDedicatedBuffer() && !mem_info->IsDedicatedImage() && !mem_info->IsExport() && !mem_info->IsImport()) {
834 MemoryFreeEvent event;
835 event.time = std::chrono::high_resolution_clock::now();
836 event.memory_type_index = mem_info->alloc_info.memoryTypeIndex;
837 event.allocation_size = mem_info->alloc_info.allocationSize;
838
839 WriteLockGuard guard{memory_free_events_lock_};
840 memory_free_events_.push_back(event);
841 }
842 }
843
844 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
845}
846
Jeff Bolz5c801d12019-10-09 10:38:45 -0500847bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
848 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700849 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600850 bool skip = false;
851
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700852 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600853
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700854 for (const auto& item : mem_info->ObjectBindings()) {
855 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600856 LogObjectList objlist(device);
857 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600858 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600859 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 -0600860 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600861 }
862
Camden5b184be2019-08-13 07:50:19 -0600863 return skip;
864}
865
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000866bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600867 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700868 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600869
sfricke-samsunge2441192019-11-06 14:07:57 -0800870 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700871 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
872 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
873 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600874 }
875
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700876 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000877
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300878 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000879 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
880 skip |= LogPerformanceWarning(
881 device, kVUID_BestPractices_SmallDedicatedAllocation,
882 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600883 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
884 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000885 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
886 }
887
Rodrigo Locatti66b23352022-03-15 17:28:32 -0300888 skip |= ValidateBindMemory(device, memory);
889
Camden Stockerb603cc82019-09-03 10:09:02 -0600890 return skip;
891}
892
893bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500894 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600895 bool skip = false;
896 const char* api_name = "BindBufferMemory()";
897
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000898 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600899
900 return skip;
901}
902
903bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500904 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600905 char api_name[64];
906 bool skip = false;
907
908 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200909 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000910 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600911 }
912
913 return skip;
914}
Camden Stockerb603cc82019-09-03 10:09:02 -0600915
916bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500917 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600918 char api_name[64];
919 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600920
Camden Stocker8b798ab2019-09-03 10:33:28 -0600921 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200922 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000923 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600924 }
925
926 return skip;
927}
928
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000929bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600930 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700931 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600932
sfricke-samsung71bc6572020-04-29 15:49:43 -0700933 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600934 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700935 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
936 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
937 api_name, report_data->FormatHandle(image).c_str());
938 }
939 } else {
940 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
941 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600942 }
943
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700944 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000945
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600946 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000947 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
948 skip |= LogPerformanceWarning(
949 device, kVUID_BestPractices_SmallDedicatedAllocation,
950 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600951 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
952 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000953 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
954 }
955
956 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
957 // make sure this type is actually used.
958 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
959 // (i.e.most tile - based renderers)
960 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
961 bool supports_lazy = false;
962 uint32_t suggested_type = 0;
963
964 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600965 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000966 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
967 supports_lazy = true;
968 suggested_type = i;
969 break;
970 }
971 }
972 }
973
974 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
975
976 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
977 skip |= LogPerformanceWarning(
978 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600979 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000980 "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 -0600981 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600982 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000983 }
984 }
985
Rodrigo Locatti66b23352022-03-15 17:28:32 -0300986 skip |= ValidateBindMemory(device, memory);
987
Camden Stocker8b798ab2019-09-03 10:33:28 -0600988 return skip;
989}
990
991bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500992 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600993 bool skip = false;
994 const char* api_name = "vkBindImageMemory()";
995
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000996 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600997
998 return skip;
999}
1000
1001bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001002 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -06001003 char api_name[64];
1004 bool skip = false;
1005
1006 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +02001007 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001008 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -06001009 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
1010 }
Camden Stocker8b798ab2019-09-03 10:33:28 -06001011 }
1012
1013 return skip;
1014}
1015
1016bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001017 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -06001018 char api_name[64];
1019 bool skip = false;
1020
1021 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +02001022 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +00001023 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -06001024 }
1025
1026 return skip;
1027}
Camden83a9c372019-08-14 11:41:38 -06001028
Rodrigo Locatti66b23352022-03-15 17:28:32 -03001029void BestPractices::PreCallRecordSetDeviceMemoryPriorityEXT(VkDevice device, VkDeviceMemory memory, float priority) {
1030 auto mem_info = std::static_pointer_cast<bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
1031 mem_info->dynamic_priority.emplace(priority);
1032}
1033
Attilio Provenzano02859b22020-02-27 14:17:28 +00001034static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
1035 switch (format) {
1036 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
1037 case VK_FORMAT_R16_SFLOAT:
1038 case VK_FORMAT_R16G16_SFLOAT:
1039 case VK_FORMAT_R16G16B16_SFLOAT:
1040 case VK_FORMAT_R16G16B16A16_SFLOAT:
1041 case VK_FORMAT_R32_SFLOAT:
1042 case VK_FORMAT_R32G32_SFLOAT:
1043 case VK_FORMAT_R32G32B32_SFLOAT:
1044 case VK_FORMAT_R32G32B32A32_SFLOAT:
1045 return false;
1046
1047 default:
1048 return true;
1049 }
1050}
1051
1052bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
1053 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
1054 bool skip = false;
1055
1056 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001057 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001058
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001059 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
1060 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
1061 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001062 return skip;
1063 }
1064
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001065 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001066 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001067
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001068 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1069 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
1070
1071 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001072 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001073 uint32_t att = subpass.pColorAttachments[j].attachment;
1074
1075 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
1076 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
1077 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
1078 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
1079 "color attachment #%u makes use "
1080 "of a format which cannot be blended at full throughput when using MSAA.",
1081 VendorSpecificTag(kBPVendorArm), i, j);
1082 }
1083 }
1084 }
1085 }
1086
1087 return skip;
1088}
1089
Nadav Gevaf0808442021-05-21 13:51:25 -04001090void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1091 const VkComputePipelineCreateInfo* pCreateInfos,
1092 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1093 VkResult result, void* pipe_state) {
1094 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001095 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -04001096}
1097
Camden5b184be2019-08-13 07:50:19 -06001098bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1099 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001100 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001101 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001102 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1103 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +01001104 if (skip) {
1105 return skip;
1106 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001107 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001108
1109 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001110 skip |= LogPerformanceWarning(
1111 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1112 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
1113 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001114 }
1115
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001116 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001117 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001118
Tony-LunarGb6a2daf2022-07-29 11:30:55 -06001119 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 +02001120 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001121 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001122 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
1123 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001124 count++;
1125 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001126 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001127 if (count > kMaxInstancedVertexBuffers) {
1128 skip |= LogPerformanceWarning(
1129 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
1130 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
1131 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
1132 count, kMaxInstancedVertexBuffers);
1133 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001134 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001135
Szilard Pappaaf2da32020-06-22 10:37:35 +01001136 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1137 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001138 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1139 VendorCheckEnabled(kBPVendorArm)) {
1140 skip |= LogPerformanceWarning(
1141 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1142 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1143 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1144 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1145 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1146 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001147 }
1148
Attilio Provenzano02859b22020-02-27 14:17:28 +00001149 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001150 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001151 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001152 auto prev_pipeline = pipeline_cache_.load();
1153 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001154 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001155 "%s %s Performance Warning: A second pipeline cache is in use. "
1156 "Consider using only one pipeline cache to improve cache hit rate.",
1157 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04001158 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001159 }
1160 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001161 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001162 skip |=
1163 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1164 "%s Performance warning: Too many pipelines created, consider consolidation",
1165 VendorSpecificTag(kBPVendorAMD));
1166 }
1167
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001168 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001169 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1170 "%s Performance warning: Use of primitive restart is not recommended",
1171 VendorSpecificTag(kBPVendorAMD));
1172 }
1173
1174 // TODO: this might be too aggressive of a check
1175 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1176 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1177 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1178 VendorSpecificTag(kBPVendorAMD));
1179 }
1180 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001181
Camden5b184be2019-08-13 07:50:19 -06001182 return skip;
1183}
1184
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001185static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1186 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1187 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001188 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001189 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001190 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001191
1192 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1193
1194 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1195 // are only non-null if they are enabled.
1196 if (create_info.pColorBlendState) {
1197 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1198 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1199 for (uint32_t j = 0; j < num_color_attachments; j++) {
1200 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1201 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1202 if (attachment != VK_ATTACHMENT_UNUSED) {
1203 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1204 }
1205 }
1206 }
1207 }
1208
1209 if (create_info.pDepthStencilState &&
1210 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1211 create_info.pDepthStencilState->stencilTestEnable)) {
1212 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1213 if (attachment != VK_ATTACHMENT_UNUSED) {
1214 VkImageAspectFlags aspects = 0;
1215 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1216 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1217 }
1218 if (create_info.pDepthStencilState->stencilTestEnable) {
1219 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1220 }
1221 result.push_back({attachment, aspects});
1222 }
1223 }
1224 return result;
1225}
1226
1227bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1228 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1229 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1230 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1231 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1232
1233std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1234 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1235 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1236 return std::static_pointer_cast<PIPELINE_STATE>(
1237 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001238}
1239
Sam Walls0961ec02020-03-31 16:39:15 +01001240void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1241 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1242 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1243 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001244 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001245 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001246}
1247
Camden5b184be2019-08-13 07:50:19 -06001248bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1249 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001250 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001251 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001252 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1253 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001254
1255 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001256 skip |= LogPerformanceWarning(
1257 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1258 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1259 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001260 }
1261
Nadav Gevaf0808442021-05-21 13:51:25 -04001262 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001263 auto prev_pipeline = pipeline_cache_.load();
1264 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1265 skip |= LogPerformanceWarning(
1266 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1267 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001268 "improve cache hit rate",
1269 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001270 }
1271 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001272
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001273 for (uint32_t i = 0; i < createInfoCount; i++) {
1274 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1275 if (VendorCheckEnabled(kBPVendorArm)) {
1276 skip |= ValidateCreateComputePipelineArm(createInfo);
1277 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001278
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001279 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1280 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1281 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1282 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1283 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1284 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1285 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1286 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1287 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001288 }
1289 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001290 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001291 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001292
1293 return skip;
1294}
1295
1296bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1297 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001298 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001299 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001300 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1301 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001302
1303 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001304 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001305
1306 uint32_t thread_count = x * y * z;
1307
1308 // Generate a priori warnings about work group sizes.
1309 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1310 skip |= LogPerformanceWarning(
1311 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1312 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1313 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1314 "groups with less than %u threads, especially when using barrier() or shared memory.",
1315 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1316 }
1317
1318 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1319 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1320 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1321 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1322 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1323 "%u, %u) is not aligned to %u "
1324 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1325 "leave threads idle on the shader "
1326 "core.",
1327 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1328 kThreadGroupDispatchCountAlignmentArm);
1329 }
1330
sfricke-samsungef15e482022-01-26 11:32:49 -08001331 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1332 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001333
1334 unsigned dimensions = 0;
1335 if (x > 1) dimensions++;
1336 if (y > 1) dimensions++;
1337 if (z > 1) dimensions++;
1338 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1339 dimensions = std::max(dimensions, 1u);
1340
1341 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1342 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1343 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1344 bool accesses_2d = false;
1345 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001346 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001347 if (dim < 0) continue;
1348 auto spvdim = spv::Dim(dim);
1349 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1350 }
1351
1352 if (accesses_2d && dimensions < 2) {
1353 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1354 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1355 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1356 "exhibiting poor spatial locality with respect to one or more shader resources.",
1357 VendorSpecificTag(kBPVendorArm), x, y, z);
1358 }
1359
Camden5b184be2019-08-13 07:50:19 -06001360 return skip;
1361}
1362
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001363bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001364 bool skip = false;
1365
1366 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001367 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1368 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001369 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001370 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1371 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001372 }
1373
1374 return skip;
1375}
1376
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001377bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1378 bool skip = false;
1379
1380 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1381 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1382 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1383 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1384 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1385 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1386 }
1387
1388 return skip;
1389}
1390
1391bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1392 bool skip = false;
1393 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1394
1395 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1396 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1397
1398 return skip;
1399}
1400
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001401void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001402 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1403 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1404 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1405 LogPerformanceWarning(
1406 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1407 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1408 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1409 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1410 "convenient opportunity.",
1411 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1412 }
1413 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001414
1415 // AMD best practice
1416 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001417 num_queue_submissions_ = 0;
1418 num_barriers_objects_ = 0;
1419 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001420}
1421
Jeff Bolz5c801d12019-10-09 10:38:45 -05001422bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1423 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001424 bool skip = false;
1425
1426 for (uint32_t submit = 0; submit < submitCount; submit++) {
1427 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1428 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1429 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001430 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1431 skip |=
1432 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1433 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1434 submit, submit);
1435 }
1436 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1437 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1438 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1439 submit, submit);
1440 }
Camden5b184be2019-08-13 07:50:19 -06001441 }
1442
1443 return skip;
1444}
1445
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001446bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1447 VkFence fence) const {
1448 bool skip = false;
1449
1450 for (uint32_t submit = 0; submit < submitCount; submit++) {
1451 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1452 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1453 }
1454 }
1455
1456 return skip;
1457}
1458
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001459bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1460 VkFence fence) const {
1461 bool skip = false;
1462
1463 for (uint32_t submit = 0; submit < submitCount; submit++) {
1464 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1465 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1466 }
1467 }
1468
1469 return skip;
1470}
1471
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001472bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1473 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1474 bool skip = false;
1475
1476 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1477 skip |= LogPerformanceWarning(
1478 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1479 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1480 "pool instead.");
1481 }
1482
1483 return skip;
1484}
1485
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001486void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer,
1487 const VkCommandBufferBeginInfo* pBeginInfo) {
1488 StateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1489
1490 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
paul-lunarg093c1762022-08-23 18:52:10 +02001491 if (!cb) return;
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001492
1493 cb->num_submits = 0;
1494 cb->is_one_time_submit = (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) != 0;
1495}
1496
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001497bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1498 const VkCommandBufferBeginInfo* pBeginInfo) const {
1499 bool skip = false;
1500
1501 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1502 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1503 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1504 }
1505
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001506 if (VendorCheckEnabled(kBPVendorArm)) {
Rodrigo Locattife5172b2022-03-22 18:49:29 -03001507 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1508 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001509 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1510 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1511 VendorSpecificTag(kBPVendorArm));
1512 }
1513 }
1514 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1515 auto cb = GetRead<bp_state::CommandBuffer>(commandBuffer);
1516 if (cb->num_submits == 1 && !cb->is_one_time_submit) {
1517 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1518 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT was not set "
1519 "and the command buffer has only been submitted once. "
1520 "For best performance on NVIDIA GPUs, use ONE_TIME_SUBMIT.",
1521 VendorSpecificTag(kBPVendorNVIDIA));
Rodrigo Locattife5172b2022-03-22 18:49:29 -03001522 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001523 }
1524
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001525 return skip;
1526}
1527
Jeff Bolz5c801d12019-10-09 10:38:45 -05001528bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001529 bool skip = false;
1530
1531 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1532
1533 return skip;
1534}
1535
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001536bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1537 const VkDependencyInfoKHR* pDependencyInfo) const {
1538 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1539}
1540
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001541bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1542 const VkDependencyInfo* pDependencyInfo) const {
1543 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1544}
1545
Jeff Bolz5c801d12019-10-09 10:38:45 -05001546bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1547 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001548 bool skip = false;
1549
1550 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1551
1552 return skip;
1553}
1554
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001555bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1556 VkPipelineStageFlags2KHR stageMask) const {
1557 bool skip = false;
1558
1559 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1560
1561 return skip;
1562}
1563
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001564bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1565 VkPipelineStageFlags2 stageMask) const {
1566 bool skip = false;
1567
1568 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1569
1570 return skip;
1571}
1572
Camden5b184be2019-08-13 07:50:19 -06001573bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1574 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1575 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1576 uint32_t bufferMemoryBarrierCount,
1577 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1578 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001579 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001580 bool skip = false;
1581
1582 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1583 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1584
1585 return skip;
1586}
1587
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001588bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1589 const VkDependencyInfoKHR* pDependencyInfos) const {
1590 bool skip = false;
1591 for (uint32_t i = 0; i < eventCount; i++) {
1592 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1593 }
1594
1595 return skip;
1596}
1597
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001598bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1599 const VkDependencyInfo* pDependencyInfos) const {
1600 bool skip = false;
1601 for (uint32_t i = 0; i < eventCount; i++) {
1602 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1603 }
1604
1605 return skip;
1606}
1607
Camden5b184be2019-08-13 07:50:19 -06001608bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1609 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1610 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1611 uint32_t bufferMemoryBarrierCount,
1612 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1613 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001614 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001615 bool skip = false;
1616
1617 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1618 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1619
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001620 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1621 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1622 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1623 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1624 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1625 "may be discarded, but the newLayout is %s, which is read only.",
1626 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1627 }
1628 }
1629
Nadav Gevaf0808442021-05-21 13:51:25 -04001630 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001631 auto num = num_barriers_objects_.load();
1632 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001633 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001634 "%s Performance warning: In this frame, %" PRIu32
1635 " barriers were already submitted. Barriers have a high cost and can "
1636 "stall the GPU. "
1637 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1638 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001639 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001640 }
1641 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
1642 static constexpr std::array<VkImageLayout, 3> read_layouts = {
Nadav Gevaf0808442021-05-21 13:51:25 -04001643 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1644 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1645 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1646 };
1647
1648 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1649 // read to read barriers
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001650 const auto &image_barrier = pImageMemoryBarriers[i];
1651 bool old_is_read_layout = std::find(read_layouts.begin(), read_layouts.end(), image_barrier.oldLayout) != read_layouts.end();
1652 bool new_is_read_layout = std::find(read_layouts.begin(), read_layouts.end(), image_barrier.newLayout) != read_layouts.end();
1653
Nadav Gevaf0808442021-05-21 13:51:25 -04001654 if (old_is_read_layout && new_is_read_layout) {
1655 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001656 "%s %s Performance warning: Don't issue read-to-read barriers. "
1657 "Get the resource in the right state the first time you use it.",
1658 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04001659 }
1660
1661 // general with no storage
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001662 if (VendorCheckEnabled(kBPVendorAMD) && image_barrier.newLayout == VK_IMAGE_LAYOUT_GENERAL) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001663 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1664 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1665 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1666 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1667 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1668 VendorSpecificTag(kBPVendorAMD));
1669 }
1670 }
1671 }
1672 }
1673
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001674 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1675 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
1676 }
1677
Camden5b184be2019-08-13 07:50:19 -06001678 return skip;
1679}
1680
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001681bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1682 const VkDependencyInfoKHR* pDependencyInfo) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001683 bool skip = false;
1684
1685 skip |= CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1686
1687 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
1688 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
1689 }
1690
1691 return skip;
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001692}
1693
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001694bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1695 const VkDependencyInfo* pDependencyInfo) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001696 bool skip = false;
1697
1698 skip |= CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1699
1700 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
1701 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
1702 }
1703
1704 return skip;
1705}
1706
1707template <typename ImageMemoryBarrier>
1708bool BestPractices::ValidateCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer,
1709 const ImageMemoryBarrier& barrier) const {
1710
1711 bool skip = false;
1712
Mark Young0a6b48f2022-08-18 11:17:02 -06001713 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
1714 assert(cmd_state);
1715
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001716 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1717 if (barrier.oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && barrier.newLayout != VK_IMAGE_LAYOUT_UNDEFINED) {
Mark Young0a6b48f2022-08-18 11:17:02 -06001718 skip |= ValidateZcull(*cmd_state, barrier.image, barrier.subresourceRange);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001719 }
1720 }
1721
1722 return skip;
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001723}
1724
Camden5b184be2019-08-13 07:50:19 -06001725bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001726 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001727 bool skip = false;
1728
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001729 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1730
1731 return skip;
1732}
1733
1734bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1735 VkQueryPool queryPool, uint32_t query) const {
1736 bool skip = false;
1737
1738 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001739
1740 return skip;
1741}
1742
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001743bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1744 VkQueryPool queryPool, uint32_t query) const {
1745 bool skip = false;
1746
1747 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1748
1749 return skip;
1750}
1751
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001752void BestPractices::PreCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1753 VkPipeline pipeline) {
1754 StateTracker::PreCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1755
1756 auto pipeline_info = Get<PIPELINE_STATE>(pipeline);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001757 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001758
1759 assert(pipeline_info);
1760 assert(cb);
1761
1762 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS && VendorCheckEnabled(kBPVendorNVIDIA)) {
1763 using TessGeometryMeshState = bp_state::CommandBufferStateNV::TessGeometryMesh::State;
1764 auto& tgm = cb->nv.tess_geometry_mesh;
1765
1766 // Make sure the message is only signaled once per command buffer
1767 tgm.threshold_signaled = tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA;
1768
1769 // Track pipeline switches with tessellation, geometry, and/or mesh shaders enabled, and disabled
1770 auto tgm_stages = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT |
1771 VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_TASK_BIT_NV | VK_SHADER_STAGE_MESH_BIT_NV;
1772 auto new_tgm_state = (pipeline_info->active_shaders & tgm_stages) != 0
1773 ? TessGeometryMeshState::Enabled
1774 : TessGeometryMeshState::Disabled;
1775 if (tgm.state != new_tgm_state && tgm.state != TessGeometryMeshState::Unknown) {
1776 tgm.num_switches++;
1777 }
1778 tgm.state = new_tgm_state;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001779
1780 // Track depthTestEnable and depthCompareOp
1781 auto &pipeline_create_info = pipeline_info->GetCreateInfo<VkGraphicsPipelineCreateInfo>();
1782 auto depth_stencil_state = pipeline_create_info.pDepthStencilState;
1783 auto dynamic_state = pipeline_create_info.pDynamicState;
1784 if (depth_stencil_state && dynamic_state) {
1785 auto dynamic_state_begin = dynamic_state->pDynamicStates;
1786 auto dynamic_state_end = dynamic_state->pDynamicStates + dynamic_state->dynamicStateCount;
1787
1788 bool dynamic_depth_test_enable = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE) != dynamic_state_end;
1789 bool dynamic_depth_func = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_COMPARE_OP) != dynamic_state_end;
1790
1791 if (!dynamic_depth_test_enable) {
1792 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depth_stencil_state->depthTestEnable != VK_FALSE);
1793 }
1794 if (!dynamic_depth_func) {
1795 RecordSetDepthTestState(*cb, depth_stencil_state->depthCompareOp, cb->nv.depth_test_enable);
1796 }
1797 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001798 }
1799}
1800
Sam Walls0961ec02020-03-31 16:39:15 +01001801void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1802 VkPipeline pipeline) {
1803 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1804
Nadav Gevaf0808442021-05-21 13:51:25 -04001805 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001806 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001807
Sam Walls0961ec02020-03-31 16:39:15 +01001808 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001809 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001810 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001811 if (pipeline_state) {
1812 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001813 assert(cb_node);
1814 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001815
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001816 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001817 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001818
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001819 const auto* blend_state = pipeline_state->ColorBlendState();
1820 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001821
1822 if (blend_state) {
1823 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001824 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001825 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1826 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001827 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001828 }
1829 }
1830 }
1831
1832 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001833 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001834
1835 if (stencil_state && stencil_state->depthTestEnable) {
1836 switch (stencil_state->depthCompareOp) {
1837 case VK_COMPARE_OP_EQUAL:
1838 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1839 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001840 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001841 break;
1842 default:
1843 break;
1844 }
1845 }
Sam Walls0961ec02020-03-31 16:39:15 +01001846 }
1847 }
1848}
1849
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001850void BestPractices::PreCallRecordCmdSetDepthCompareOp(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1851 StateTracker::PreCallRecordCmdSetDepthCompareOp(commandBuffer, depthCompareOp);
1852
1853 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1854 assert(cb);
1855
1856 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1857 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1858 }
1859}
1860
1861void BestPractices::PreCallRecordCmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1862 StateTracker::PreCallRecordCmdSetDepthCompareOpEXT(commandBuffer, depthCompareOp);
1863
1864 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1865 assert(cb);
1866
1867 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1868 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1869 }
1870}
1871
1872void BestPractices::PreCallRecordCmdSetDepthTestEnable(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1873 StateTracker::PreCallRecordCmdSetDepthTestEnable(commandBuffer, depthTestEnable);
1874
1875 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1876 assert(cb);
1877
1878 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1879 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1880 }
1881}
1882
1883void BestPractices::PreCallRecordCmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1884 StateTracker::PreCallRecordCmdSetDepthTestEnableEXT(commandBuffer, depthTestEnable);
1885
1886 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1887 assert(cb);
1888
1889 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1890 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1891 }
1892}
1893
1894void BestPractices::RecordSetDepthTestState(bp_state::CommandBuffer& cmd_state, VkCompareOp new_depth_compare_op, bool new_depth_test_enable) {
1895 assert(VendorCheckEnabled(kBPVendorNVIDIA));
1896
1897 if (cmd_state.nv.depth_compare_op != new_depth_compare_op) {
1898 switch (new_depth_compare_op) {
1899 case VK_COMPARE_OP_LESS:
1900 case VK_COMPARE_OP_LESS_OR_EQUAL:
1901 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Less;
1902 break;
1903 case VK_COMPARE_OP_GREATER:
1904 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1905 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Greater;
1906 break;
1907 default:
1908 // The other ops carry over the previous state.
1909 break;
1910 }
1911 }
1912 cmd_state.nv.depth_compare_op = new_depth_compare_op;
1913 cmd_state.nv.depth_test_enable = new_depth_test_enable;
1914}
1915
1916void BestPractices::RecordCmdBeginRenderingCommon(VkCommandBuffer commandBuffer) {
1917 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1918 assert(cmd_state);
1919
1920 auto rp = cmd_state->activeRenderPass.get();
1921 assert(rp);
1922
1923 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1924 std::shared_ptr<IMAGE_VIEW_STATE> depth_image_view_shared_ptr;
1925 IMAGE_VIEW_STATE* depth_image_view = nullptr;
1926 layer_data::optional<VkAttachmentLoadOp> load_op;
1927
1928 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1929 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1930 if (depth_attachment) {
1931 load_op.emplace(depth_attachment->loadOp);
1932 depth_image_view_shared_ptr = Get<IMAGE_VIEW_STATE>(depth_attachment->imageView);
1933 depth_image_view = depth_image_view_shared_ptr.get();
1934 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001935
1936 for (uint32_t i = 0; i < rp->dynamic_rendering_begin_rendering_info.colorAttachmentCount; ++i) {
1937 const auto& color_attachment = rp->dynamic_rendering_begin_rendering_info.pColorAttachments[i];
1938 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1939 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
1940 RecordClearColor(format, color_attachment.clearValue.color);
1941 }
1942 }
1943
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001944 } else {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001945 if (rp->createInfo.pAttachments) {
1946 if (rp->createInfo.subpassCount > 0) {
1947 const auto depth_attachment = rp->createInfo.pSubpasses[0].pDepthStencilAttachment;
1948 if (depth_attachment) {
1949 const uint32_t attachment_index = depth_attachment->attachment;
1950 if (attachment_index != VK_ATTACHMENT_UNUSED) {
1951 load_op.emplace(rp->createInfo.pAttachments[attachment_index].loadOp);
1952 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
1953 }
1954 }
1955 }
1956 for (uint32_t i = 0; i < cmd_state->activeRenderPassBeginInfo.clearValueCount; ++i) {
1957 const auto& attachment = rp->createInfo.pAttachments[i];
1958 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1959 const auto& clear_color = cmd_state->activeRenderPassBeginInfo.pClearValues[i].color;
1960 RecordClearColor(attachment.format, clear_color);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001961 }
1962 }
1963 }
1964 }
1965 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
1966 const VkImage depth_image = depth_image_view->image_state->image();
1967 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
1968 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
1969 } else {
1970 RecordUnbindZcullScope(*cmd_state);
1971 }
1972 if (load_op) {
1973 if (*load_op == VK_ATTACHMENT_LOAD_OP_CLEAR || *load_op == VK_ATTACHMENT_LOAD_OP_DONT_CARE) {
1974 RecordResetScopeZcullDirection(*cmd_state);
1975 }
1976 }
1977 }
1978}
1979
1980void BestPractices::RecordCmdEndRenderingCommon(VkCommandBuffer commandBuffer) {
1981 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1982 assert(cmd_state);
1983
1984 auto rp = cmd_state->activeRenderPass.get();
1985 assert(rp);
1986
1987 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1988 layer_data::optional<VkAttachmentStoreOp> store_op;
1989
1990 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1991 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1992 if (depth_attachment) {
1993 store_op.emplace(depth_attachment->storeOp);
1994 }
1995 } else {
1996 if (rp->createInfo.subpassCount > 0) {
1997 const uint32_t last_subpass = rp->createInfo.subpassCount - 1;
1998 const auto depth_attachment = rp->createInfo.pSubpasses[last_subpass].pDepthStencilAttachment;
1999 if (depth_attachment) {
2000 const uint32_t attachment = depth_attachment->attachment;
2001 if (attachment != VK_ATTACHMENT_UNUSED) {
2002 store_op.emplace(rp->createInfo.pAttachments[attachment].storeOp);
2003 }
2004 }
2005 }
2006 }
2007
2008 if (store_op) {
2009 if (*store_op == VK_ATTACHMENT_STORE_OP_DONT_CARE || *store_op == VK_ATTACHMENT_STORE_OP_NONE) {
2010 RecordResetScopeZcullDirection(*cmd_state);
2011 }
2012 }
2013
2014 RecordUnbindZcullScope(*cmd_state);
2015 }
2016}
2017
2018void BestPractices::RecordBindZcullScope(bp_state::CommandBuffer& cmd_state, VkImage depth_attachment, const VkImageSubresourceRange& subresource_range) {
2019 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2020
2021 if (depth_attachment == VK_NULL_HANDLE) {
2022 cmd_state.nv.zcull_scope = {};
2023 return;
2024 }
2025
2026 assert((subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U);
2027
2028 auto image_state = Get<IMAGE_STATE>(depth_attachment);
2029 assert(image_state);
2030
2031 const uint32_t mip_levels = image_state->createInfo.mipLevels;
2032 const uint32_t array_layers = image_state->createInfo.arrayLayers;
2033
2034 auto& tree = cmd_state.nv.zcull_per_image[depth_attachment];
2035 if (tree.states.empty()) {
2036 tree.mip_levels = mip_levels;
2037 tree.array_layers = array_layers;
2038 tree.states.resize(array_layers * mip_levels);
2039 }
2040
2041 cmd_state.nv.zcull_scope.image = depth_attachment;
2042 cmd_state.nv.zcull_scope.range = subresource_range;
2043 cmd_state.nv.zcull_scope.tree = &tree;
2044}
2045
2046void BestPractices::RecordUnbindZcullScope(bp_state::CommandBuffer& cmd_state) {
2047 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2048
2049 RecordBindZcullScope(cmd_state, VK_NULL_HANDLE, VkImageSubresourceRange{});
2050}
2051
2052void BestPractices::RecordResetScopeZcullDirection(bp_state::CommandBuffer& cmd_state) {
2053 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2054
2055 auto& scope = cmd_state.nv.zcull_scope;
2056 RecordResetZcullDirection(cmd_state, scope.image, scope.range);
2057}
2058
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002059template <typename Func>
2060static void ForEachSubresource(const IMAGE_STATE& image, const VkImageSubresourceRange& range, Func&& func)
2061{
paul-lunarg0ec95562022-09-08 16:02:53 +02002062 const uint32_t layerCount =
2063 (range.layerCount == VK_REMAINING_ARRAY_LAYERS) ? (image.full_range.layerCount - range.baseArrayLayer) : range.layerCount;
2064 const uint32_t levelCount =
2065 (range.levelCount == VK_REMAINING_MIP_LEVELS) ? (image.full_range.levelCount - range.baseMipLevel) : range.levelCount;
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002066
2067 for (uint32_t i = 0; i < layerCount; ++i) {
2068 const uint32_t layer = range.baseArrayLayer + i;
2069 for (uint32_t j = 0; j < levelCount; ++j) {
2070 const uint32_t level = range.baseMipLevel + j;
2071 func(layer, level);
2072 }
2073 }
2074}
2075
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002076void BestPractices::RecordResetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2077 const VkImageSubresourceRange& subresource_range) {
2078 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2079
2080 RecordSetZcullDirection(cmd_state, depth_image, subresource_range, bp_state::CommandBufferStateNV::ZcullDirection::Unknown);
2081
2082 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2083 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2084 return;
2085 }
2086 auto& tree = image_it->second;
2087
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002088 auto image = Get<IMAGE_STATE>(depth_image);
2089 if (!image) return;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002090
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002091 ForEachSubresource(*image, subresource_range, [&tree](uint32_t layer, uint32_t level) {
2092 auto& subresource = tree.GetState(layer, level);
2093 subresource.num_less_draws = 0;
2094 subresource.num_greater_draws = 0;
2095 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002096}
2097
2098void BestPractices::RecordSetScopeZcullDirection(bp_state::CommandBuffer& cmd_state, bp_state::CommandBufferStateNV::ZcullDirection mode) {
2099 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2100
2101 auto& scope = cmd_state.nv.zcull_scope;
2102 RecordSetZcullDirection(cmd_state, scope.image, scope.range, mode);
2103}
2104
2105void BestPractices::RecordSetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2106 const VkImageSubresourceRange& subresource_range,
2107 bp_state::CommandBufferStateNV::ZcullDirection mode) {
2108 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2109
2110 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2111 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2112 return;
2113 }
2114 auto& tree = image_it->second;
2115
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002116 auto image = Get<IMAGE_STATE>(depth_image);
2117 if (!image) return;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002118
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002119 ForEachSubresource(*image, subresource_range, [&tree, &cmd_state](uint32_t layer, uint32_t level) {
2120 tree.GetState(layer, level).direction = cmd_state.nv.zcull_direction;
2121 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002122}
2123
2124void BestPractices::RecordZcullDraw(bp_state::CommandBuffer& cmd_state) {
2125 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2126
2127 // Add one draw to each subresource depending on the current Z-cull direction
2128 auto& scope = cmd_state.nv.zcull_scope;
2129
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002130 auto image = Get<IMAGE_STATE>(scope.image);
2131 if (!image) return;
2132
2133 ForEachSubresource(*image, scope.range, [&scope](uint32_t layer, uint32_t level) {
2134 auto& subresource = scope.tree->GetState(layer, level);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002135
2136 switch (subresource.direction) {
2137 case bp_state::CommandBufferStateNV::ZcullDirection::Unknown:
2138 // Unreachable
2139 assert(0);
2140 break;
2141 case bp_state::CommandBufferStateNV::ZcullDirection::Less:
2142 ++subresource.num_less_draws;
2143 break;
2144 case bp_state::CommandBufferStateNV::ZcullDirection::Greater:
2145 ++subresource.num_greater_draws;
2146 break;
2147 }
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002148 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002149}
2150
Mark Young0a6b48f2022-08-18 11:17:02 -06002151bool BestPractices::ValidateZcullScope(const bp_state::CommandBuffer& cmd_state) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002152 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2153
2154 bool skip = false;
2155
Mark Young0a6b48f2022-08-18 11:17:02 -06002156 if (cmd_state.nv.depth_test_enable) {
2157 auto& scope = cmd_state.nv.zcull_scope;
2158 skip |= ValidateZcull(cmd_state, scope.image, scope.range);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002159 }
2160
2161 return skip;
2162}
2163
Mark Young0a6b48f2022-08-18 11:17:02 -06002164bool BestPractices::ValidateZcull(const bp_state::CommandBuffer& cmd_state, VkImage image,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002165 const VkImageSubresourceRange& subresource_range) const {
2166 bool skip = false;
2167
2168 const char* good_mode = nullptr;
2169 const char* bad_mode = nullptr;
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002170 bool is_balanced = false;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002171
Mark Young0a6b48f2022-08-18 11:17:02 -06002172 const auto image_it = cmd_state.nv.zcull_per_image.find(image);
2173 if (image_it == cmd_state.nv.zcull_per_image.end()) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002174 return skip;
2175 }
2176 const auto& tree = image_it->second;
2177
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002178 auto image_state = Get<IMAGE_STATE>(image);
2179 if (!image_state) {
2180 return skip;
2181 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002182
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002183 ForEachSubresource(*image_state, subresource_range, [&](uint32_t layer, uint32_t level) {
2184 if (is_balanced) {
2185 return;
2186 }
2187 const auto& resource = tree.GetState(layer, level);
2188 const uint64_t num_draws = resource.num_less_draws + resource.num_greater_draws;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002189
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002190 if (num_draws == 0) {
2191 return;
2192 }
2193 const uint64_t less_ratio = (resource.num_less_draws * 100) / num_draws;
2194 const uint64_t greater_ratio = (resource.num_greater_draws * 100) / num_draws;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002195
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002196 if ((less_ratio > kZcullDirectionBalanceRatioNVIDIA) && (greater_ratio > kZcullDirectionBalanceRatioNVIDIA)) {
2197 is_balanced = true;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002198
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002199 if (greater_ratio > less_ratio) {
2200 good_mode = "GREATER";
2201 bad_mode = "LESS";
2202 } else {
2203 good_mode = "LESS";
2204 bad_mode = "GREATER";
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002205 }
2206 }
Rodrigo Locattic94a5cd2022-08-24 18:33:07 -03002207 });
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002208
2209 if (is_balanced) {
2210 skip |= LogPerformanceWarning(
Mark Young0a6b48f2022-08-18 11:17:02 -06002211 cmd_state.commandBuffer(), kVUID_BestPractices_Zcull_LessGreaterRatio,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002212 "%s Depth attachment %s is primarily rendered with depth compare op %s, but some draws use %s. "
2213 "Z-cull is disabled for the least used direction, which harms depth testing performance. "
2214 "The Z-cull direction can be reset by clearing the depth attachment, transitioning from VK_IMAGE_LAYOUT_UNDEFINED, "
2215 "using VK_ATTACHMENT_LOAD_OP_DONT_CARE, or using VK_ATTACHMENT_STORE_OP_DONT_CARE.",
Mark Young0a6b48f2022-08-18 11:17:02 -06002216 VendorSpecificTag(kBPVendorNVIDIA), report_data->FormatHandle(cmd_state.nv.zcull_scope.image).c_str(), good_mode,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002217 bad_mode);
2218 }
2219
2220 return skip;
2221}
2222
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002223static std::array<uint32_t, 4> GetRawClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2224 std::array<uint32_t, 4> raw_color{};
2225 std::copy_n(clear_value.uint32, raw_color.size(), raw_color.data());
2226
2227 // Zero out unused components to avoid polluting the cache with garbage
2228 if (!FormatHasRed(format)) raw_color[0] = 0;
2229 if (!FormatHasGreen(format)) raw_color[1] = 0;
2230 if (!FormatHasBlue(format)) raw_color[2] = 0;
2231 if (!FormatHasAlpha(format)) raw_color[3] = 0;
2232
2233 return raw_color;
2234}
2235
2236static bool IsClearColorZeroOrOne(VkFormat format, const std::array<uint32_t, 4> clear_color) {
2237 static_assert(sizeof(float) == sizeof(uint32_t), "Mismatching float <-> uint32 sizes");
2238 const float one = 1.0f;
2239 const float zero = 0.0f;
2240 uint32_t raw_one{};
2241 uint32_t raw_zero{};
2242 memcpy(&raw_one, &one, sizeof(one));
2243 memcpy(&raw_zero, &zero, sizeof(zero));
2244
2245 const bool is_one = (!FormatHasRed(format) || (clear_color[0] == raw_one)) &&
2246 (!FormatHasGreen(format) || (clear_color[1] == raw_one)) &&
2247 (!FormatHasBlue(format) || (clear_color[2] == raw_one)) &&
2248 (!FormatHasAlpha(format) || (clear_color[3] == raw_one));
2249 const bool is_zero = (!FormatHasRed(format) || (clear_color[0] == raw_zero)) &&
2250 (!FormatHasGreen(format) || (clear_color[1] == raw_zero)) &&
2251 (!FormatHasBlue(format) || (clear_color[2] == raw_zero)) &&
2252 (!FormatHasAlpha(format) || (clear_color[3] == raw_zero));
2253 return is_one || is_zero;
2254}
2255
2256static std::string MakeCompressedFormatListNVIDIA() {
2257 std::string format_list;
2258 for (VkFormat compressed_format : kCustomClearColorCompressedFormatsNVIDIA) {
2259 if (compressed_format == kCustomClearColorCompressedFormatsNVIDIA.back()) {
2260 format_list += "or ";
2261 }
2262 format_list += string_VkFormat(compressed_format);
2263 if (compressed_format != kCustomClearColorCompressedFormatsNVIDIA.back()) {
2264 format_list += ", ";
2265 }
2266 }
2267 return format_list;
2268}
2269
2270void BestPractices::RecordClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2271 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2272
2273 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2274 if (IsClearColorZeroOrOne(format, raw_color)) {
2275 // These colors are always compressed
2276 return;
2277 }
2278
2279 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2280 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2281 // The format cannot be compressed with a custom color
2282 return;
2283 }
2284
2285 // Record custom clear color
2286 WriteLockGuard guard{clear_colors_lock_};
2287 if (clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA) {
2288 clear_colors_.insert(raw_color);
2289 }
2290}
2291
2292bool BestPractices::ValidateClearColor(VkCommandBuffer commandBuffer, VkFormat format, const VkClearColorValue& clear_value) const {
2293 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2294
2295 bool skip = false;
2296
2297 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2298 if (IsClearColorZeroOrOne(format, raw_color)) {
2299 return skip;
2300 }
2301
2302 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2303 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2304 // The format is not compressible
2305 static const std::string format_list = MakeCompressedFormatListNVIDIA();
2306
2307 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2308 "%s Clearing image with format %s without a 1.0f or 0.0f clear color. "
2309 "The clear will not get compressed in the GPU, harming performance. "
2310 "This can be fixed using a clear color of VkClearColorValue{0.0f, 0.0f, 0.0f, 0.0f}, or "
2311 "VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f}. Alternatively, use %s.",
2312 VendorSpecificTag(kBPVendorNVIDIA), string_VkFormat(format), format_list.c_str());
2313 } else {
2314 // The format is compressible
2315 bool registered = false;
2316 {
2317 ReadLockGuard guard{clear_colors_lock_};
2318 registered = clear_colors_.find(raw_color) != clear_colors_.end();
2319
2320 if (!registered) {
2321 // If it's not in the list, it might be new. Check if there's still space for new entries.
2322 registered = clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA;
2323 }
2324 }
2325 if (!registered) {
2326 std::string clear_color_str;
2327
2328 if (FormatIsUINT(format)) {
2329 clear_color_str = std::to_string(clear_value.uint32[0]) + ", " + std::to_string(clear_value.uint32[1]) + ", " +
2330 std::to_string(clear_value.uint32[2]) + ", " + std::to_string(clear_value.uint32[3]);
2331 } else if (FormatIsSINT(format)) {
2332 clear_color_str = std::to_string(clear_value.int32[0]) + ", " + std::to_string(clear_value.int32[1]) + ", " +
2333 std::to_string(clear_value.int32[2]) + ", " + std::to_string(clear_value.int32[3]);
2334 } else {
2335 clear_color_str = std::to_string(clear_value.float32[0]) + ", " + std::to_string(clear_value.float32[1]) + ", " +
2336 std::to_string(clear_value.float32[2]) + ", " + std::to_string(clear_value.float32[3]);
2337 }
2338
2339 skip |= LogPerformanceWarning(
2340 commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2341 "%s Clearing image with unregistered VkClearColorValue{%s}. "
2342 "This clear will not get compressed in the GPU, harming performance. "
2343 "The clear color is not registered because too many unique colors have been used. "
2344 "Select a discrete set of clear colors and stick to those. "
2345 "VkClearColorValue{0, 0, 0, 0} and VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f} are always registered.",
2346 VendorSpecificTag(kBPVendorNVIDIA), clear_color_str.c_str());
2347 }
2348 }
2349
2350 return skip;
2351}
2352
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002353static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2354 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
2355 const auto& subpass_info = createInfo.pSubpasses[subpass];
2356 if (subpass_info.pResolveAttachments) {
2357 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2358 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2359 }
2360 }
2361 }
2362
2363 return false;
2364}
2365
Attilio Provenzano02859b22020-02-27 14:17:28 +00002366static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2367 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002368 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002369
2370 // If an attachment is ever used as a color attachment,
2371 // resolve attachment or depth stencil attachment,
2372 // it needs to exist on tile at some point.
2373
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002374 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2375 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002376 }
2377
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002378 if (subpass_info.pResolveAttachments) {
2379 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2380 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2381 }
2382 }
2383
2384 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002385 }
2386
2387 return false;
2388}
2389
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002390static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2391 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
2392 return false;
2393 }
2394
2395 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002396 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002397
2398 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
2399 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
2400 return true;
2401 }
2402 }
2403 }
2404
2405 return false;
2406}
2407
Attilio Provenzano02859b22020-02-27 14:17:28 +00002408bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2409 const VkRenderPassBeginInfo* pRenderPassBegin) const {
2410 bool skip = false;
2411
2412 if (!pRenderPassBegin) {
2413 return skip;
2414 }
2415
Gareth Webbdc6549a2021-06-16 03:52:24 +01002416 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
2417 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
2418 "This render pass has a zero-size render area. It cannot write to any attachments, "
2419 "and can only be used for side effects such as layout transitions.");
2420 }
2421
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002422 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002423 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002424 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07002425 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06002426 if (rpabi) {
2427 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
2428 }
2429 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002430 // Check if any attachments have LOAD operation on them
2431 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002432 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002433
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002434 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02002435 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002436 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002437 }
2438
2439 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002440 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002441 }
2442
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002443 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002444
2445 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002446 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2447 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002448 }
2449
2450 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00002451 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
2452 skip |=
2453 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00002454 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00002455 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04002456 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00002457 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
2458 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
2459 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
2460 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
2461 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002462 }
2463 }
paul-lunarg7089e272022-06-20 22:19:37 +02002464
2465 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
2466
2467 bool clearing = false;
2468
2469 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
2470 const auto& attachment = rp_state->createInfo.pAttachments[att];
2471
2472 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2473 clearing = true;
2474 break;
2475 }
2476 }
2477
2478 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
2479 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
2480 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
2481 skip |= LogWarning(
2482 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
2483 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
2484 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02002485 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02002486 }
paul-lunarga0a149c2022-06-23 16:18:51 +02002487
2488 // Check if there are more clearValues than attachments
2489 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
2490 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
2491 // This could signal a bug and there seems to be no reason for this to happen on purpose.
2492 skip |= LogWarning(
2493 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
2494 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
2495 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
2496 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
2497 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002498
2499 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp_state->createInfo.pAttachments) {
2500 for (uint32_t i = 0; i < pRenderPassBegin->clearValueCount; ++i) {
2501 const auto& attachment = rp_state->createInfo.pAttachments[i];
2502 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2503 const auto& clear_color = pRenderPassBegin->pClearValues[i].color;
2504 skip |= ValidateClearColor(commandBuffer, attachment.format, clear_color);
2505 }
2506 }
2507 }
2508 }
2509
2510 return skip;
2511}
2512
2513bool BestPractices::ValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2514 bool skip = false;
2515
2516 auto cmd_state = Get<bp_state::CommandBuffer>(commandBuffer);
2517 assert(cmd_state);
2518
2519 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2520 for (uint32_t i = 0; i < pRenderingInfo->colorAttachmentCount; ++i) {
2521 const auto& color_attachment = pRenderingInfo->pColorAttachments[i];
2522 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2523 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
2524 skip |= ValidateClearColor(commandBuffer, format, color_attachment.clearValue.color);
2525 }
2526 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002527 }
2528
2529 return skip;
2530}
2531
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002532void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
2533 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002534 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002535 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
2536 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002537 }
2538}
2539
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002540void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2541 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002542 // If we're viewing a 3D slice, ignore base array layer.
2543 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002544 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 +02002545
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002546 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002547 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002548 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
2549 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002550
2551 for (uint32_t layer = 0; layer < array_layers; layer++) {
2552 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002553 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
2554 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002555 }
2556 }
2557}
2558
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002559void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2560 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
2561 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002562 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002563
2564 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002565 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002566 }
2567}
2568
paul-lunarg5eb52062022-06-27 18:57:15 +02002569void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2570 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
2571 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
2572 const CMD_BUFFER_STATE&) -> bool {
2573 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
2574 return false;
2575 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002576}
2577
LawG44d414ba2022-02-23 15:35:41 +00002578void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002579 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002580 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002581 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002582 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 -07002583 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002584 LogPerformanceWarning(
2585 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00002586 "%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 +02002587 "image was used, it was written to with STORE_OP_STORE. "
2588 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
2589 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00002590 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002591 } 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 +02002592 LogPerformanceWarning(
2593 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00002594 "%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 +02002595 "image was used, it was written to with vkCmdClear*Image(). "
2596 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00002597 "tile-based architectures.",
2598 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002599 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002600 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
2601 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002602 const char *last_cmd = nullptr;
2603 const char *vuid = nullptr;
2604 const char *suggestion = nullptr;
2605
2606 switch (last_usage) {
2607 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
2608 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
2609 last_cmd = "vkCmdBlitImage";
2610 suggestion =
2611 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2612 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
2613 "which avoids the memory roundtrip.";
2614 break;
2615 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
2616 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
2617 last_cmd = "vkCmdClear*Image";
2618 suggestion =
2619 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
2620 "tile-based architectures. "
2621 "Use LOAD_OP_CLEAR instead to clear the image for free.";
2622 break;
2623 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
2624 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
2625 last_cmd = "vkCmdCopy*Image";
2626 suggestion =
2627 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2628 "Rather than copying, just render the source image in a fragment shader in this render pass, "
2629 "which avoids the memory roundtrip.";
2630 break;
2631 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
2632 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
2633 last_cmd = "vkCmdResolveImage";
2634 suggestion =
2635 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
2636 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
2637 "which avoids the memory roundtrip.";
2638 break;
2639 default:
2640 break;
2641 }
2642
2643 LogPerformanceWarning(
2644 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00002645 "%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 +01002646 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00002647 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
2648 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002649 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002650}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002651
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002652void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
2653 uint32_t array_layer, uint32_t mip_level) {
2654 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02002655
2656 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
2657 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
2658 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
2659 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
2660 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
2661 "result in undefined behaviour.");
2662 }
2663
LawG44d414ba2022-02-23 15:35:41 +00002664 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
2665 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002666 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002667}
2668
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002669void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
2670 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
2671 cb.queue_submit_functions_after_render_pass.end());
2672 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002673}
2674
2675void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002676 RecordCmdEndRenderingCommon(commandBuffer);
2677
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002678 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002679 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2680 if (cb_node) {
2681 AddDeferredQueueOperations(*cb_node);
2682 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002683}
2684
2685void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002686 RecordCmdEndRenderingCommon(commandBuffer);
2687
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002688 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002689 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2690 if (cb_node) {
2691 AddDeferredQueueOperations(*cb_node);
2692 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002693}
2694
2695void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002696 RecordCmdEndRenderingCommon(commandBuffer);
2697
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002698 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002699 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2700 if (cb_node) {
2701 AddDeferredQueueOperations(*cb_node);
2702 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002703}
2704
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002705void BestPractices::PreCallRecordCmdEndRendering(VkCommandBuffer commandBuffer) {
2706 RecordCmdEndRenderingCommon(commandBuffer);
2707
2708 ValidationStateTracker::PreCallRecordCmdEndRendering(commandBuffer);
2709}
2710
2711void BestPractices::PreCallRecordCmdEndRenderingKHR(VkCommandBuffer commandBuffer) {
2712 RecordCmdEndRenderingCommon(commandBuffer);
2713
2714 ValidationStateTracker::PreCallRecordCmdEndRenderingKHR(commandBuffer);
2715}
2716
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002717void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
2718 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002719 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002720 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002721 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002722 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2723}
2724
2725void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
2726 const VkRenderPassBeginInfo* pRenderPassBegin,
2727 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2728 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002729 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002730 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2731}
2732
2733void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2734 const VkRenderPassBeginInfo* pRenderPassBegin,
2735 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2736 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002737 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002738 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2739}
2740
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002741void BestPractices::PreCallRecordCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2742 ValidationStateTracker::PreCallRecordCmdBeginRendering(commandBuffer, pRenderingInfo);
2743 RecordCmdBeginRenderingCommon(commandBuffer);
2744}
2745
2746void BestPractices::PreCallRecordCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2747 ValidationStateTracker::PreCallRecordCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2748 RecordCmdBeginRenderingCommon(commandBuffer);
2749}
2750
2751void BestPractices::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
2752 ValidationStateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
2753
2754 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2755 auto rp = cmd_state->activeRenderPass.get();
2756 assert(rp);
2757
2758 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2759 IMAGE_VIEW_STATE* depth_image_view = nullptr;
2760
2761 const auto depth_attachment = rp->createInfo.pSubpasses[cmd_state->activeSubpass].pDepthStencilAttachment;
2762 if (depth_attachment) {
2763 const uint32_t attachment_index = depth_attachment->attachment;
2764 if (attachment_index != VK_ATTACHMENT_UNUSED) {
2765 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
2766 }
2767 }
2768 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
2769 const VkImage depth_image = depth_image_view->image_state->image();
2770 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
2771 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
2772 } else {
2773 RecordUnbindZcullScope(*cmd_state);
2774 }
2775 }
2776}
2777
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002778void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002779
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002780 if (!pRenderPassBegin) {
2781 return;
2782 }
2783
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002784 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002785
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002786 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002787 if (rp_state) {
2788 // Check load ops
2789 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002790 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002791
2792 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
2793 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2794 continue;
2795 }
2796
paul-lunargce0a2062022-09-09 15:22:51 +02002797 // If renderpass doesn't load attachment, no need to validate image in queue
2798 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_NONE_EXT) ||
2799 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_NONE_EXT)) {
2800 continue;
2801 }
2802
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002803 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002804
2805 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
2806 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002807 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002808 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
2809 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002810 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002811 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002812 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002813 }
2814
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002815 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002816 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002817
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002818 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002819 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2820 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002821 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002822 }
2823 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002824 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002825 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002826
Jeremy Gebben9f537102021-10-05 16:37:12 -06002827 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002828 }
2829
2830 // Check store ops
2831 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002832 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002833
2834 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2835 continue;
2836 }
2837
paul-lunargce0a2062022-09-09 15:22:51 +02002838 // If renderpass doesn't store attachment, no need to validate image in queue
2839 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_NONE) ||
2840 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_NONE)) {
2841 continue;
2842 }
2843
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002844 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002845
2846 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2847 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002848 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002849 }
2850
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002851 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002852
Jeremy Gebben9f537102021-10-05 16:37:12 -06002853 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002854 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002855 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2856 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002857 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002858 }
2859 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002860 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002861 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002862
Jeremy Gebben9f537102021-10-05 16:37:12 -06002863 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002864 }
2865 }
2866}
2867
Attilio Provenzano02859b22020-02-27 14:17:28 +00002868bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2869 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002870 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2871 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002872 return skip;
2873}
2874
2875bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2876 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002877 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002878 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2879 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002880 return skip;
2881}
2882
2883bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002884 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002885 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2886 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002887 return skip;
2888}
2889
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002890bool BestPractices::PreCallValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2891 bool skip = StateTracker::PreCallValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2892 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2893 return skip;
2894}
2895
2896bool BestPractices::PreCallValidateCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2897 bool skip = StateTracker::PreCallValidateCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2898 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2899 return skip;
2900}
2901
Sam Walls0961ec02020-03-31 16:39:15 +01002902void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2903 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002904 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002905 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002906 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2907 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002908 assert(cb);
2909 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002910 render_pass_state.touchesAttachments.clear();
2911 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002912 render_pass_state.numDrawCallsDepthOnly = 0;
2913 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2914 render_pass_state.colorAttachment = false;
2915 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002916 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002917 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002918
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03002919 // Reset NV state
2920 cb->nv = {};
2921
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002922 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002923
2924 // track depth / color attachment usage within the renderpass
2925 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2926 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002927 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002928
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002929 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002930 }
2931}
2932
2933void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2934 VkSubpassContents contents) {
2935 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2936 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2937}
2938
2939void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2940 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2941 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2942 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2943}
2944
2945void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2946 const VkRenderPassBeginInfo* pRenderPassBegin,
2947 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2948 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2949 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2950}
2951
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002952// Generic function to handle validation for all CmdDraw* type functions
2953bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2954 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002955 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002956 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002957 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2958 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002959 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002960
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002961 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002962 if (pipeline_state && pipeline_state->vertex_input_state &&
2963 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002964 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002965 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002966 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002967 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2968 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002969 }
2970 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002971
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002972 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002973 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002974 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002975 if (rp_state) {
2976 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2977 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002978 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002979 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002980 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2981 const auto* raster_state = pipe->RasterizationState();
2982 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2983 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002984 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2985 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2986 }
2987 }
2988 }
2989 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002990 }
2991 return skip;
2992}
2993
Sam Walls0961ec02020-03-31 16:39:15 +01002994void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002995 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002996 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002997 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002998 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002999 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003000 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3001 RecordCmdDrawTypeNVIDIA(*cb_node);
3002 }
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02003003
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003004 if (cb_node->render_pass_state.drawTouchAttachments) {
3005 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
3006 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02003007 }
3008 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003009 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01003010 }
3011}
3012
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003013void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
3014 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00003015 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
3016 // depth prepass warnings First find the lowest enabled draw count
3017 uint32_t lowestEnabledMinDrawCount = 0;
3018 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
3019 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
3020 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
3021
3022 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02003023 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
3024 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01003025 }
3026}
3027
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003028void BestPractices::RecordCmdDrawTypeNVIDIA(bp_state::CommandBuffer& cmd_state) {
3029 assert(VendorCheckEnabled(kBPVendorNVIDIA));
3030
3031 if (cmd_state.nv.depth_test_enable && cmd_state.nv.zcull_direction != bp_state::CommandBufferStateNV::ZcullDirection::Unknown) {
3032 RecordSetScopeZcullDirection(cmd_state, cmd_state.nv.zcull_direction);
3033 RecordZcullDraw(cmd_state);
3034 }
3035}
3036
Camden5b184be2019-08-13 07:50:19 -06003037bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003038 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003039 bool skip = false;
3040
3041 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003042 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3043 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003044 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06003045 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06003046
3047 return skip;
3048}
3049
Sam Walls0961ec02020-03-31 16:39:15 +01003050void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3051 uint32_t firstVertex, uint32_t firstInstance) {
3052 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
3053 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
3054}
3055
Camden5b184be2019-08-13 07:50:19 -06003056bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003057 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003058 bool skip = false;
3059
3060 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003061 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3062 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003063 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003064 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
3065
Attilio Provenzano02859b22020-02-27 14:17:28 +00003066 // Check if we reached the limit for small indexed draw calls.
3067 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003068 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003069 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003070 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00003071 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003072 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00003073 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00003074 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
3075 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00003076 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
3077 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003078 }
3079
Sam Walls8e77e4f2020-03-16 20:47:40 +00003080 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003081 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003082 }
3083
3084 return skip;
3085}
3086
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003087bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00003088 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
3089 bool skip = false;
3090
3091 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00003092
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003093 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
3094 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003095
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003096 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003097 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00003098 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
3099 const void* ib_mem = ib_mem_state.p_driver_data;
3100 bool primitive_restart_enable = false;
3101
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003102 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003103 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003104 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003105
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07003106 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
3107 if (ia_state) {
3108 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003109 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00003110
3111 // 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 -06003112 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00003113 uint32_t scan_stride;
3114 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3115 scan_stride = sizeof(uint8_t);
3116 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3117 scan_stride = sizeof(uint16_t);
3118 } else {
3119 scan_stride = sizeof(uint32_t);
3120 }
3121
3122 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
3123 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
3124
3125 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
3126 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
3127 // irrespective of whether or not they're part of the draw call.
3128
3129 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
3130 uint32_t min_index = ~0u;
3131 // start with maximum as 0 and adjust to indices in the buffer
3132 uint32_t max_index = 0u;
3133
3134 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
3135 // for the given index buffer
3136 uint32_t vertex_shade_count = 0;
3137
3138 PostTransformLRUCacheModel post_transform_cache;
3139
3140 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
3141 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
3142 // target architecture.
3143 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
3144 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
3145 post_transform_cache.resize(32);
3146
3147 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3148 uint32_t scan_index;
3149 uint32_t primitive_restart_value;
3150 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3151 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3152 primitive_restart_value = 0xFF;
3153 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3154 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3155 primitive_restart_value = 0xFFFF;
3156 } else {
3157 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3158 primitive_restart_value = 0xFFFFFFFF;
3159 }
3160
3161 max_index = std::max(max_index, scan_index);
3162 min_index = std::min(min_index, scan_index);
3163
3164 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
3165 bool in_cache = post_transform_cache.query_cache(scan_index);
3166 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
3167 if (!in_cache) vertex_shade_count++;
3168 }
3169 }
3170
3171 // 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 +01003172 // 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
3173 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003174
3175 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07003176 skip |=
3177 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3178 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
3179 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
3180 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
3181 "maximum would be loaded, and possibly shaded, whether or not they are used.",
3182 VendorSpecificTag(kBPVendorArm),
3183 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003184 return skip;
3185 }
3186
3187 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
3188 // 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 +01003189 const size_t refs_per_bucket = 64;
3190 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
3191
3192 const uint32_t n_indices = max_index - min_index + 1;
3193 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
3194 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
3195
3196 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
3197 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00003198
3199 // To avoid using too much memory, we run over the indices again.
3200 // Knowing the size from the last scan allows us to record index usage with bitsets
3201 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3202 uint32_t scan_index;
3203 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3204 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3205 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3206 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3207 } else {
3208 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3209 }
3210 // keep track of the set of all indices used to reference vertices in the draw call
3211 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01003212 size_t bitset_bucket_index = index_offset / refs_per_bucket;
3213 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003214 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
3215 }
3216
3217 uint32_t vertex_reference_count = 0;
3218 for (const auto& bitset : vertex_reference_buckets) {
3219 vertex_reference_count += static_cast<uint32_t>(bitset.count());
3220 }
3221
3222 // 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 -07003223 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003224 // 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 -07003225 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003226
3227 if (utilization < 0.5f) {
3228 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3229 "%s The indices which were specified for the draw call only utilise approximately "
3230 "%.02f%% of the bound vertex buffer.",
3231 VendorSpecificTag(kBPVendorArm), utilization);
3232 }
3233
3234 if (cache_hit_rate <= 0.5f) {
3235 skip |=
3236 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
3237 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
3238 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
3239 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
3240 "recently shaded vertices.",
3241 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
3242 }
3243 }
3244
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003245 return skip;
3246}
3247
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003248bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3249 const VkCommandBuffer* pCommandBuffers) const {
3250 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003251 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003252 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003253 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003254 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003255 continue;
3256 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003257 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003258 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003259 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
3260 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003261 }
3262 }
3263 }
Nadav Gevaf0808442021-05-21 13:51:25 -04003264
3265 if (VendorCheckEnabled(kBPVendorAMD)) {
3266 if (commandBufferCount > 0) {
3267 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
3268 "%s Performance warning: Use of secondary command buffers is not recommended. ",
3269 VendorSpecificTag(kBPVendorAMD));
3270 }
3271 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003272 return skip;
3273}
3274
3275void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3276 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003277 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
3278
3279 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3280 if (!primary) {
3281 return;
3282 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003283
3284 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003285 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
3286 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003287 continue;
3288 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003289
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003290 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
3291 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
3292 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
3293 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003294 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003295 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003296 }
3297 }
3298
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003299 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
3300 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003301 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02003302
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003303 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
3304 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003305 }
3306
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003307}
3308
Rodrigo Locatti7d716e12022-03-09 19:15:17 -03003309bool BestPractices::PreCallValidateCmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer,
3310 const VkAccelerationStructureInfoNV* pInfo,
3311 VkBuffer instanceData, VkDeviceSize instanceOffset,
3312 VkBool32 update, VkAccelerationStructureNV dst,
3313 VkAccelerationStructureNV src, VkBuffer scratch,
3314 VkDeviceSize scratchOffset) const {
3315 return ValidateBuildAccelerationStructure(commandBuffer);
3316}
3317
3318bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresIndirectKHR(
3319 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3320 const VkDeviceAddress* pIndirectDeviceAddresses, const uint32_t* pIndirectStrides,
3321 const uint32_t* const* ppMaxPrimitiveCounts) const {
3322 return ValidateBuildAccelerationStructure(commandBuffer);
3323}
3324
3325bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresKHR(
3326 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3327 const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const {
3328 return ValidateBuildAccelerationStructure(commandBuffer);
3329}
3330
3331bool BestPractices::ValidateBuildAccelerationStructure(VkCommandBuffer commandBuffer) const {
3332 bool skip = false;
3333 auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
3334 assert(cb_node);
3335
3336 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3337 if ((cb_node->GetQueueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) {
3338 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_AccelerationStructure_NotAsync,
3339 "%s Performance warning: Prefer building acceleration structures on an asynchronous "
3340 "compute queue, instead of using the universal graphics queue.",
3341 VendorSpecificTag(kBPVendorNVIDIA));
3342 }
3343 }
3344
3345 return skip;
3346}
3347
Rodrigo Locatti66b23352022-03-15 17:28:32 -03003348bool BestPractices::ValidateBindMemory(VkDevice device, VkDeviceMemory memory) const {
3349 bool skip = false;
3350
3351 if (VendorCheckEnabled(kBPVendorNVIDIA) && device_extensions.vk_ext_pageable_device_local_memory) {
3352 auto mem_info = std::static_pointer_cast<const bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
3353 if (!mem_info->dynamic_priority) {
3354 skip |=
3355 LogPerformanceWarning(device, kVUID_BestPractices_BindMemory_NoPriority,
3356 "%s Use vkSetDeviceMemoryPriorityEXT to provide the OS with information on which allocations "
3357 "should stay in memory and which should be demoted first when video memory is limited. The "
3358 "highest priority should be given to GPU-written resources like color attachments, depth "
3359 "attachments, storage images, and buffers written from the GPU.",
3360 VendorSpecificTag(kBPVendorNVIDIA));
3361 }
3362 }
3363
3364 return skip;
3365}
3366
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003367void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
3368 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003369 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003370 auto itr =
3371 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3372 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003373
3374 if (itr != state.touchesAttachments.end()) {
3375 itr->aspects |= aspects;
3376 } else {
3377 state.touchesAttachments.push_back({ fb_attachment, aspects });
3378 }
3379}
3380
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003381void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003382 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
3383 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003384 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003385 // If we observe a full clear before any other access to a frame buffer attachment,
3386 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003387 auto itr =
3388 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3389 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003390
3391 uint32_t new_aspects = aspects;
3392 if (itr != state.touchesAttachments.end()) {
3393 new_aspects = aspects & ~itr->aspects;
3394 itr->aspects |= aspects;
3395 } else {
3396 state.touchesAttachments.push_back({ fb_attachment, aspects });
3397 }
3398
3399 if (new_aspects == 0) {
3400 return;
3401 }
3402
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003403 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003404 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
3405 // CmdExecuteCommands.
3406 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
3407 std::vector<VkClearRect>{pRects, pRects + rectCount} });
3408 }
3409}
3410
3411void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
3412 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
3413 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003414 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
3415
3416 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3417 auto* rp_state = cmd_state->activeRenderPass.get();
3418 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003419 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
3420
3421 if (rectCount == 0 || !rp_state) {
3422 return;
3423 }
3424
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003425 if (!is_secondary && !fb_state && !rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003426 return;
3427 }
3428
3429 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003430 const bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003431
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003432 if (rp_state->UsesDynamicRendering()) {
3433 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003434 auto pColorAttachments = rp_state->dynamic_rendering_begin_rendering_info.pColorAttachments;
3435
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003436 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003437 auto& clear_attachment = pClearAttachments[i];
3438
3439 if (clear_attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003440 RecordResetScopeZcullDirection(*cmd_state);
3441 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003442 if ((clear_attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) &&
3443 clear_attachment.colorAttachment != VK_ATTACHMENT_UNUSED &&
3444 pColorAttachments) {
3445 const auto& attachment = pColorAttachments[clear_attachment.colorAttachment];
3446 if (attachment.imageView) {
3447 auto image_view_state = Get<IMAGE_VIEW_STATE>(attachment.imageView);
3448 const VkFormat format = image_view_state->create_info.format;
3449 RecordClearColor(format, clear_attachment.clearValue.color);
3450 }
3451 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003452 }
3453 }
3454
3455 // TODO: Implement other best practices for dynamic rendering
3456
3457 } else {
ziga-lunarg885c6542022-03-07 01:08:25 +01003458 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
3459 for (uint32_t i = 0; i < attachmentCount; i++) {
3460 auto& attachment = pClearAttachments[i];
3461 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
3462 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003463
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003464 if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
3465 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3466 RecordResetScopeZcullDirection(*cmd_state);
3467 }
3468 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003469 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
3470 if (subpass.pDepthStencilAttachment) {
3471 fb_attachment = subpass.pDepthStencilAttachment->attachment;
3472 }
3473 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
3474 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003475 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003476 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
3477 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003478 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01003479 aspects, rectCount, pRects);
3480 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003481 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01003482 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003483 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3484 const VkFormat format = rp_state->createInfo.pAttachments[fb_attachment].format;
3485 RecordClearColor(format, attachment.clearValue.color);
3486 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003487 }
3488 }
3489 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003490}
3491
Attilio Provenzano02859b22020-02-27 14:17:28 +00003492void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3493 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3494 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
3495 firstInstance);
3496
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003497 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003498 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
3499 cmd_state->small_indexed_draw_call_count++;
3500 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003501
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003502 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00003503}
3504
Sam Walls0961ec02020-03-31 16:39:15 +01003505void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3506 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3507 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
3508 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
3509}
3510
Camden5b184be2019-08-13 07:50:19 -06003511bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003512 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003513 bool skip = false;
3514
3515 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003516 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3517 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003518 }
3519
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003520 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
3521
Camden5b184be2019-08-13 07:50:19 -06003522 return skip;
3523}
3524
Sam Walls0961ec02020-03-31 16:39:15 +01003525void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3526 uint32_t count, uint32_t stride) {
3527 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
3528 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
3529}
3530
Camden5b184be2019-08-13 07:50:19 -06003531bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003532 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003533 bool skip = false;
3534
3535 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003536 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3537 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003538 }
3539
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003540 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
3541
Camden5b184be2019-08-13 07:50:19 -06003542 return skip;
3543}
3544
Sam Walls0961ec02020-03-31 16:39:15 +01003545void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3546 uint32_t count, uint32_t stride) {
3547 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
3548 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
3549}
3550
Rodrigo Locatti467344a2022-03-30 18:48:13 -03003551bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3552 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3553 uint32_t maxDrawCount, uint32_t stride) const {
3554 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
3555
3556 return skip;
3557}
3558
3559void BestPractices::PostCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3560 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3561 uint32_t maxDrawCount, uint32_t stride) {
3562 StateTracker::PostCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3563 maxDrawCount, stride);
3564 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCount()");
3565}
3566
3567bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3568 VkDeviceSize offset, VkBuffer countBuffer,
3569 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3570 uint32_t stride) const {
3571 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountAMD");
3572
3573 return skip;
3574}
3575
3576void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3577 VkDeviceSize offset, VkBuffer countBuffer,
3578 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3579 uint32_t stride) {
3580 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3581 maxDrawCount, stride);
3582 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountAMD()");
3583}
3584
3585bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3586 VkDeviceSize offset, VkBuffer countBuffer,
3587 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3588 uint32_t stride) const {
3589 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR");
3590
3591 return skip;
3592}
3593
3594void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3595 VkDeviceSize offset, VkBuffer countBuffer,
3596 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3597 uint32_t stride) {
3598 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3599 maxDrawCount, stride);
3600 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountKHR()");
3601}
3602
3603bool BestPractices::PreCallValidateCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3604 uint32_t firstInstance, VkBuffer counterBuffer,
3605 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3606 uint32_t vertexStride) const {
3607 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectByteCountEXT");
3608
3609 return skip;
3610}
3611
3612void BestPractices::PostCallRecordCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3613 uint32_t firstInstance, VkBuffer counterBuffer,
3614 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3615 uint32_t vertexStride) {
3616 StateTracker::PostCallRecordCmdDrawIndirectByteCountEXT(commandBuffer, instanceCount, firstInstance, counterBuffer,
3617 counterBufferOffset, counterOffset, vertexStride);
3618 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectByteCountEXT()");
3619}
3620
3621bool BestPractices::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3622 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3623 uint32_t stride) const {
3624 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCount");
3625
3626 return skip;
3627}
3628
3629void BestPractices::PostCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3630 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3631 uint32_t stride) {
3632 StateTracker::PostCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3633 stride);
3634 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCount()");
3635}
3636
3637bool BestPractices::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3638 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3639 uint32_t maxDrawCount, uint32_t stride) const {
3640 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountAMD");
3641
3642 return skip;
3643}
3644
3645void BestPractices::PostCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3646 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3647 uint32_t maxDrawCount, uint32_t stride) {
3648 StateTracker::PostCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3649 stride);
3650 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountAMD()");
3651}
3652
3653bool BestPractices::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3654 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3655 uint32_t maxDrawCount, uint32_t stride) const {
3656 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountKHR");
3657
3658 return skip;
3659}
3660
3661void BestPractices::PostCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3662 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3663 uint32_t maxDrawCount, uint32_t stride) {
3664 StateTracker::PostCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3665 stride);
3666 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountKHR()");
3667}
3668
3669bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3670 VkDeviceSize offset, VkBuffer countBuffer,
3671 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3672 uint32_t stride) const {
3673 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectCountNV");
3674
3675 return skip;
3676}
3677
3678void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3679 VkDeviceSize offset, VkBuffer countBuffer,
3680 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3681 uint32_t stride) {
3682 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectCountNV(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3683 maxDrawCount, stride);
3684 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectCountNV()");
3685}
3686
3687bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3688 uint32_t drawCount, uint32_t stride) const {
3689 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectNV");
3690
3691 return skip;
3692}
3693
3694void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3695 uint32_t drawCount, uint32_t stride) {
3696 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectNV(commandBuffer, buffer, offset, drawCount, stride);
3697 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectNV()");
3698}
3699
3700bool BestPractices::PreCallValidateCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) const {
3701 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksNV");
3702
3703 return skip;
3704}
3705
3706void BestPractices::PostCallRecordCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) {
3707 StateTracker::PostCallRecordCmdDrawMeshTasksNV(commandBuffer, taskCount, firstTask);
3708 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksNV()");
3709}
3710
3711bool BestPractices::PreCallValidateCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3712 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3713 uint32_t firstInstance, uint32_t stride,
3714 const int32_t* pVertexOffset) const {
3715 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiIndexedEXT");
3716
3717 return skip;
3718}
3719
3720void BestPractices::PostCallRecordCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3721 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3722 uint32_t firstInstance, uint32_t stride, const int32_t* pVertexOffset) {
3723 StateTracker::PostCallRecordCmdDrawMultiIndexedEXT(commandBuffer, drawCount, pIndexInfo, instanceCount, firstInstance, stride,
3724 pVertexOffset);
3725 uint32_t count = 0;
3726 for (uint32_t i = 0; i < drawCount; ++i) {
3727 count += pIndexInfo[i].indexCount;
3728 }
3729 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiIndexedEXT()");
3730}
3731
3732bool BestPractices::PreCallValidateCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount, const VkMultiDrawInfoEXT* pVertexInfo,
3733 uint32_t instanceCount, uint32_t firstInstance, uint32_t stride) const {
3734 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiEXT");
3735
3736 return skip;
3737}
3738
3739void BestPractices::PostCallRecordCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3740 const VkMultiDrawInfoEXT* pVertexInfo, uint32_t instanceCount,
3741 uint32_t firstInstance, uint32_t stride) {
3742 StateTracker::PostCallRecordCmdDrawMultiEXT(commandBuffer, drawCount, pVertexInfo, instanceCount, firstInstance, stride);
3743 uint32_t count = 0;
3744 for (uint32_t i = 0; i < drawCount; ++i) {
3745 count += pVertexInfo[i].vertexCount;
3746 }
3747 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiEXT()");
3748}
3749
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003750void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
3751 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003752 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003753 // For bindless scenarios, we should not attempt to track descriptor set state.
3754 // It is highly uncertain which resources are actually bound.
3755 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003756 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
3757 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003758 continue;
3759 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003760
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003761 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003762 VkImageView image_view{VK_NULL_HANDLE};
3763
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003764 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02003765 if (!descriptor) {
3766 continue;
3767 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003768 switch (descriptor->GetClass()) {
3769 case cvdescriptorset::DescriptorClass::Image: {
3770 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
3771 image_view = image_descriptor->GetImageView();
3772 }
3773 break;
3774 }
3775 case cvdescriptorset::DescriptorClass::ImageSampler: {
3776 if (const auto image_sampler_descriptor =
3777 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
3778 image_view = image_sampler_descriptor->GetImageView();
3779 }
3780 break;
3781 }
3782 default:
3783 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003784 }
3785
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003786 if (image_view) {
3787 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
3788 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
3789 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003790 }
3791 }
3792 }
3793 }
3794}
3795
3796void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3797 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003798 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3799 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003800}
3801
3802void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3803 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003804 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3805 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003806}
3807
3808void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3809 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003810 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3811 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003812}
3813
Camden5b184be2019-08-13 07:50:19 -06003814bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003815 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06003816 bool skip = false;
3817
3818 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003819 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
3820 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
3821 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
3822 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06003823 }
3824
3825 return skip;
3826}
Camden83a9c372019-08-14 11:41:38 -06003827
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003828bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3829 bool skip = false;
3830 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3831 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003832 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003833 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3834 assert(cmd_state);
3835 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003836 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003837 return skip;
3838}
3839
3840bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3841 bool skip = false;
3842 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3843 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003844 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003845 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3846 assert(cmd_state);
3847 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003848 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003849 return skip;
3850}
3851
Sam Walls0961ec02020-03-31 16:39:15 +01003852bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3853 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01003854 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003855 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003856 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003857 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3858 assert(cmd_state);
3859 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003860 }
3861 return skip;
3862}
3863
3864bool BestPractices::PreCallValidateCmdEndRendering(VkCommandBuffer commandBuffer) const {
3865 bool skip = false;
3866 skip |= StateTracker::PreCallValidateCmdEndRendering(commandBuffer);
3867 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003868 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3869 assert(cmd_state);
3870 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003871 }
3872 return skip;
3873}
3874
3875bool BestPractices::PreCallValidateCmdEndRenderingKHR(VkCommandBuffer commandBuffer) const {
3876 bool skip = false;
3877 skip |= StateTracker::PreCallValidateCmdEndRenderingKHR(commandBuffer);
3878 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003879 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3880 assert(cmd_state);
3881 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003882 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003883 return skip;
3884}
3885
3886bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3887 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003888 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01003889
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003890 if (cmd == nullptr) return skip;
3891 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01003892
LawG4b21485c2022-02-28 13:46:48 +00003893 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
3894 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
3895 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
3896 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
3897 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
3898
3899 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01003900 bool uses_depth =
3901 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01003902 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00003903
Sam Walls0961ec02020-03-31 16:39:15 +01003904 if (uses_depth) {
3905 skip |= LogPerformanceWarning(
3906 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00003907 "%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 +00003908 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
3909 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
3910 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
3911 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01003912 }
3913
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003914 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
3915
LawG40da9c3d2022-03-01 09:51:01 +00003916 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003917 // If we use an attachment on-tile, we should access it in some way. Otherwise,
3918 // it is redundant to have it be part of the render pass.
3919 // Only consider it redundant if it will actually consume bandwidth, i.e.
3920 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
3921 // as is using pure input attachments.
3922 // CLEAR -> STORE might be considered a "useful" thing to do, but
3923 // the optimal thing to do is to defer the clear until you're actually
3924 // going to render to the image.
3925
3926 uint32_t num_attachments = rp->createInfo.attachmentCount;
3927 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02003928 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
3929 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003930 continue;
3931 }
3932
3933 auto& attachment = rp->createInfo.pAttachments[i];
3934
3935 VkImageAspectFlags bandwidth_aspects = 0;
3936
3937 if (!FormatIsStencilOnly(attachment.format) &&
3938 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3939 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3940 if (FormatHasDepth(attachment.format)) {
3941 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
3942 } else {
3943 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
3944 }
3945 }
3946
3947 if (FormatHasStencil(attachment.format) &&
3948 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3949 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3950 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
3951 }
3952
3953 if (!bandwidth_aspects) {
3954 continue;
3955 }
3956
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003957 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003958 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003959 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003960 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003961 untouched_aspects &= ~itr->aspects;
3962 }
3963
3964 if (untouched_aspects) {
3965 skip |= LogPerformanceWarning(
3966 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00003967 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003968 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00003969 "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 +00003970 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00003971 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003972 }
3973 }
3974 }
3975
Sam Walls0961ec02020-03-31 16:39:15 +01003976 return skip;
3977}
3978
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003979void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003980 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3981 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003982}
3983
3984void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003985 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3986 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003987}
3988
Camden Stocker9c051442019-11-06 14:28:43 -08003989bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
3990 const char* api_name) const {
3991 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003992 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08003993
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003994 if (bp_pd_state) {
3995 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
3996 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
3997 "Potential problem with calling %s() without first retrieving properties from "
3998 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
3999 api_name);
4000 }
Camden Stocker9c051442019-11-06 14:28:43 -08004001 }
4002
4003 return skip;
4004}
4005
Camden83a9c372019-08-14 11:41:38 -06004006bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004007 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06004008 bool skip = false;
4009
Camden Stocker9c051442019-11-06 14:28:43 -08004010 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06004011
Camden Stocker9c051442019-11-06 14:28:43 -08004012 return skip;
4013}
4014
4015bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
4016 uint32_t planeIndex,
4017 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
4018 bool skip = false;
4019
4020 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
4021
4022 return skip;
4023}
4024
4025bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
4026 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
4027 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
4028 bool skip = false;
4029
4030 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06004031
4032 return skip;
4033}
Camden05de2d42019-08-19 10:23:56 -06004034
4035bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004036 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06004037 bool skip = false;
4038
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004039 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06004040
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004041 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06004042 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004043 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004044 skip |=
4045 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
4046 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
4047 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06004048 }
Camden05de2d42019-08-19 10:23:56 -06004049
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004050 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
4051 skip |= LogWarning(
4052 device, kVUID_BestPractices_Swapchain_InvalidCount,
4053 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04004054 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004055 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
4056 }
4057 }
4058
Camden05de2d42019-08-19 10:23:56 -06004059 return skip;
4060}
4061
4062// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004063bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004064 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004065 const CALL_STATE call_state,
4066 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06004067 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004068 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
4069 if (UNCALLED == call_state) {
4070 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004071 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004072 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
4073 "recommended "
4074 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
4075 caller_name, caller_name);
4076 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004077 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
4078 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004079 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
4080 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
4081 ". It is recommended to instead receive all the properties by calling %s with "
4082 "pQueueFamilyPropertyCount that was "
4083 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004084 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004085 caller_name);
Camden05de2d42019-08-19 10:23:56 -06004086 }
4087
4088 return skip;
4089}
4090
Jeff Bolz5c801d12019-10-09 10:38:45 -05004091bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
4092 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06004093 bool skip = false;
4094
4095 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004096 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06004097 if (!as_state->memory_requirements_checked) {
4098 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
4099 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
4100 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004101 skip |= LogWarning(
4102 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06004103 "vkBindAccelerationStructureMemoryNV(): "
4104 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
4105 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
4106 }
4107 }
4108
4109 return skip;
4110}
4111
Camden05de2d42019-08-19 10:23:56 -06004112bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
4113 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004114 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004115 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004116 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004117 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004118 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
4119 "vkGetPhysicalDeviceQueueFamilyProperties()");
4120 }
4121 return false;
Camden05de2d42019-08-19 10:23:56 -06004122}
4123
Mike Schuchardt2df08912020-12-15 16:28:09 -08004124bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
4125 uint32_t* pQueueFamilyPropertyCount,
4126 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004127 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004128 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004129 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004130 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
4131 "vkGetPhysicalDeviceQueueFamilyProperties2()");
4132 }
4133 return false;
Camden05de2d42019-08-19 10:23:56 -06004134}
4135
Jeff Bolz5c801d12019-10-09 10:38:45 -05004136bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08004137 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004138 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004139 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004140 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004141 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
4142 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
4143 }
4144 return false;
Camden05de2d42019-08-19 10:23:56 -06004145}
4146
4147bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
4148 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004149 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06004150 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004151 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06004152 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06004153 bool skip = false;
4154 if (call_state == UNCALLED) {
4155 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
4156 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004157 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
4158 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
4159 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06004160 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004161 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004162 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
4163 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
4164 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
4165 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004166 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06004167 }
4168 }
4169 return skip;
4170}
Camden Stocker23cc47d2019-09-03 14:53:57 -06004171
4172bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004173 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004174 bool skip = false;
4175
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004176 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4177 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06004178 // 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 -07004179 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004180 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
4181 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07004182 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06004183 // 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 -07004184 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
4185 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004186 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004187 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004188 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004189 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004190 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004191 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4192 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4193 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004194 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004195 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4196 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004197 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004198 }
4199 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004200 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004201 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004202 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004203 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4204 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004205 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004206 }
4207 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004208 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4209 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004210 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004211 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004212 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004213 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004214 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004215 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4216 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4217 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004218 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004219 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4220 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004221 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004222 }
4223 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004224 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004225 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004226 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004227 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4228 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004229 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004230 }
4231 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4232 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004233 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004234 }
4235 }
4236 }
4237 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004238 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
4239 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004240 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004241 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004242 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
4243 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004244 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004245 }
4246 }
4247 }
4248
Rodrigo Locatti7ab778d2022-03-09 18:57:15 -03004249 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4250 auto queue_state = Get<QUEUE_STATE>(queue);
4251 if (queue_state && queue_state->queueFamilyProperties.queueFlags != (VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT)) {
4252 skip |= LogPerformanceWarning(queue, kVUID_BestPractices_QueueBindSparse_NotAsync,
4253 "vkQueueBindSparse() issued on queue %s. All binds should happen on an asynchronous copy "
4254 "queue to hide the OS scheduling and submit costs.",
4255 report_data->FormatHandle(queue).c_str());
4256 }
4257 }
4258
Camden Stocker23cc47d2019-09-03 14:53:57 -06004259 return skip;
4260}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004261
Mark Lobodzinski84101d72020-04-24 09:43:48 -06004262void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
4263 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004264 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004265 return;
4266 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004267
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004268 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4269 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
4270 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4271 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004272 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004273 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004274 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004275 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004276 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4277 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
4278 image_state->sparse_metadata_bound = true;
4279 }
4280 }
4281 }
4282 }
4283}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004284
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004285bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004286 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004287 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004288 // We don't know the accurate render area in a secondary,
4289 // so assume we clear the entire frame buffer.
4290 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
4291 return true;
4292 }
4293
4294 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
4295 for (uint32_t i = 0; i < rectCount; i++) {
4296 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004297 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004298 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
4299 return true;
4300 }
4301 }
4302
4303 return false;
4304}
4305
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004306bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
4307 VkImageAspectFlags aspects, bool secondary) const {
4308 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004309 bool skip = false;
4310
4311 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
4312 return skip;
4313 }
4314
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004315 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004316
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004317 auto attachment_itr =
4318 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
4319 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004320
4321 // Only report aspects which haven't been touched yet.
4322 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004323 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004324 new_aspects &= ~attachment_itr->aspects;
4325 }
4326
4327 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09004328 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004329 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004330 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02004331 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
4332 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004333 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004334 }
4335
4336 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
4337 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
4338 skip |= LogPerformanceWarning(
4339 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4340 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
4341 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4342 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004343 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004344 }
4345
4346 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4347 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004348 skip |=
4349 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4350 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
4351 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4352 "it is more efficient.",
4353 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004354
4355 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004356 const auto cmd_state = GetRead<bp_state::CommandBuffer>(cmd.commandBuffer());
4357 assert(cmd_state);
4358 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004359 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004360 }
4361
4362 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
4363 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004364 skip |=
4365 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4366 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
4367 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4368 "it is more efficient.",
4369 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004370 }
4371
4372 return skip;
4373}
4374
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004375bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06004376 const VkClearAttachment* pAttachments, uint32_t rectCount,
4377 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004378 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004379 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004380 if (!cb_node) return skip;
4381
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004382 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
4383 // Defer checks to ExecuteCommands.
4384 return skip;
4385 }
4386
4387 // Only care about full clears, partial clears might have legitimate uses.
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004388 const bool is_full_clear = ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004389
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004390 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
4391 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06004392 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004393 if (rp) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004394 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004395 const auto pColorAttachments = rp->dynamic_rendering_begin_rendering_info.pColorAttachments;
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004396
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004397 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4398 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004399 const auto& attachment = pAttachments[i];
4400 if (attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004401 skip |= ValidateZcullScope(*cb_node);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004402 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004403 if ((attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) && attachment.colorAttachment != VK_ATTACHMENT_UNUSED) {
4404 const auto& color_attachment = pColorAttachments[attachment.colorAttachment];
4405 if (color_attachment.imageView) {
4406 auto image_view_state = Get<IMAGE_VIEW_STATE>(color_attachment.imageView);
4407 const VkFormat format = image_view_state->create_info.format;
4408 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4409 }
4410 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004411 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004412 }
4413
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004414 if (is_full_clear) {
4415 // TODO: Implement ValidateClearAttachment for dynamic rendering
4416 }
4417
4418 } else {
4419 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
4420
4421 if (is_full_clear) {
4422 for (uint32_t i = 0; i < attachmentCount; i++) {
4423 const auto& attachment = pAttachments[i];
4424
4425 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4426 uint32_t color_attachment = attachment.colorAttachment;
4427 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
4428 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
4429 }
4430
4431 if (subpass.pDepthStencilAttachment &&
4432 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
4433 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
4434 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
4435 }
4436 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004437 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004438 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp->createInfo.pAttachments) {
4439 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; ++attachment_idx) {
4440 const auto& attachment = pAttachments[attachment_idx];
4441
4442 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4443 const uint32_t fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
4444 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
4445 const VkFormat format = rp->createInfo.pAttachments[fb_attachment].format;
4446 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4447 }
4448 }
4449 }
4450 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004451 }
4452 }
4453
Nadav Gevaf0808442021-05-21 13:51:25 -04004454 if (VendorCheckEnabled(kBPVendorAMD)) {
4455 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
4456 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
4457 bool black_check = false;
4458 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
4459 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
4460 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
4461 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4462 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4463
4464 bool white_check = false;
4465 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
4466 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
4467 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
4468 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4469 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4470
4471 if (black_check && white_check) {
4472 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4473 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
4474 "Consider changing to one of the following:"
4475 "RGBA(0, 0, 0, 0) "
4476 "RGBA(0, 0, 0, 1) "
4477 "RGBA(1, 1, 1, 0) "
4478 "RGBA(1, 1, 1, 1)",
4479 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4480 }
4481 } else {
4482 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
4483 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
4484 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
4485 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4486 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
4487 "attachment %" PRId32 " is not a fast clear value."
4488 "Consider changing to one of the following:"
4489 "D=0.0f, S=0"
4490 "D=1.0f, S=0",
4491 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4492 }
4493 }
4494 }
4495 }
4496
Camden Stockerf55721f2019-09-09 11:04:49 -06004497 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004498}
Attilio Provenzano02859b22020-02-27 14:17:28 +00004499
4500bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4501 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4502 const VkImageResolve* pRegions) const {
4503 bool skip = false;
4504
4505 skip |= VendorCheckEnabled(kBPVendorArm) &&
4506 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
4507 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
4508 "This is a very slow and extremely bandwidth intensive path. "
4509 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4510 VendorSpecificTag(kBPVendorArm));
4511
4512 return skip;
4513}
4514
Jeff Leger178b1e52020-10-05 12:22:23 -04004515bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4516 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
4517 bool skip = false;
4518
4519 skip |= VendorCheckEnabled(kBPVendorArm) &&
4520 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
4521 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
4522 "This is a very slow and extremely bandwidth intensive path. "
4523 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4524 VendorSpecificTag(kBPVendorArm));
4525
4526 return skip;
4527}
4528
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004529bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
4530 const VkResolveImageInfo2* pResolveImageInfo) const {
4531 bool skip = false;
4532
4533 skip |= VendorCheckEnabled(kBPVendorArm) &&
4534 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
4535 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
4536 "This is a very slow and extremely bandwidth intensive path. "
4537 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4538 VendorSpecificTag(kBPVendorArm));
4539
4540 return skip;
4541}
4542
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004543void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4544 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4545 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004546 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004547 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004548 auto src = Get<bp_state::Image>(srcImage);
4549 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004550
4551 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004552 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
4553 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004554 }
4555}
4556
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004557void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4558 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004559 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004560 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004561 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4562 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004563 uint32_t regionCount = pResolveImageInfo->regionCount;
4564
4565 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004566 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
4567 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004568 }
4569}
4570
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004571void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
4572 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004573 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004574 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004575 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4576 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004577 uint32_t regionCount = pResolveImageInfo->regionCount;
4578
4579 for (uint32_t i = 0; i < regionCount; i++) {
4580 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
4581 pResolveImageInfo->pRegions[i].srcSubresource);
4582 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
4583 pResolveImageInfo->pRegions[i].dstSubresource);
4584 }
4585}
4586
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004587void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4588 const VkClearColorValue* pColor, uint32_t rangeCount,
4589 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004590 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004591 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004592 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004593
4594 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004595 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004596 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004597
4598 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4599 RecordClearColor(dst->createInfo.format, *pColor);
4600 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004601}
4602
4603void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4604 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4605 const VkImageSubresourceRange* pRanges) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004606 ValidationStateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount,
4607 pRanges);
4608
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004609 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004610 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004611 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004612
4613 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004614 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004615 }
Rodrigo Locatti6c4c2662022-08-18 14:20:04 -03004616 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4617 for (uint32_t i = 0; i < rangeCount; i++) {
4618 RecordResetZcullDirection(*cb, image, pRanges[i]);
4619 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004620 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004621}
4622
4623void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4624 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4625 const VkImageCopy* pRegions) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004626 ValidationStateTracker::PreCallRecordCmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
4627 regionCount, pRegions);
4628
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004629 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004630 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004631 auto src = Get<bp_state::Image>(srcImage);
4632 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004633
4634 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004635 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
4636 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004637 }
4638}
4639
4640void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4641 VkImageLayout dstImageLayout, uint32_t regionCount,
4642 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004643 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004644 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004645 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004646
4647 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004648 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004649 }
4650}
4651
4652void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4653 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004654 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004655 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004656 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004657
4658 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004659 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004660 }
4661}
4662
4663void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4664 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4665 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004666 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004667 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004668 auto src = Get<bp_state::Image>(srcImage);
4669 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004670
4671 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004672 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
4673 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004674 }
4675}
4676
Attilio Provenzano02859b22020-02-27 14:17:28 +00004677bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
4678 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
4679 bool skip = false;
4680
4681 if (VendorCheckEnabled(kBPVendorArm)) {
4682 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
4683 skip |= LogPerformanceWarning(
4684 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
4685 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
4686 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
4687 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06004688 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00004689 }
4690
4691 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
4692 skip |= LogPerformanceWarning(
4693 device, kVUID_BestPractices_CreateSampler_LodClamping,
4694 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
4695 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
4696 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
4697 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
4698 }
4699
4700 if (pCreateInfo->mipLodBias != 0.0f) {
4701 skip |=
4702 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
4703 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
4704 "descriptors being created and may cause reduced performance.",
4705 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
4706 }
4707
4708 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4709 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4710 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
4711 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
4712 skip |= LogPerformanceWarning(
4713 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
4714 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
4715 "This will lead to less efficient descriptors being created and may cause reduced performance. "
4716 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
4717 VendorSpecificTag(kBPVendorArm));
4718 }
4719
4720 if (pCreateInfo->unnormalizedCoordinates) {
4721 skip |= LogPerformanceWarning(
4722 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
4723 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
4724 "descriptors being created and may cause reduced performance.",
4725 VendorSpecificTag(kBPVendorArm));
4726 }
4727
4728 if (pCreateInfo->anisotropyEnable) {
4729 skip |= LogPerformanceWarning(
4730 device, kVUID_BestPractices_CreateSampler_Anisotropy,
4731 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
4732 "and may cause reduced performance.",
4733 VendorSpecificTag(kBPVendorArm));
4734 }
4735 }
4736
4737 return skip;
4738}
Sam Walls8e77e4f2020-03-16 20:47:40 +00004739
Nadav Gevaf0808442021-05-21 13:51:25 -04004740void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
4741 const VkGraphicsPipelineCreateInfo* pCreateInfos,
4742 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
4743 void* cgpl_state) {
4744 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
4745 pPipelines);
4746 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004747 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004748}
4749
4750bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
4751 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
4752 const VkCopyDescriptorSet* pDescriptorCopies) const {
4753 bool skip = false;
4754 if (VendorCheckEnabled(kBPVendorAMD)) {
4755 if (descriptorCopyCount > 0) {
4756 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
4757 "%s Performance warning: copying descriptor sets is not recommended",
4758 VendorSpecificTag(kBPVendorAMD));
4759 }
4760 }
4761
4762 return skip;
4763}
4764
4765bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
4766 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
4767 const VkAllocationCallbacks* pAllocator,
4768 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
4769 bool skip = false;
4770 if (VendorCheckEnabled(kBPVendorAMD)) {
4771 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
4772 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
4773 "vkUpdateDescriptorSet instead",
4774 VendorSpecificTag(kBPVendorAMD));
4775 }
4776
4777 return skip;
4778}
4779
4780bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4781 const VkClearColorValue* pColor, uint32_t rangeCount,
4782 const VkImageSubresourceRange* pRanges) const {
4783 bool skip = false;
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004784
4785 auto dst = Get<bp_state::Image>(image);
4786
Nadav Gevaf0808442021-05-21 13:51:25 -04004787 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08004788 skip |= LogPerformanceWarning(
4789 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04004790 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4791 "vkCmdClearAttachments instead",
4792 VendorSpecificTag(kBPVendorAMD));
4793 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004794 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4795 skip |= ValidateClearColor(commandBuffer, dst->createInfo.format, *pColor);
4796 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004797
4798 return skip;
4799}
4800
4801bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4802 VkImageLayout imageLayout,
4803 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4804 const VkImageSubresourceRange* pRanges) const {
4805 bool skip = false;
4806 if (VendorCheckEnabled(kBPVendorAMD)) {
4807 skip |= LogPerformanceWarning(
4808 device, kVUID_BestPractices_ClearAttachment_ClearImage,
4809 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4810 "vkCmdClearAttachments instead",
4811 VendorSpecificTag(kBPVendorAMD));
4812 }
Mark Young0a6b48f2022-08-18 11:17:02 -06004813 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
4814 assert(cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004815 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4816 for (uint32_t i = 0; i < rangeCount; i++) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004817 skip |= ValidateZcull(*cmd_state, image, pRanges[i]);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004818 }
4819 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004820
4821 return skip;
4822}
4823
4824bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
4825 const VkAllocationCallbacks* pAllocator,
4826 VkPipelineLayout* pPipelineLayout) const {
4827 bool skip = false;
4828 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004829 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04004830 // Descriptor sets cost 1 DWORD each.
4831 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
4832 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
4833 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
4834 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
4835 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004836 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004837 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04004838 }
4839
4840 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
4841 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
4842 }
4843
4844 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
4845 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
4846 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
4847 "Descriptor sets cost 1 DWORD each. "
4848 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
4849 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
4850 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
4851 VendorSpecificTag(kBPVendorAMD));
4852 }
4853 }
4854
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004855 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4856 bool has_separate_sampler = false;
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004857 size_t fast_space_usage = 0;
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004858
4859 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) {
4860 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
4861 for (const auto& binding : descriptor_set_layout_state->GetBindings()) {
4862 if (binding.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) {
4863 has_separate_sampler = true;
4864 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004865
4866 if ((descriptor_set_layout_state->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) == 0U) {
4867 size_t descriptor_type_size = 0;
4868
4869 switch (binding.descriptorType) {
4870 case VK_DESCRIPTOR_TYPE_SAMPLER:
4871 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
4872 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
4873 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
4874 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
4875 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
4876 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
4877 descriptor_type_size = 4;
4878 break;
4879 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
4880 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
4881 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR:
4882 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV:
4883 descriptor_type_size = 8;
4884 break;
4885 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
4886 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
4887 case VK_DESCRIPTOR_TYPE_MUTABLE_VALVE:
4888 descriptor_type_size = 16;
4889 break;
4890 case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK:
4891 descriptor_type_size = 1;
4892 default:
4893 // Unknown type.
4894 break;
4895 }
4896
4897 size_t descriptor_size = descriptor_type_size * binding.descriptorCount;
4898 fast_space_usage += descriptor_size;
4899 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004900 }
4901 }
4902
4903 if (has_separate_sampler) {
4904 skip |= LogPerformanceWarning(
4905 device, kVUID_BestPractices_CreatePipelineLayout_SeparateSampler,
4906 "%s Consider using combined image samplers instead of separate samplers for marginally better performance.",
4907 VendorSpecificTag(kBPVendorNVIDIA));
4908 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004909
4910 if (fast_space_usage > kPipelineLayoutFastDescriptorSpaceNVIDIA) {
4911 skip |= LogPerformanceWarning(
4912 device, kVUID_BestPractices_CreatePipelinesLayout_LargePipelineLayout,
4913 "%s Pipeline layout size is too large, prefer using pipeline-specific descriptor set layouts. "
4914 "Aim for consuming less than %" PRIu32 " bytes to allow fast reads for all non-bindless descriptors. "
4915 "Samplers, textures, texel buffers, and combined image samplers consume 4 bytes each. "
4916 "Uniform buffers and acceleration structures consume 8 bytes. "
4917 "Storage buffers consume 16 bytes. "
4918 "Push constants do not consume space.",
4919 VendorSpecificTag(kBPVendorNVIDIA), kPipelineLayoutFastDescriptorSpaceNVIDIA);
4920 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004921 }
4922
Nadav Gevaf0808442021-05-21 13:51:25 -04004923 return skip;
4924}
4925
4926bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4927 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4928 const VkImageCopy* pRegions) const {
4929 bool skip = false;
4930 std::stringstream src_image_hex;
4931 std::stringstream dst_image_hex;
4932 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
4933 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
4934
4935 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004936 auto src_state = Get<IMAGE_STATE>(srcImage);
4937 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04004938
4939 if (src_state && dst_state) {
4940 VkImageTiling src_Tiling = src_state->createInfo.tiling;
4941 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
4942 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
4943 skip |=
4944 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
4945 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
4946 "image (vkCmdCopyImageToBuffer) "
4947 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
4948 "copies when converting between linear and optimal images",
4949 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
4950 }
4951 }
4952 }
4953
4954 return skip;
4955}
4956
4957bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
4958 VkPipeline pipeline) const {
4959 bool skip = false;
4960
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004961 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
4962
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004963 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004964 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04004965 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004966 "%s %s Performance warning: Pipeline %s was bound twice in the frame. "
4967 "Keep pipeline state changes to a minimum, for example, by sorting draw calls by pipeline.",
4968 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA),
4969 report_data->FormatHandle(pipeline).c_str());
Nadav Gevaf0808442021-05-21 13:51:25 -04004970 }
4971 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004972 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4973 const auto& tgm = cb->nv.tess_geometry_mesh;
4974 if (tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA && !tgm.threshold_signaled) {
4975 LogPerformanceWarning(commandBuffer, kVUID_BestPractices_BindPipeline_SwitchTessGeometryMesh,
4976 "%s Avoid switching between pipelines with and without tessellation, geometry, task, "
4977 "and/or mesh shaders. Group draw calls using these shader stages together.",
4978 VendorSpecificTag(kBPVendorNVIDIA));
4979 // Do not set 'skip' so the number of switches gets properly counted after the message.
4980 }
4981 }
4982
Nadav Gevaf0808442021-05-21 13:51:25 -04004983 return skip;
4984}
4985
4986void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
4987 VkFence fence, VkResult result) {
4988 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004989 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004990}
4991
4992bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
4993 bool skip = false;
4994
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004995 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004996 auto num = num_queue_submissions_.load();
4997 if (num > kNumberOfSubmissionWarningLimitAMD) {
4998 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004999 "%s %s Performance warning: command buffers submitted %" PRId32
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005000 " times this frame. Submitting command buffers has a CPU "
5001 "and GPU overhead. Submit fewer times to incur less overhead.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005002 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04005003 }
5004 }
5005
5006 return skip;
5007}
5008
5009void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
5010 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
5011 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
5012 uint32_t bufferMemoryBarrierCount,
5013 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
5014 uint32_t imageMemoryBarrierCount,
5015 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03005016 ValidationStateTracker::PostCallRecordCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags,
5017 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5018 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
5019
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005020 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03005021
5022 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
5023 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
5024 }
5025}
5026
5027void BestPractices::PostCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
5028 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2(commandBuffer, pDependencyInfo);
5029
5030 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
5031 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5032 }
5033}
5034
5035void BestPractices::PostCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
5036 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2KHR(commandBuffer, pDependencyInfo);
5037
5038 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
5039 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5040 }
5041}
5042
5043template <typename ImageMemoryBarrier>
5044void BestPractices::RecordCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer, const ImageMemoryBarrier& barrier) {
5045 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
5046 assert(cb);
5047
5048 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
5049 RecordResetZcullDirection(*cb, barrier.image, barrier.subresourceRange);
5050 }
Nadav Gevaf0808442021-05-21 13:51:25 -04005051}
5052
5053bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
5054 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
5055 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005056 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005057 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005058 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005059 "%s %s Performance warning: High number of vkSemaphore objects created. "
Nadav Gevaf0808442021-05-21 13:51:25 -04005060 "Minimize the amount of queue synchronization that is used. "
5061 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005062 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005063 }
5064 }
5065
5066 return skip;
5067}
5068
5069bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
5070 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
5071 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005072 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005073 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005074 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005075 "%s %s Performance warning: High number of VkFence objects created."
Nadav Gevaf0808442021-05-21 13:51:25 -04005076 "Minimize the amount of CPU-GPU synchronization that is used. "
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005077 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
5078 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005079 }
5080 }
5081
5082 return skip;
5083}
5084
Sam Walls8e77e4f2020-03-16 20:47:40 +00005085void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
5086
5087bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
5088 // look for a cache hit
5089 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
5090 if (hit != _entries.end()) {
5091 // mark the cache hit as being most recently used
5092 hit->age = iteration++;
5093 return true;
5094 }
5095
5096 // if there's no cache hit, we need to model the entry being inserted into the cache
5097 CacheEntry new_entry = {value, iteration};
5098 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
5099 // if there is still space left in the cache, use the next available slot
5100 *(_entries.begin() + iteration) = new_entry;
5101 } else {
5102 // otherwise replace the least recently used cache entry
5103 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
5104 *lru = new_entry;
5105 }
5106 iteration++;
5107 return false;
5108}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005109
5110bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
5111 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005112 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005113 bool skip = false;
5114 if (swapchain_data && swapchain_data->images.size() == 0) {
5115 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
5116 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
5117 "vkGetSwapchainImagesKHR after swapchain creation.");
5118 }
5119 return skip;
5120}
5121
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005122void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
5123 if (no_pointer) {
5124 if (UNCALLED == call_state) {
5125 call_state = QUERY_COUNT;
5126 }
5127 } else { // Save queue family properties
5128 call_state = QUERY_DETAILS;
5129 }
5130}
5131
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005132void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
5133 uint32_t* pQueueFamilyPropertyCount,
5134 VkQueueFamilyProperties* pQueueFamilyProperties) {
5135 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
5136 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005137 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005138 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005139 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
5140 nullptr == pQueueFamilyProperties);
5141 }
5142}
5143
5144void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
5145 uint32_t* pQueueFamilyPropertyCount,
5146 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5147 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
5148 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005149 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005150 if (bp_pd_state) {
5151 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
5152 nullptr == pQueueFamilyProperties);
5153 }
5154}
5155
5156void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
5157 uint32_t* pQueueFamilyPropertyCount,
5158 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5159 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
5160 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005161 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005162 if (bp_pd_state) {
5163 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
5164 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005165 }
5166}
5167
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005168void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
5169 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005170 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005171 if (bp_pd_state) {
5172 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5173 }
5174}
5175
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005176void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
5177 VkPhysicalDeviceFeatures2* pFeatures) {
5178 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005179 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005180 if (bp_pd_state) {
5181 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5182 }
5183}
5184
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005185void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
5186 VkPhysicalDeviceFeatures2* pFeatures) {
5187 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005188 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005189 if (bp_pd_state) {
5190 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5191 }
5192}
5193
5194void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
5195 VkSurfaceKHR surface,
5196 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
5197 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005198 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005199 if (bp_pd_state) {
5200 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5201 }
5202}
5203
5204void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
5205 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5206 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005207 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005208 if (bp_pd_state) {
5209 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5210 }
5211}
5212
5213void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
5214 VkSurfaceKHR surface,
5215 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
5216 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005217 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005218 if (bp_pd_state) {
5219 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5220 }
5221}
5222
5223void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
5224 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
5225 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005226 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005227 if (bp_pd_data) {
5228 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
5229
5230 if (*pPresentModeCount) {
5231 if (call_state < QUERY_COUNT) {
5232 call_state = QUERY_COUNT;
5233 }
5234 }
5235 if (pPresentModes) {
5236 if (call_state < QUERY_DETAILS) {
5237 call_state = QUERY_DETAILS;
5238 }
5239 }
5240 }
5241}
5242
5243void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
5244 uint32_t* pSurfaceFormatCount,
5245 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005246 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005247 if (bp_pd_data) {
5248 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
5249
5250 if (*pSurfaceFormatCount) {
5251 if (call_state < QUERY_COUNT) {
5252 call_state = QUERY_COUNT;
5253 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005254 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005255 }
5256 if (pSurfaceFormats) {
5257 if (call_state < QUERY_DETAILS) {
5258 call_state = QUERY_DETAILS;
5259 }
5260 }
5261 }
5262}
5263
5264void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
5265 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5266 uint32_t* pSurfaceFormatCount,
5267 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005268 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005269 if (bp_pd_data) {
5270 if (*pSurfaceFormatCount) {
5271 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
5272 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
5273 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005274 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005275 }
5276 if (pSurfaceFormats) {
5277 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
5278 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
5279 }
5280 }
5281 }
5282}
5283
5284void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
5285 uint32_t* pPropertyCount,
5286 VkDisplayPlanePropertiesKHR* pProperties,
5287 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005288 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005289 if (bp_pd_data) {
5290 if (*pPropertyCount) {
5291 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
5292 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
5293 }
5294 }
5295 if (pProperties) {
5296 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
5297 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
5298 }
5299 }
5300 }
5301}
5302
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005303void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
5304 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
5305 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005306 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06005307 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
5308 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
5309 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005310 }
5311 }
5312}
5313
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005314void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
5315 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
5316
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06005317 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005318 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02005319 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005320 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005321 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005322 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07005323 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005324 }
Rodrigo Locattic789fe82022-07-06 17:42:19 -03005325 cb->num_submits++;
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005326 }
5327 }
5328}