blob: be7daed63c33fd94cb39518a028099cdc61b28c8 [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
268 if (white_list(extension_name, kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800269 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700270 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300271 extension_name);
Camden5b184be2019-08-13 07:50:19 -0600272 }
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300273
274 skip |= ValidateDeprecatedExtensions("CreateDevice", extension_name, api_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700275 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300276 skip |= ValidateSpecialUseExtensions("CreateDevice", extension_name, kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600277 }
278
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700279 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600280 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700281 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
282 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600283 }
284
LawG43f848c72022-02-23 09:35:21 +0000285 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorIMG)) &&
286 (pCreateInfo->pEnabledFeatures != nullptr) && (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
Szilard Papp7d2c7952020-06-22 14:38:13 +0100287 skip |= LogPerformanceWarning(
288 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
LawG4015be1c2022-03-01 10:37:52 +0000289 "%s %s %s: vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
Szilard Papp7d2c7952020-06-22 14:38:13 +0100290 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
291 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
292 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
LawG43f848c72022-02-23 09:35:21 +0000293 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorIMG));
Szilard Papp7d2c7952020-06-22 14:38:13 +0100294 }
295
Rodrigo Locatti8dde2ff2022-03-01 18:06:08 -0300296 const bool enabled_pageable_device_local_memory = IsExtEnabled(device_extensions.vk_ext_pageable_device_local_memory);
297 if (VendorCheckEnabled(kBPVendorNVIDIA) && !enabled_pageable_device_local_memory &&
298 std::find(extensions.begin(), extensions.end(), VK_EXT_PAGEABLE_DEVICE_LOCAL_MEMORY_EXTENSION_NAME) != extensions.end()) {
299 skip |= LogPerformanceWarning(
300 device, kVUID_BestPractices_CreateDevice_PageableDeviceLocalMemory,
301 "%s vkCreateDevice() called without pageable device local memory. "
302 "Use pageableDeviceLocalMemory from VK_EXT_pageable_device_local_memory when it is available.",
303 VendorSpecificTag(kBPVendorNVIDIA));
304 }
305
Camden5b184be2019-08-13 07:50:19 -0600306 return skip;
307}
308
309bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500310 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600311 bool skip = false;
312
313 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700314 std::stringstream buffer_hex;
315 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600316
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700317 skip |= LogWarning(
318 device, kVUID_BestPractices_SharingModeExclusive,
319 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
320 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700321 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600322 }
323
324 return skip;
325}
326
327bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500328 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600329 bool skip = false;
330
331 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700332 std::stringstream image_hex;
333 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600334
335 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700336 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
337 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
338 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700339 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600340 }
341
ziga-lunarg6df3d102022-03-18 17:02:14 +0100342 if ((pCreateInfo->flags & VK_IMAGE_CREATE_EXTENDED_USAGE_BIT) && !(pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
343 skip |= LogWarning(device, kVUID_BestPractices_ImageCreateFlags,
344 "vkCreateImage(): pCreateInfo->flags has VK_IMAGE_CREATE_EXTENDED_USAGE_BIT set, but not "
345 "VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, therefore image views created from this image will have to use the "
346 "same format and VK_IMAGE_CREATE_EXTENDED_USAGE_BIT will not have any effect.");
347 }
348
LawG4655f59c2022-02-23 13:55:55 +0000349 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000350 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
351 skip |= LogPerformanceWarning(
352 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
LawG4655f59c2022-02-23 13:55:55 +0000353 "%s %s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
Attilio Provenzano02859b22020-02-27 14:17:28 +0000354 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
355 "and do not need to be backed by physical storage. "
356 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
LawG4655f59c2022-02-23 13:55:55 +0000357 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Attilio Provenzano02859b22020-02-27 14:17:28 +0000358 }
359 }
360
LawG4ba113892022-02-23 14:39:02 +0000361 if (VendorCheckEnabled(kBPVendorArm) && pCreateInfo->samples > kMaxEfficientSamplesArm) {
362 skip |= LogPerformanceWarning(
363 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
364 "%s vkCreateImage(): Trying to create an image with %u samples. "
365 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
366 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
367 }
368
369 if (VendorCheckEnabled(kBPVendorIMG) && pCreateInfo->samples > kMaxEfficientSamplesImg) {
370 skip |= LogPerformanceWarning(
371 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
372 "%s vkCreateImage(): Trying to create an image with %u samples. "
373 "The device may not have full support for true multisampling for images with more than %u samples. "
374 "XT devices support up to 8 samples, XE up to 4 samples.",
375 VendorSpecificTag(kBPVendorIMG), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesImg);
376 }
377
LawG4db16f802022-03-21 17:33:39 +0000378 if (VendorCheckEnabled(kBPVendorIMG) && (pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG ||
379 pCreateInfo->format == VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG ||
380 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG ||
381 pCreateInfo->format == VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG ||
382 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG ||
383 pCreateInfo->format == VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG ||
384 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG ||
385 pCreateInfo->format == VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG)) {
386 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Texture_Format_PVRTC_Outdated,
387 "%s vkCreateImage(): Trying to create an image with a PVRTC format. Both PVRTC1 and PVRTC2 "
388 "are slower than standard image formats on PowerVR GPUs, prefer ETC, BC, ASTC, etc.",
389 VendorSpecificTag(kBPVendorIMG));
390 }
391
Nadav Gevaf0808442021-05-21 13:51:25 -0400392 if (VendorCheckEnabled(kBPVendorAMD)) {
393 std::stringstream image_hex;
394 image_hex << "0x" << std::hex << HandleToUint64(pImage);
395
396 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
397 (pCreateInfo->sharingMode == VK_SHARING_MODE_CONCURRENT)) {
398 skip |= LogPerformanceWarning(device,
399 kVUID_BestPractices_vkImage_AvoidConcurrentRenderTargets,
400 "%s Performance warning: image (%s) is created as a render target with VK_SHARING_MODE_CONCURRENT. "
401 "Using a SHARING_MODE_CONCURRENT "
402 "is not recommended with color and depth targets",
403 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
404 }
405
406 if ((pCreateInfo->usage &
407 (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
408 (pCreateInfo->flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) {
409 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseMutableRenderTargets,
410 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. "
411 "Using a MUTABLE_FORMAT is not recommended with color, depth, and storage targets",
412 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
413 }
414
415 if ((pCreateInfo->usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) &&
416 (pCreateInfo->usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
417 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_DontUseStorageRenderTargets,
418 "%s Performance warning: image (%s) is created as a render target with VK_IMAGE_USAGE_STORAGE_BIT. Using a "
419 "VK_IMAGE_USAGE_STORAGE_BIT is not recommended with color and depth targets",
420 VendorSpecificTag(kBPVendorAMD), image_hex.str().c_str());
421 }
422 }
423
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300424 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
425 std::stringstream image_hex;
426 image_hex << "0x" << std::hex << HandleToUint64(pImage);
427
428 if (pCreateInfo->tiling == VK_IMAGE_TILING_LINEAR) {
429 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateImage_TilingLinear,
430 "%s Performance warning: image (%s) is created with tiling VK_IMAGE_TILING_LINEAR. "
431 "Use VK_IMAGE_TILING_OPTIMAL instead.",
432 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
433 }
Rodrigo Locatti3290c2b2022-03-09 18:25:56 -0300434
435 if (pCreateInfo->format == VK_FORMAT_D32_SFLOAT || pCreateInfo->format == VK_FORMAT_D32_SFLOAT_S8_UINT) {
436 skip |= LogPerformanceWarning(
437 device, kVUID_BestPractices_CreateImage_Depth32Format,
438 "%s Performance warning: image (%s) is created with a 32-bit depth format. Use VK_FORMAT_D24_UNORM_S8_UINT or "
439 "VK_FORMAT_D16_UNORM instead, unless the extra precision is needed.",
440 VendorSpecificTag(kBPVendorNVIDIA), image_hex.str().c_str());
441 }
Rodrigo Locatti5466f9d2022-03-09 18:20:38 -0300442 }
443
Camden5b184be2019-08-13 07:50:19 -0600444 return skip;
445}
446
447bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500448 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600449 bool skip = false;
450
Jeremy Gebben383b9a32021-09-08 16:31:33 -0600451 const auto* bp_pd_state = GetPhysicalDeviceState();
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600452 if (bp_pd_state) {
453 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
454 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
455 "vkCreateSwapchainKHR() called before getting surface capabilities from "
456 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
457 }
Camden83a9c372019-08-14 11:41:38 -0600458
Shannon McPherson73e58c82021-03-05 17:14:26 -0700459 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
460 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600461 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
462 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
463 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
464 }
Camden83a9c372019-08-14 11:41:38 -0600465
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600466 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
467 skip |= LogWarning(
468 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
469 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
470 }
Camden83a9c372019-08-14 11:41:38 -0600471 }
472
Camden5b184be2019-08-13 07:50:19 -0600473 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700474 skip |=
475 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600476 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700477 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
478 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600479 }
480
ziga-lunarg79beba62022-03-30 01:17:30 +0200481 const auto present_mode = pCreateInfo->presentMode;
482 if (((present_mode == VK_PRESENT_MODE_MAILBOX_KHR) || (present_mode == VK_PRESENT_MODE_FIFO_KHR)) &&
483 (pCreateInfo->minImageCount == 2)) {
Szilard Papp48a6da32020-06-10 14:41:59 +0100484 skip |= LogPerformanceWarning(
485 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
486 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
487 ", which means double buffering is going "
488 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
489 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
490 "3 to use triple buffering to maximize performance in such cases.",
491 pCreateInfo->minImageCount);
492 }
493
Szilard Pappd5f0f812020-06-22 09:01:29 +0100494 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
495 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
496 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
497 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
498 "Presentation modes which are not FIFO will present the latest available frame and discard other "
499 "frame(s) if any.",
500 VendorSpecificTag(kBPVendorArm));
501 }
502
Camden5b184be2019-08-13 07:50:19 -0600503 return skip;
504}
505
506bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
507 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500508 const VkAllocationCallbacks* pAllocator,
509 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600510 bool skip = false;
511
512 for (uint32_t i = 0; i < swapchainCount; i++) {
513 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700514 skip |= LogWarning(
515 device, kVUID_BestPractices_SharingModeExclusive,
516 "Warning: A shared swapchain (index %" PRIu32
517 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
518 "queues (queueFamilyIndexCount of %" PRIu32 ").",
519 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600520 }
521 }
522
523 return skip;
524}
525
526bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500527 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600528 bool skip = false;
529
530 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
531 VkFormat format = pCreateInfo->pAttachments[i].format;
532 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
533 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
534 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700535 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
536 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
537 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
538 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
539 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600540 }
541 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700542 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
543 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
544 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
545 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
546 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600547 }
548 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000549
550 const auto& attachment = pCreateInfo->pAttachments[i];
551 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
552 bool access_requires_memory =
553 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
554
555 if (FormatHasStencil(format)) {
556 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
557 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
558 }
559
560 if (access_requires_memory) {
561 skip |= LogPerformanceWarning(
562 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
563 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
564 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
565 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
566 i, static_cast<uint32_t>(attachment.samples));
567 }
568 }
Camden5b184be2019-08-13 07:50:19 -0600569 }
570
571 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
572 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
573 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
574 }
575
576 return skip;
577}
578
Tony-LunarG767180f2020-04-23 14:03:59 -0600579bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
580 const VkImageView* image_views) const {
581 bool skip = false;
582
583 // Check for non-transient attachments that should be transient and vice versa
584 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200585 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600586 bool attachment_should_be_transient =
587 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
588
589 if (FormatHasStencil(attachment.format)) {
590 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
591 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
592 }
593
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600594 auto view_state = Get<IMAGE_VIEW_STATE>(image_views[i]);
Tony-LunarG767180f2020-04-23 14:03:59 -0600595 if (view_state) {
Jeremy Gebben057f9d52021-11-05 14:12:31 -0600596 const auto& ici = view_state->image_state->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600597
598 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
599
600 // The check for an image that should not be transient applies to all GPUs
601 if (!attachment_should_be_transient && image_is_transient) {
602 skip |= LogPerformanceWarning(
603 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
604 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
605 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
606 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
607 i);
608 }
609
610 bool supports_lazy = false;
611 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
612 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
613 supports_lazy = true;
614 }
615 }
616
617 // The check for an image that should be transient only applies to GPUs supporting
618 // lazily allocated memory
619 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
620 skip |= LogPerformanceWarning(
621 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
622 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
623 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
624 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
625 i);
626 }
627 }
628 }
629 return skip;
630}
631
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000632bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
633 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
634 bool skip = false;
635
Jeremy Gebbenb20a8242021-11-05 15:14:43 -0600636 auto rp_state = Get<RENDER_PASS_STATE>(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800637 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600638 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000639 }
640
641 return skip;
642}
643
Sam Wallse746d522020-03-16 21:20:23 +0000644bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
645 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
646 bool skip = false;
647 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
648
649 if (!skip) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700650 const auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000651 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
652 // this warning is specific to Arm
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700653 if (VendorCheckEnabled(kBPVendorArm) && pool_state && (pool_state->freed_count > 0)) {
Sam Wallse746d522020-03-16 21:20:23 +0000654 skip |= LogPerformanceWarning(
655 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
656 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
657 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
658 VendorSpecificTag(kBPVendorArm));
659 }
ziga-lunarg5a76c442022-04-17 18:04:08 +0200660
661 if (IsExtEnabled(device_extensions.vk_khr_maintenance1)) {
662 // Track number of descriptorSets allowable in this pool
663 if (pool_state->GetAvailableSets() < pAllocateInfo->descriptorSetCount) {
664 skip |= LogWarning(pool_state->Handle(), kVUID_BestPractices_EmptyDescriptorPool,
665 "vkAllocateDescriptorSets(): Unable to allocate %" PRIu32 " descriptorSets from %s"
666 ". This pool only has %" PRIu32 " descriptorSets remaining.",
667 pAllocateInfo->descriptorSetCount, report_data->FormatHandle(pool_state->Handle()).c_str(),
668 pool_state->GetAvailableSets());
669 }
670 }
Sam Wallse746d522020-03-16 21:20:23 +0000671 }
672
673 return skip;
674}
675
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600676void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
677 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000678 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700679 auto pool_state = Get<bp_state::DescriptorPool>(pAllocateInfo->descriptorPool);
680 if (pool_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000681 // we record successful allocations by subtracting the allocation count from the last recorded free count
682 const auto alloc_count = pAllocateInfo->descriptorSetCount;
683 // clamp the unsigned subtraction to the range [0, last_free_count]
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700684 if (pool_state->freed_count > alloc_count) {
685 pool_state->freed_count -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700686 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700687 pool_state->freed_count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700688 }
Sam Wallse746d522020-03-16 21:20:23 +0000689 }
690 }
691}
692
693void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
694 const VkDescriptorSet* pDescriptorSets, VkResult result) {
695 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
696 if (result == VK_SUCCESS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700697 auto pool_state = Get<bp_state::DescriptorPool>(descriptorPool);
Sam Wallse746d522020-03-16 21:20:23 +0000698 // we want to track frees because we're interested in suggesting re-use
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700699 if (pool_state) {
700 pool_state->freed_count += descriptorSetCount;
Sam Wallse746d522020-03-16 21:20:23 +0000701 }
702 }
703}
704
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300705void BestPractices::PreCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
706 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) {
707 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
708 WriteLockGuard guard{memory_free_events_lock_};
709
710 // Release old allocations to avoid overpopulating the container
711 const auto now = std::chrono::high_resolution_clock::now();
712 const auto last_old = std::find_if(memory_free_events_.rbegin(), memory_free_events_.rend(), [now](const MemoryFreeEvent& event) {
713 return now - event.time > kAllocateMemoryReuseTimeThresholdNVIDIA;
714 });
715 memory_free_events_.erase(memory_free_events_.begin(), last_old.base());
716 }
717}
718
Camden5b184be2019-08-13 07:50:19 -0600719bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500720 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600721 bool skip = false;
722
Jeremy Gebben20da7a12022-02-25 14:07:46 -0700723 if ((Count<DEVICE_MEMORY_STATE>() + 1) > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700724 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
725 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600726 }
727
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000728 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
729 skip |= LogPerformanceWarning(
730 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600731 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
732 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000733 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
734 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
735 }
736
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300737 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
738 if (!device_extensions.vk_ext_pageable_device_local_memory &&
739 !LvlFindInChain<VkMemoryPriorityAllocateInfoEXT>(pAllocateInfo->pNext)) {
740 skip |= LogPerformanceWarning(
741 device, kVUID_BestPractices_AllocateMemory_SetPriority,
742 "%s Use VkMemoryPriorityAllocateInfoEXT to provide the operating system information on the allocations that "
743 "should stay in video memory and which should be demoted first when video memory is limited. "
744 "The highest priority should be given to GPU-written resources like color attachments, depth attachments, "
745 "storage images, and buffers written from the GPU.",
746 VendorSpecificTag(kBPVendorNVIDIA));
747 }
748
749 {
750 // Size in bytes for an allocation to be considered "compatible"
751 static constexpr VkDeviceSize size_threshold = VkDeviceSize{1} << 20;
752
753 ReadLockGuard guard{memory_free_events_lock_};
754
755 const auto now = std::chrono::high_resolution_clock::now();
756 const VkDeviceSize alloc_size = pAllocateInfo->allocationSize;
757 const uint32_t memory_type_index = pAllocateInfo->memoryTypeIndex;
758 const auto latest_event = std::find_if(memory_free_events_.rbegin(), memory_free_events_.rend(), [&](const MemoryFreeEvent& event) {
759 return (memory_type_index == event.memory_type_index) && (alloc_size <= event.allocation_size) &&
760 (alloc_size - event.allocation_size <= size_threshold) && (now - event.time < kAllocateMemoryReuseTimeThresholdNVIDIA);
761 });
762
763 if (latest_event != memory_free_events_.rend()) {
764 const auto time_delta = std::chrono::duration_cast<std::chrono::milliseconds>(now - latest_event->time);
765 if (time_delta < std::chrono::milliseconds{5}) {
766 skip |=
767 LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_ReuseAllocations,
768 "%s Reuse memory allocations instead of releasing and reallocating. A memory allocation "
769 "has just been released, and it could have been reused in place of this allocation.",
770 VendorSpecificTag(kBPVendorNVIDIA));
771 } else {
772 const uint32_t seconds = static_cast<uint32_t>(time_delta.count() / 1000);
773 const uint32_t milliseconds = static_cast<uint32_t>(time_delta.count() % 1000);
774
775 skip |= LogPerformanceWarning(
776 device, kVUID_BestPractices_AllocateMemory_ReuseAllocations,
777 "%s Reuse memory allocations instead of releasing and reallocating. A memory allocation has been released "
778 "%" PRIu32 ".%03" PRIu32 " seconds ago, and it could have been reused in place of this allocation.",
779 VendorSpecificTag(kBPVendorNVIDIA), seconds, milliseconds);
780 }
781 }
782 }
Rodrigo Locattie4f8d522022-03-15 16:30:49 -0300783 }
784
Camden83a9c372019-08-14 11:41:38 -0600785 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
786
787 return skip;
788}
789
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600790void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
791 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
792 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700793 if (result != VK_SUCCESS) {
794 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
795 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800796 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700797 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600798 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700799 return;
800 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700801}
Camden Stocker9738af92019-10-16 13:54:03 -0700802
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600803void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
804 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700805 auto error = std::find(error_codes.begin(), error_codes.end(), result);
806 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000807 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
808 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
809
810 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
811 if (common_failure != common_failure_codes.end()) {
812 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
813 } else {
814 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
815 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700816 return;
817 }
818 auto success = std::find(success_codes.begin(), success_codes.end(), result);
819 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600820 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
821 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500822 }
823}
824
Rodrigo Locattid5b54f52022-03-16 19:12:45 -0300825void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
826 if (memory != VK_NULL_HANDLE && VendorCheckEnabled(kBPVendorNVIDIA)) {
827 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
828
829 // Exclude memory free events on dedicated allocations, or imported/exported allocations.
830 if (!mem_info->IsDedicatedBuffer() && !mem_info->IsDedicatedImage() && !mem_info->IsExport() && !mem_info->IsImport()) {
831 MemoryFreeEvent event;
832 event.time = std::chrono::high_resolution_clock::now();
833 event.memory_type_index = mem_info->alloc_info.memoryTypeIndex;
834 event.allocation_size = mem_info->alloc_info.allocationSize;
835
836 WriteLockGuard guard{memory_free_events_lock_};
837 memory_free_events_.push_back(event);
838 }
839 }
840
841 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
842}
843
Jeff Bolz5c801d12019-10-09 10:38:45 -0500844bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
845 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700846 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600847 bool skip = false;
848
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700849 auto mem_info = Get<DEVICE_MEMORY_STATE>(memory);
Camden83a9c372019-08-14 11:41:38 -0600850
Jeremy Gebben610d3a62022-01-01 12:53:17 -0700851 for (const auto& item : mem_info->ObjectBindings()) {
852 const auto& obj = item.first;
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600853 LogObjectList objlist(device);
854 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600855 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600856 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 -0600857 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600858 }
859
Camden5b184be2019-08-13 07:50:19 -0600860 return skip;
861}
862
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000863bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600864 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700865 auto buffer_state = Get<BUFFER_STATE>(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600866
sfricke-samsunge2441192019-11-06 14:07:57 -0800867 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700868 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
869 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
870 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600871 }
872
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700873 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000874
AndreyVK_D3D0416a332021-11-02 23:22:28 +0300875 if (mem_state && mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000876 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
877 skip |= LogPerformanceWarning(
878 device, kVUID_BestPractices_SmallDedicatedAllocation,
879 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600880 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
881 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000882 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
883 }
884
Rodrigo Locatti66b23352022-03-15 17:28:32 -0300885 skip |= ValidateBindMemory(device, memory);
886
Camden Stockerb603cc82019-09-03 10:09:02 -0600887 return skip;
888}
889
890bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500891 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600892 bool skip = false;
893 const char* api_name = "BindBufferMemory()";
894
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000895 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600896
897 return skip;
898}
899
900bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500901 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600902 char api_name[64];
903 bool skip = false;
904
905 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200906 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000907 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600908 }
909
910 return skip;
911}
Camden Stockerb603cc82019-09-03 10:09:02 -0600912
913bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500914 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600915 char api_name[64];
916 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600917
Camden Stocker8b798ab2019-09-03 10:33:28 -0600918 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +0200919 snprintf(api_name, sizeof(api_name), "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000920 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600921 }
922
923 return skip;
924}
925
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000926bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600927 bool skip = false;
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700928 auto image_state = Get<IMAGE_STATE>(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600929
sfricke-samsung71bc6572020-04-29 15:49:43 -0700930 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600931 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700932 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
933 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
934 api_name, report_data->FormatHandle(image).c_str());
935 }
936 } else {
937 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
938 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600939 }
940
Jeremy Gebbenf4449392022-01-28 10:09:10 -0700941 auto mem_state = Get<DEVICE_MEMORY_STATE>(memory);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000942
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600943 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000944 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
945 skip |= LogPerformanceWarning(
946 device, kVUID_BestPractices_SmallDedicatedAllocation,
947 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600948 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
949 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000950 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
951 }
952
953 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
954 // make sure this type is actually used.
955 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
956 // (i.e.most tile - based renderers)
957 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
958 bool supports_lazy = false;
959 uint32_t suggested_type = 0;
960
961 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600962 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000963 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
964 supports_lazy = true;
965 suggested_type = i;
966 break;
967 }
968 }
969 }
970
971 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
972
973 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
974 skip |= LogPerformanceWarning(
975 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600976 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000977 "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 -0600978 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600979 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000980 }
981 }
982
Rodrigo Locatti66b23352022-03-15 17:28:32 -0300983 skip |= ValidateBindMemory(device, memory);
984
Camden Stocker8b798ab2019-09-03 10:33:28 -0600985 return skip;
986}
987
988bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500989 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600990 bool skip = false;
991 const char* api_name = "vkBindImageMemory()";
992
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000993 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600994
995 return skip;
996}
997
998bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500999 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -06001000 char api_name[64];
1001 bool skip = false;
1002
1003 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +02001004 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001005 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -06001006 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
1007 }
Camden Stocker8b798ab2019-09-03 10:33:28 -06001008 }
1009
1010 return skip;
1011}
1012
1013bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001014 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -06001015 char api_name[64];
1016 bool skip = false;
1017
1018 for (uint32_t i = 0; i < bindInfoCount; i++) {
Frédéric Wangafb89862022-06-21 16:15:29 +02001019 snprintf(api_name, sizeof(api_name), "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +00001020 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -06001021 }
1022
1023 return skip;
1024}
Camden83a9c372019-08-14 11:41:38 -06001025
Rodrigo Locatti66b23352022-03-15 17:28:32 -03001026void BestPractices::PreCallRecordSetDeviceMemoryPriorityEXT(VkDevice device, VkDeviceMemory memory, float priority) {
1027 auto mem_info = std::static_pointer_cast<bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
1028 mem_info->dynamic_priority.emplace(priority);
1029}
1030
Attilio Provenzano02859b22020-02-27 14:17:28 +00001031static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
1032 switch (format) {
1033 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
1034 case VK_FORMAT_R16_SFLOAT:
1035 case VK_FORMAT_R16G16_SFLOAT:
1036 case VK_FORMAT_R16G16B16_SFLOAT:
1037 case VK_FORMAT_R16G16B16A16_SFLOAT:
1038 case VK_FORMAT_R32_SFLOAT:
1039 case VK_FORMAT_R32G32_SFLOAT:
1040 case VK_FORMAT_R32G32B32_SFLOAT:
1041 case VK_FORMAT_R32G32B32A32_SFLOAT:
1042 return false;
1043
1044 default:
1045 return true;
1046 }
1047}
1048
1049bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
1050 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
1051 bool skip = false;
1052
1053 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001054 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001055
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001056 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
1057 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
1058 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +00001059 return skip;
1060 }
1061
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06001062 auto rp_state = Get<RENDER_PASS_STATE>(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001063 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001064
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +02001065 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1066 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
1067
1068 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001069 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001070 uint32_t att = subpass.pColorAttachments[j].attachment;
1071
1072 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
1073 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
1074 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
1075 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
1076 "color attachment #%u makes use "
1077 "of a format which cannot be blended at full throughput when using MSAA.",
1078 VendorSpecificTag(kBPVendorArm), i, j);
1079 }
1080 }
1081 }
1082 }
1083
1084 return skip;
1085}
1086
Nadav Gevaf0808442021-05-21 13:51:25 -04001087void BestPractices::ManualPostCallRecordCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1088 const VkComputePipelineCreateInfo* pCreateInfos,
1089 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1090 VkResult result, void* pipe_state) {
1091 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001092 pipeline_cache_ = pipelineCache;
Nadav Gevaf0808442021-05-21 13:51:25 -04001093}
1094
Camden5b184be2019-08-13 07:50:19 -06001095bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1096 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001097 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001098 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001099 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1100 pAllocator, pPipelines, cgpl_state_data);
ziga-lunarg08c81582022-03-08 17:33:45 +01001101 if (skip) {
1102 return skip;
1103 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001104 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001105
1106 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001107 skip |= LogPerformanceWarning(
1108 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1109 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
1110 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001111 }
1112
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001113 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001114 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001115
Tony-LunarGb6a2daf2022-07-29 11:30:55 -06001116 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 +02001117 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001118 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001119 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
1120 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001121 count++;
1122 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001123 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -06001124 if (count > kMaxInstancedVertexBuffers) {
1125 skip |= LogPerformanceWarning(
1126 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
1127 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
1128 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
1129 count, kMaxInstancedVertexBuffers);
1130 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001131 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001132
Szilard Pappaaf2da32020-06-22 10:37:35 +01001133 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
1134 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001135 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
1136 VendorCheckEnabled(kBPVendorArm)) {
1137 skip |= LogPerformanceWarning(
1138 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
1139 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
1140 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
1141 "efficiency during rasterization. Consider disabling depthBias or increasing either "
1142 "depthBiasConstantFactor or depthBiasSlopeFactor.",
1143 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +01001144 }
1145
Attilio Provenzano02859b22020-02-27 14:17:28 +00001146 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001147 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001148 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001149 auto prev_pipeline = pipeline_cache_.load();
1150 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001151 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultiplePipelineCaches,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001152 "%s %s Performance Warning: A second pipeline cache is in use. "
1153 "Consider using only one pipeline cache to improve cache hit rate.",
1154 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04001155 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001156 }
1157 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001158 if (num_pso_ > kMaxRecommendedNumberOfPSOAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001159 skip |=
1160 LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_TooManyPipelines,
1161 "%s Performance warning: Too many pipelines created, consider consolidation",
1162 VendorSpecificTag(kBPVendorAMD));
1163 }
1164
Nathaniel Cesario1a7e1a92021-08-30 14:34:20 -06001165 if (pCreateInfos->pInputAssemblyState && pCreateInfos->pInputAssemblyState->primitiveRestartEnable) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001166 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_AvoidPrimitiveRestart,
1167 "%s Performance warning: Use of primitive restart is not recommended",
1168 VendorSpecificTag(kBPVendorAMD));
1169 }
1170
1171 // TODO: this might be too aggressive of a check
1172 if (pCreateInfos->pDynamicState && pCreateInfos->pDynamicState->dynamicStateCount > kDynamicStatesWarningLimitAMD) {
1173 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MinimizeNumDynamicStates,
1174 "%s Performance warning: Dynamic States usage incurs a performance cost. Ensure that they are truly needed",
1175 VendorSpecificTag(kBPVendorAMD));
1176 }
1177 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00001178
Camden5b184be2019-08-13 07:50:19 -06001179 return skip;
1180}
1181
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001182static std::vector<bp_state::AttachmentInfo> GetAttachmentAccess(const safe_VkGraphicsPipelineCreateInfo& create_info,
1183 std::shared_ptr<const RENDER_PASS_STATE>& rp) {
1184 std::vector<bp_state::AttachmentInfo> result;
Jeremy Gebbenb5dda542022-08-02 14:26:20 -06001185 if (!rp || rp->UsesDynamicRendering()) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001186 return result;
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001187 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001188
1189 const auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
1190
1191 // NOTE: see PIPELINE_LAYOUT and safe_VkGraphicsPipelineCreateInfo constructors. pColorBlendState and pDepthStencilState
1192 // are only non-null if they are enabled.
1193 if (create_info.pColorBlendState) {
1194 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
1195 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info.pColorBlendState->attachmentCount);
1196 for (uint32_t j = 0; j < num_color_attachments; j++) {
1197 if (create_info.pColorBlendState->pAttachments[j].colorWriteMask != 0) {
1198 uint32_t attachment = subpass.pColorAttachments[j].attachment;
1199 if (attachment != VK_ATTACHMENT_UNUSED) {
1200 result.push_back({attachment, VK_IMAGE_ASPECT_COLOR_BIT});
1201 }
1202 }
1203 }
1204 }
1205
1206 if (create_info.pDepthStencilState &&
1207 (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable ||
1208 create_info.pDepthStencilState->stencilTestEnable)) {
1209 uint32_t attachment = subpass.pDepthStencilAttachment ? subpass.pDepthStencilAttachment->attachment : VK_ATTACHMENT_UNUSED;
1210 if (attachment != VK_ATTACHMENT_UNUSED) {
1211 VkImageAspectFlags aspects = 0;
1212 if (create_info.pDepthStencilState->depthTestEnable || create_info.pDepthStencilState->depthBoundsTestEnable) {
1213 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1214 }
1215 if (create_info.pDepthStencilState->stencilTestEnable) {
1216 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1217 }
1218 result.push_back({attachment, aspects});
1219 }
1220 }
1221 return result;
1222}
1223
1224bp_state::Pipeline::Pipeline(const ValidationStateTracker* state_data, const VkGraphicsPipelineCreateInfo* pCreateInfo,
1225 std::shared_ptr<const RENDER_PASS_STATE>&& rpstate,
1226 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout)
1227 : PIPELINE_STATE(state_data, pCreateInfo, std::move(rpstate), std::move(layout)),
1228 access_framebuffer_attachments(GetAttachmentAccess(create_info.graphics, rp_state)) {}
1229
1230std::shared_ptr<PIPELINE_STATE> BestPractices::CreateGraphicsPipelineState(
1231 const VkGraphicsPipelineCreateInfo* pCreateInfo, std::shared_ptr<const RENDER_PASS_STATE>&& render_pass,
1232 std::shared_ptr<const PIPELINE_LAYOUT_STATE>&& layout) const {
1233 return std::static_pointer_cast<PIPELINE_STATE>(
1234 std::make_shared<bp_state::Pipeline>(this, pCreateInfo, std::move(render_pass), std::move(layout)));
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +02001235}
1236
Sam Walls0961ec02020-03-31 16:39:15 +01001237void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
1238 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1239 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
1240 VkResult result, void* cgpl_state_data) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001241 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001242 pipeline_cache_ = pipelineCache;
Sam Walls0961ec02020-03-31 16:39:15 +01001243}
1244
Camden5b184be2019-08-13 07:50:19 -06001245bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1246 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001247 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001248 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001249 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1250 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001251
1252 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001253 skip |= LogPerformanceWarning(
1254 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1255 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1256 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001257 }
1258
Nadav Gevaf0808442021-05-21 13:51:25 -04001259 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001260 auto prev_pipeline = pipeline_cache_.load();
1261 if (pipelineCache && prev_pipeline && pipelineCache != prev_pipeline) {
1262 skip |= LogPerformanceWarning(
1263 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1264 "%s Performance Warning: A second pipeline cache is in use. Consider using only one pipeline cache to "
Nadav Gevaf0808442021-05-21 13:51:25 -04001265 "improve cache hit rate",
1266 VendorSpecificTag(kBPVendorAMD));
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001267 }
1268 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001269
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001270 for (uint32_t i = 0; i < createInfoCount; i++) {
1271 const VkComputePipelineCreateInfo& createInfo = pCreateInfos[i];
1272 if (VendorCheckEnabled(kBPVendorArm)) {
1273 skip |= ValidateCreateComputePipelineArm(createInfo);
1274 }
sfricke-samsung86d055a2022-02-11 14:43:50 -08001275
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001276 if (IsExtEnabled(device_extensions.vk_khr_maintenance4)) {
1277 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
1278 for (const auto& builtin : module_state->static_data_.builtin_decoration_list) {
1279 if (builtin.builtin == spv::BuiltInWorkgroupSize) {
1280 skip |= LogWarning(device, kVUID_BestPractices_SpirvDeprecated_WorkgroupSize,
1281 "vkCreateComputePipelines(): pCreateInfos[ %" PRIu32
1282 "] is using the Workgroup built-in which SPIR-V 1.6 deprecated. The VK_KHR_maintenance4 "
1283 "extension exposes a new LocalSizeId execution mode that should be used instead.",
1284 i);
sfricke-samsung86d055a2022-02-11 14:43:50 -08001285 }
1286 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001287 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001288 }
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001289
1290 return skip;
1291}
1292
1293bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1294 bool skip = false;
sfricke-samsungef15e482022-01-26 11:32:49 -08001295 auto module_state = Get<SHADER_MODULE_STATE>(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001296 // Generate warnings about work group sizes based on active resources.
sfricke-samsungef15e482022-01-26 11:32:49 -08001297 auto entrypoint = module_state->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
1298 if (entrypoint == module_state->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001299
1300 uint32_t x = 1, y = 1, z = 1;
sfricke-samsungef15e482022-01-26 11:32:49 -08001301 module_state->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001302
1303 uint32_t thread_count = x * y * z;
1304
1305 // Generate a priori warnings about work group sizes.
1306 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1307 skip |= LogPerformanceWarning(
1308 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1309 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1310 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1311 "groups with less than %u threads, especially when using barrier() or shared memory.",
1312 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1313 }
1314
1315 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1316 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1317 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1318 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1319 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1320 "%u, %u) is not aligned to %u "
1321 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1322 "leave threads idle on the shader "
1323 "core.",
1324 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1325 kThreadGroupDispatchCountAlignmentArm);
1326 }
1327
sfricke-samsungef15e482022-01-26 11:32:49 -08001328 auto accessible_ids = module_state->MarkAccessibleIds(entrypoint);
1329 auto descriptor_uses = module_state->CollectInterfaceByDescriptorSlot(accessible_ids);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001330
1331 unsigned dimensions = 0;
1332 if (x > 1) dimensions++;
1333 if (y > 1) dimensions++;
1334 if (z > 1) dimensions++;
1335 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1336 dimensions = std::max(dimensions, 1u);
1337
1338 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1339 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1340 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1341 bool accesses_2d = false;
1342 for (const auto& usage : descriptor_uses) {
sfricke-samsungef15e482022-01-26 11:32:49 -08001343 auto dim = module_state->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001344 if (dim < 0) continue;
1345 auto spvdim = spv::Dim(dim);
1346 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1347 }
1348
1349 if (accesses_2d && dimensions < 2) {
1350 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1351 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1352 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1353 "exhibiting poor spatial locality with respect to one or more shader resources.",
1354 VendorSpecificTag(kBPVendorArm), x, y, z);
1355 }
1356
Camden5b184be2019-08-13 07:50:19 -06001357 return skip;
1358}
1359
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001360bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001361 bool skip = false;
1362
1363 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001364 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1365 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001366 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001367 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1368 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001369 }
1370
1371 return skip;
1372}
1373
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001374bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1375 bool skip = false;
1376
1377 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1378 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1379 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1380 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1381 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1382 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1383 }
1384
1385 return skip;
1386}
1387
1388bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1389 bool skip = false;
1390 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1391
1392 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1393 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1394
1395 return skip;
1396}
1397
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001398void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001399 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1400 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1401 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1402 LogPerformanceWarning(
1403 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1404 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1405 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1406 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1407 "convenient opportunity.",
1408 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1409 }
1410 }
Nadav Gevaf0808442021-05-21 13:51:25 -04001411
1412 // AMD best practice
1413 // end-of-frame cleanup
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001414 num_queue_submissions_ = 0;
1415 num_barriers_objects_ = 0;
1416 ClearPipelinesUsedInFrame();
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001417}
1418
Jeff Bolz5c801d12019-10-09 10:38:45 -05001419bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1420 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001421 bool skip = false;
1422
1423 for (uint32_t submit = 0; submit < submitCount; submit++) {
1424 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1425 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1426 }
ziga-lunargc77f0c02022-04-18 00:15:16 +02001427 if (pSubmits[submit].signalSemaphoreCount == 0 && pSubmits[submit].pSignalSemaphores != nullptr) {
1428 skip |=
1429 LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1430 "pSubmits[%" PRIu32 "].pSignalSemaphores is set, but pSubmits[%" PRIu32 "].signalSemaphoreCount is 0.",
1431 submit, submit);
1432 }
1433 if (pSubmits[submit].waitSemaphoreCount == 0 && pSubmits[submit].pWaitSemaphores != nullptr) {
1434 skip |= LogWarning(device, kVUID_BestPractices_SemaphoreCount,
1435 "pSubmits[%" PRIu32 "].pWaitSemaphores is set, but pSubmits[%" PRIu32 "].waitSemaphoreCount is 0.",
1436 submit, submit);
1437 }
Camden5b184be2019-08-13 07:50:19 -06001438 }
1439
1440 return skip;
1441}
1442
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001443bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1444 VkFence fence) const {
1445 bool skip = false;
1446
1447 for (uint32_t submit = 0; submit < submitCount; submit++) {
1448 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1449 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1450 }
1451 }
1452
1453 return skip;
1454}
1455
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001456bool BestPractices::PreCallValidateQueueSubmit2(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2* pSubmits,
1457 VkFence fence) const {
1458 bool skip = false;
1459
1460 for (uint32_t submit = 0; submit < submitCount; submit++) {
1461 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1462 skip |= CheckPipelineStageFlags("vkQueueSubmit2", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1463 }
1464 }
1465
1466 return skip;
1467}
1468
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001469bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1470 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1471 bool skip = false;
1472
1473 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1474 skip |= LogPerformanceWarning(
1475 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1476 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1477 "pool instead.");
1478 }
1479
1480 return skip;
1481}
1482
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001483void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer,
1484 const VkCommandBufferBeginInfo* pBeginInfo) {
1485 StateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1486
1487 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
paul-lunarg093c1762022-08-23 18:52:10 +02001488 if (!cb) return;
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001489
1490 cb->num_submits = 0;
1491 cb->is_one_time_submit = (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) != 0;
1492}
1493
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001494bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1495 const VkCommandBufferBeginInfo* pBeginInfo) const {
1496 bool skip = false;
1497
1498 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1499 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1500 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1501 }
1502
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001503 if (VendorCheckEnabled(kBPVendorArm)) {
Rodrigo Locattife5172b2022-03-22 18:49:29 -03001504 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)) {
1505 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Rodrigo Locattic789fe82022-07-06 17:42:19 -03001506 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1507 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1508 VendorSpecificTag(kBPVendorArm));
1509 }
1510 }
1511 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1512 auto cb = GetRead<bp_state::CommandBuffer>(commandBuffer);
1513 if (cb->num_submits == 1 && !cb->is_one_time_submit) {
1514 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
1515 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT was not set "
1516 "and the command buffer has only been submitted once. "
1517 "For best performance on NVIDIA GPUs, use ONE_TIME_SUBMIT.",
1518 VendorSpecificTag(kBPVendorNVIDIA));
Rodrigo Locattife5172b2022-03-22 18:49:29 -03001519 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001520 }
1521
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001522 return skip;
1523}
1524
Jeff Bolz5c801d12019-10-09 10:38:45 -05001525bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001526 bool skip = false;
1527
1528 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1529
1530 return skip;
1531}
1532
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001533bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1534 const VkDependencyInfoKHR* pDependencyInfo) const {
1535 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1536}
1537
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001538bool BestPractices::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1539 const VkDependencyInfo* pDependencyInfo) const {
1540 return CheckDependencyInfo("vkCmdSetEvent2", *pDependencyInfo);
1541}
1542
Jeff Bolz5c801d12019-10-09 10:38:45 -05001543bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1544 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001545 bool skip = false;
1546
1547 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1548
1549 return skip;
1550}
1551
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001552bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1553 VkPipelineStageFlags2KHR stageMask) const {
1554 bool skip = false;
1555
1556 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1557
1558 return skip;
1559}
1560
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001561bool BestPractices::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
1562 VkPipelineStageFlags2 stageMask) const {
1563 bool skip = false;
1564
1565 skip |= CheckPipelineStageFlags("vkCmdResetEvent2", stageMask);
1566
1567 return skip;
1568}
1569
Camden5b184be2019-08-13 07:50:19 -06001570bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1571 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1572 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1573 uint32_t bufferMemoryBarrierCount,
1574 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1575 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001576 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001577 bool skip = false;
1578
1579 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1580 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1581
1582 return skip;
1583}
1584
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001585bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1586 const VkDependencyInfoKHR* pDependencyInfos) const {
1587 bool skip = false;
1588 for (uint32_t i = 0; i < eventCount; i++) {
1589 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1590 }
1591
1592 return skip;
1593}
1594
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001595bool BestPractices::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1596 const VkDependencyInfo* pDependencyInfos) const {
1597 bool skip = false;
1598 for (uint32_t i = 0; i < eventCount; i++) {
1599 skip = CheckDependencyInfo("vkCmdWaitEvents2", pDependencyInfos[i]);
1600 }
1601
1602 return skip;
1603}
1604
Camden5b184be2019-08-13 07:50:19 -06001605bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1606 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1607 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1608 uint32_t bufferMemoryBarrierCount,
1609 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1610 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001611 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001612 bool skip = false;
1613
1614 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1615 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1616
ziga-lunargb65dbfb2022-03-19 18:45:09 +01001617 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1618 if (pImageMemoryBarriers[i].oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
1619 IsImageLayoutReadOnly(pImageMemoryBarriers[i].newLayout)) {
1620 skip |= LogWarning(device, kVUID_BestPractices_TransitionUndefinedToReadOnly,
1621 "VkImageMemoryBarrier is being submitted with oldLayout VK_IMAGE_LAYOUT_UNDEFINED and the contents "
1622 "may be discarded, but the newLayout is %s, which is read only.",
1623 string_VkImageLayout(pImageMemoryBarriers[i].newLayout));
1624 }
1625 }
1626
Nadav Gevaf0808442021-05-21 13:51:25 -04001627 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001628 auto num = num_barriers_objects_.load();
1629 if (num + imageMemoryBarrierCount + bufferMemoryBarrierCount > kMaxRecommendedBarriersSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001630 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_highBarrierCount,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001631 "%s Performance warning: In this frame, %" PRIu32
1632 " barriers were already submitted. Barriers have a high cost and can "
1633 "stall the GPU. "
1634 "Consider consolidating and re-organizing the frame to use fewer barriers.",
1635 VendorSpecificTag(kBPVendorAMD), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04001636 }
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001637 }
1638 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
1639 static constexpr std::array<VkImageLayout, 3> read_layouts = {
Nadav Gevaf0808442021-05-21 13:51:25 -04001640 VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
1641 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
1642 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1643 };
1644
1645 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1646 // read to read barriers
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001647 const auto &image_barrier = pImageMemoryBarriers[i];
1648 bool old_is_read_layout = std::find(read_layouts.begin(), read_layouts.end(), image_barrier.oldLayout) != read_layouts.end();
1649 bool new_is_read_layout = std::find(read_layouts.begin(), read_layouts.end(), image_barrier.newLayout) != read_layouts.end();
1650
Nadav Gevaf0808442021-05-21 13:51:25 -04001651 if (old_is_read_layout && new_is_read_layout) {
1652 skip |= LogPerformanceWarning(device, kVUID_BestPractices_PipelineBarrier_readToReadBarrier,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001653 "%s %s Performance warning: Don't issue read-to-read barriers. "
1654 "Get the resource in the right state the first time you use it.",
1655 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04001656 }
1657
1658 // general with no storage
Rodrigo Locatti494e4482022-03-30 16:37:40 -03001659 if (VendorCheckEnabled(kBPVendorAMD) && image_barrier.newLayout == VK_IMAGE_LAYOUT_GENERAL) {
Nadav Gevaf0808442021-05-21 13:51:25 -04001660 auto image_state = Get<IMAGE_STATE>(pImageMemoryBarriers[i].image);
1661 if (!(image_state->createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1662 skip |= LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidGeneral,
1663 "%s Performance warning: VK_IMAGE_LAYOUT_GENERAL should only be used with "
1664 "VK_IMAGE_USAGE_STORAGE_BIT images.",
1665 VendorSpecificTag(kBPVendorAMD));
1666 }
1667 }
1668 }
1669 }
1670
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001671 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
1672 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
1673 }
1674
Camden5b184be2019-08-13 07:50:19 -06001675 return skip;
1676}
1677
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001678bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1679 const VkDependencyInfoKHR* pDependencyInfo) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001680 bool skip = false;
1681
1682 skip |= CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1683
1684 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
1685 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
1686 }
1687
1688 return skip;
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001689}
1690
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001691bool BestPractices::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
1692 const VkDependencyInfo* pDependencyInfo) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001693 bool skip = false;
1694
1695 skip |= CheckDependencyInfo("vkCmdPipelineBarrier2", *pDependencyInfo);
1696
1697 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
1698 skip |= ValidateCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
1699 }
1700
1701 return skip;
1702}
1703
1704template <typename ImageMemoryBarrier>
1705bool BestPractices::ValidateCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer,
1706 const ImageMemoryBarrier& barrier) const {
1707
1708 bool skip = false;
1709
Mark Young0a6b48f2022-08-18 11:17:02 -06001710 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
1711 assert(cmd_state);
1712
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001713 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1714 if (barrier.oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && barrier.newLayout != VK_IMAGE_LAYOUT_UNDEFINED) {
Mark Young0a6b48f2022-08-18 11:17:02 -06001715 skip |= ValidateZcull(*cmd_state, barrier.image, barrier.subresourceRange);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001716 }
1717 }
1718
1719 return skip;
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001720}
1721
Camden5b184be2019-08-13 07:50:19 -06001722bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001723 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001724 bool skip = false;
1725
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001726 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1727
1728 return skip;
1729}
1730
1731bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1732 VkQueryPool queryPool, uint32_t query) const {
1733 bool skip = false;
1734
1735 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001736
1737 return skip;
1738}
1739
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001740bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1741 VkQueryPool queryPool, uint32_t query) const {
1742 bool skip = false;
1743
1744 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1745
1746 return skip;
1747}
1748
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001749void BestPractices::PreCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1750 VkPipeline pipeline) {
1751 StateTracker::PreCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1752
1753 auto pipeline_info = Get<PIPELINE_STATE>(pipeline);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001754 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001755
1756 assert(pipeline_info);
1757 assert(cb);
1758
1759 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS && VendorCheckEnabled(kBPVendorNVIDIA)) {
1760 using TessGeometryMeshState = bp_state::CommandBufferStateNV::TessGeometryMesh::State;
1761 auto& tgm = cb->nv.tess_geometry_mesh;
1762
1763 // Make sure the message is only signaled once per command buffer
1764 tgm.threshold_signaled = tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA;
1765
1766 // Track pipeline switches with tessellation, geometry, and/or mesh shaders enabled, and disabled
1767 auto tgm_stages = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT |
1768 VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_TASK_BIT_NV | VK_SHADER_STAGE_MESH_BIT_NV;
1769 auto new_tgm_state = (pipeline_info->active_shaders & tgm_stages) != 0
1770 ? TessGeometryMeshState::Enabled
1771 : TessGeometryMeshState::Disabled;
1772 if (tgm.state != new_tgm_state && tgm.state != TessGeometryMeshState::Unknown) {
1773 tgm.num_switches++;
1774 }
1775 tgm.state = new_tgm_state;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001776
1777 // Track depthTestEnable and depthCompareOp
1778 auto &pipeline_create_info = pipeline_info->GetCreateInfo<VkGraphicsPipelineCreateInfo>();
1779 auto depth_stencil_state = pipeline_create_info.pDepthStencilState;
1780 auto dynamic_state = pipeline_create_info.pDynamicState;
1781 if (depth_stencil_state && dynamic_state) {
1782 auto dynamic_state_begin = dynamic_state->pDynamicStates;
1783 auto dynamic_state_end = dynamic_state->pDynamicStates + dynamic_state->dynamicStateCount;
1784
1785 bool dynamic_depth_test_enable = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE) != dynamic_state_end;
1786 bool dynamic_depth_func = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_COMPARE_OP) != dynamic_state_end;
1787
1788 if (!dynamic_depth_test_enable) {
1789 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depth_stencil_state->depthTestEnable != VK_FALSE);
1790 }
1791 if (!dynamic_depth_func) {
1792 RecordSetDepthTestState(*cb, depth_stencil_state->depthCompareOp, cb->nv.depth_test_enable);
1793 }
1794 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001795 }
1796}
1797
Sam Walls0961ec02020-03-31 16:39:15 +01001798void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1799 VkPipeline pipeline) {
1800 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1801
Nadav Gevaf0808442021-05-21 13:51:25 -04001802 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001803 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001804
Sam Walls0961ec02020-03-31 16:39:15 +01001805 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001806 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001807 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001808 if (pipeline_state) {
1809 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001810 assert(cb_node);
1811 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001812
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001813 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001814 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001815
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001816 const auto* blend_state = pipeline_state->ColorBlendState();
1817 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001818
1819 if (blend_state) {
1820 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001821 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001822 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1823 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001824 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001825 }
1826 }
1827 }
1828
1829 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001830 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001831
1832 if (stencil_state && stencil_state->depthTestEnable) {
1833 switch (stencil_state->depthCompareOp) {
1834 case VK_COMPARE_OP_EQUAL:
1835 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1836 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001837 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001838 break;
1839 default:
1840 break;
1841 }
1842 }
Sam Walls0961ec02020-03-31 16:39:15 +01001843 }
1844 }
1845}
1846
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001847void BestPractices::PreCallRecordCmdSetDepthCompareOp(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1848 StateTracker::PreCallRecordCmdSetDepthCompareOp(commandBuffer, depthCompareOp);
1849
1850 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1851 assert(cb);
1852
1853 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1854 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1855 }
1856}
1857
1858void BestPractices::PreCallRecordCmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1859 StateTracker::PreCallRecordCmdSetDepthCompareOpEXT(commandBuffer, depthCompareOp);
1860
1861 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1862 assert(cb);
1863
1864 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1865 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1866 }
1867}
1868
1869void BestPractices::PreCallRecordCmdSetDepthTestEnable(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1870 StateTracker::PreCallRecordCmdSetDepthTestEnable(commandBuffer, depthTestEnable);
1871
1872 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1873 assert(cb);
1874
1875 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1876 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1877 }
1878}
1879
1880void BestPractices::PreCallRecordCmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1881 StateTracker::PreCallRecordCmdSetDepthTestEnableEXT(commandBuffer, depthTestEnable);
1882
1883 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1884 assert(cb);
1885
1886 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1887 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1888 }
1889}
1890
1891void BestPractices::RecordSetDepthTestState(bp_state::CommandBuffer& cmd_state, VkCompareOp new_depth_compare_op, bool new_depth_test_enable) {
1892 assert(VendorCheckEnabled(kBPVendorNVIDIA));
1893
1894 if (cmd_state.nv.depth_compare_op != new_depth_compare_op) {
1895 switch (new_depth_compare_op) {
1896 case VK_COMPARE_OP_LESS:
1897 case VK_COMPARE_OP_LESS_OR_EQUAL:
1898 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Less;
1899 break;
1900 case VK_COMPARE_OP_GREATER:
1901 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1902 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Greater;
1903 break;
1904 default:
1905 // The other ops carry over the previous state.
1906 break;
1907 }
1908 }
1909 cmd_state.nv.depth_compare_op = new_depth_compare_op;
1910 cmd_state.nv.depth_test_enable = new_depth_test_enable;
1911}
1912
1913void BestPractices::RecordCmdBeginRenderingCommon(VkCommandBuffer commandBuffer) {
1914 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1915 assert(cmd_state);
1916
1917 auto rp = cmd_state->activeRenderPass.get();
1918 assert(rp);
1919
1920 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1921 std::shared_ptr<IMAGE_VIEW_STATE> depth_image_view_shared_ptr;
1922 IMAGE_VIEW_STATE* depth_image_view = nullptr;
1923 layer_data::optional<VkAttachmentLoadOp> load_op;
1924
1925 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1926 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1927 if (depth_attachment) {
1928 load_op.emplace(depth_attachment->loadOp);
1929 depth_image_view_shared_ptr = Get<IMAGE_VIEW_STATE>(depth_attachment->imageView);
1930 depth_image_view = depth_image_view_shared_ptr.get();
1931 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001932
1933 for (uint32_t i = 0; i < rp->dynamic_rendering_begin_rendering_info.colorAttachmentCount; ++i) {
1934 const auto& color_attachment = rp->dynamic_rendering_begin_rendering_info.pColorAttachments[i];
1935 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1936 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
1937 RecordClearColor(format, color_attachment.clearValue.color);
1938 }
1939 }
1940
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001941 } else {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001942 if (rp->createInfo.pAttachments) {
1943 if (rp->createInfo.subpassCount > 0) {
1944 const auto depth_attachment = rp->createInfo.pSubpasses[0].pDepthStencilAttachment;
1945 if (depth_attachment) {
1946 const uint32_t attachment_index = depth_attachment->attachment;
1947 if (attachment_index != VK_ATTACHMENT_UNUSED) {
1948 load_op.emplace(rp->createInfo.pAttachments[attachment_index].loadOp);
1949 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
1950 }
1951 }
1952 }
1953 for (uint32_t i = 0; i < cmd_state->activeRenderPassBeginInfo.clearValueCount; ++i) {
1954 const auto& attachment = rp->createInfo.pAttachments[i];
1955 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1956 const auto& clear_color = cmd_state->activeRenderPassBeginInfo.pClearValues[i].color;
1957 RecordClearColor(attachment.format, clear_color);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001958 }
1959 }
1960 }
1961 }
1962 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
1963 const VkImage depth_image = depth_image_view->image_state->image();
1964 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
1965 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
1966 } else {
1967 RecordUnbindZcullScope(*cmd_state);
1968 }
1969 if (load_op) {
1970 if (*load_op == VK_ATTACHMENT_LOAD_OP_CLEAR || *load_op == VK_ATTACHMENT_LOAD_OP_DONT_CARE) {
1971 RecordResetScopeZcullDirection(*cmd_state);
1972 }
1973 }
1974 }
1975}
1976
1977void BestPractices::RecordCmdEndRenderingCommon(VkCommandBuffer commandBuffer) {
1978 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1979 assert(cmd_state);
1980
1981 auto rp = cmd_state->activeRenderPass.get();
1982 assert(rp);
1983
1984 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1985 layer_data::optional<VkAttachmentStoreOp> store_op;
1986
1987 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1988 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1989 if (depth_attachment) {
1990 store_op.emplace(depth_attachment->storeOp);
1991 }
1992 } else {
1993 if (rp->createInfo.subpassCount > 0) {
1994 const uint32_t last_subpass = rp->createInfo.subpassCount - 1;
1995 const auto depth_attachment = rp->createInfo.pSubpasses[last_subpass].pDepthStencilAttachment;
1996 if (depth_attachment) {
1997 const uint32_t attachment = depth_attachment->attachment;
1998 if (attachment != VK_ATTACHMENT_UNUSED) {
1999 store_op.emplace(rp->createInfo.pAttachments[attachment].storeOp);
2000 }
2001 }
2002 }
2003 }
2004
2005 if (store_op) {
2006 if (*store_op == VK_ATTACHMENT_STORE_OP_DONT_CARE || *store_op == VK_ATTACHMENT_STORE_OP_NONE) {
2007 RecordResetScopeZcullDirection(*cmd_state);
2008 }
2009 }
2010
2011 RecordUnbindZcullScope(*cmd_state);
2012 }
2013}
2014
2015void BestPractices::RecordBindZcullScope(bp_state::CommandBuffer& cmd_state, VkImage depth_attachment, const VkImageSubresourceRange& subresource_range) {
2016 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2017
2018 if (depth_attachment == VK_NULL_HANDLE) {
2019 cmd_state.nv.zcull_scope = {};
2020 return;
2021 }
2022
2023 assert((subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U);
2024
2025 auto image_state = Get<IMAGE_STATE>(depth_attachment);
2026 assert(image_state);
2027
2028 const uint32_t mip_levels = image_state->createInfo.mipLevels;
2029 const uint32_t array_layers = image_state->createInfo.arrayLayers;
2030
2031 auto& tree = cmd_state.nv.zcull_per_image[depth_attachment];
2032 if (tree.states.empty()) {
2033 tree.mip_levels = mip_levels;
2034 tree.array_layers = array_layers;
2035 tree.states.resize(array_layers * mip_levels);
2036 }
2037
2038 cmd_state.nv.zcull_scope.image = depth_attachment;
2039 cmd_state.nv.zcull_scope.range = subresource_range;
2040 cmd_state.nv.zcull_scope.tree = &tree;
2041}
2042
2043void BestPractices::RecordUnbindZcullScope(bp_state::CommandBuffer& cmd_state) {
2044 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2045
2046 RecordBindZcullScope(cmd_state, VK_NULL_HANDLE, VkImageSubresourceRange{});
2047}
2048
2049void BestPractices::RecordResetScopeZcullDirection(bp_state::CommandBuffer& cmd_state) {
2050 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2051
2052 auto& scope = cmd_state.nv.zcull_scope;
2053 RecordResetZcullDirection(cmd_state, scope.image, scope.range);
2054}
2055
2056void BestPractices::RecordResetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2057 const VkImageSubresourceRange& subresource_range) {
2058 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2059
2060 RecordSetZcullDirection(cmd_state, depth_image, subresource_range, bp_state::CommandBufferStateNV::ZcullDirection::Unknown);
2061
2062 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2063 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2064 return;
2065 }
2066 auto& tree = image_it->second;
2067
2068 for (uint32_t i = 0; i < subresource_range.layerCount; ++i) {
2069 const uint32_t layer = subresource_range.baseArrayLayer + i;
2070
2071 for (uint32_t j = 0; j < subresource_range.levelCount; ++j) {
2072 const uint32_t level = subresource_range.baseMipLevel + j;
2073
2074 auto& subresource = tree.GetState(layer, level);
2075 subresource.num_less_draws = 0;
2076 subresource.num_greater_draws = 0;
2077 }
2078 }
2079}
2080
2081void BestPractices::RecordSetScopeZcullDirection(bp_state::CommandBuffer& cmd_state, bp_state::CommandBufferStateNV::ZcullDirection mode) {
2082 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2083
2084 auto& scope = cmd_state.nv.zcull_scope;
2085 RecordSetZcullDirection(cmd_state, scope.image, scope.range, mode);
2086}
2087
2088void BestPractices::RecordSetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2089 const VkImageSubresourceRange& subresource_range,
2090 bp_state::CommandBufferStateNV::ZcullDirection mode) {
2091 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2092
2093 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2094 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2095 return;
2096 }
2097 auto& tree = image_it->second;
2098
2099 for (uint32_t i = 0; i < subresource_range.layerCount; ++i) {
2100 const uint32_t layer = subresource_range.baseArrayLayer + i;
2101
2102 for (uint32_t j = 0; j < subresource_range.levelCount; ++j) {
2103 const uint32_t level = subresource_range.baseMipLevel + j;
2104 tree.GetState(layer, level).direction = cmd_state.nv.zcull_direction;
2105 }
2106 }
2107}
2108
2109void BestPractices::RecordZcullDraw(bp_state::CommandBuffer& cmd_state) {
2110 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2111
2112 // Add one draw to each subresource depending on the current Z-cull direction
2113 auto& scope = cmd_state.nv.zcull_scope;
2114
2115 for (uint32_t i = 0; i < scope.range.layerCount; ++i) {
2116 const uint32_t layer = scope.range.baseArrayLayer + i;
2117 auto& subresource = scope.tree->GetState(layer, scope.range.baseMipLevel);
2118
2119 switch (subresource.direction) {
2120 case bp_state::CommandBufferStateNV::ZcullDirection::Unknown:
2121 // Unreachable
2122 assert(0);
2123 break;
2124 case bp_state::CommandBufferStateNV::ZcullDirection::Less:
2125 ++subresource.num_less_draws;
2126 break;
2127 case bp_state::CommandBufferStateNV::ZcullDirection::Greater:
2128 ++subresource.num_greater_draws;
2129 break;
2130 }
2131 }
2132}
2133
Mark Young0a6b48f2022-08-18 11:17:02 -06002134bool BestPractices::ValidateZcullScope(const bp_state::CommandBuffer& cmd_state) const {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002135 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2136
2137 bool skip = false;
2138
Mark Young0a6b48f2022-08-18 11:17:02 -06002139 if (cmd_state.nv.depth_test_enable) {
2140 auto& scope = cmd_state.nv.zcull_scope;
2141 skip |= ValidateZcull(cmd_state, scope.image, scope.range);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002142 }
2143
2144 return skip;
2145}
2146
Mark Young0a6b48f2022-08-18 11:17:02 -06002147bool BestPractices::ValidateZcull(const bp_state::CommandBuffer& cmd_state, VkImage image,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002148 const VkImageSubresourceRange& subresource_range) const {
2149 bool skip = false;
2150
2151 const char* good_mode = nullptr;
2152 const char* bad_mode = nullptr;
2153
Mark Young0a6b48f2022-08-18 11:17:02 -06002154 const auto image_it = cmd_state.nv.zcull_per_image.find(image);
2155 if (image_it == cmd_state.nv.zcull_per_image.end()) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002156 return skip;
2157 }
2158 const auto& tree = image_it->second;
2159
2160 bool is_balanced = false;
2161
2162 for (uint32_t i = 0; i < subresource_range.layerCount; ++i) {
2163 const uint32_t layer = subresource_range.baseArrayLayer + i;
2164
2165 for (uint32_t j = 0; j < subresource_range.levelCount; ++j) {
2166 const uint32_t level = subresource_range.baseMipLevel + j;
2167
2168 const auto& resource = tree.GetState(layer, level);
2169 const uint64_t num_draws = resource.num_less_draws + resource.num_greater_draws;
2170
2171 if (num_draws > 0) {
2172 const uint64_t less_ratio = (resource.num_less_draws * 100) / num_draws;
2173 const uint64_t greater_ratio = (resource.num_greater_draws * 100) / num_draws;
2174
2175 if ((less_ratio > kZcullDirectionBalanceRatioNVIDIA) && (greater_ratio > kZcullDirectionBalanceRatioNVIDIA)) {
2176 is_balanced = true;
2177
2178 if (greater_ratio > less_ratio) {
2179 good_mode = "GREATER";
2180 bad_mode = "LESS";
2181 } else {
2182 good_mode = "LESS";
2183 bad_mode = "GREATER";
2184 }
2185 break;
2186 }
2187 }
2188 }
2189 if (is_balanced) {
2190 break;
2191 }
2192 }
2193
2194 if (is_balanced) {
2195 skip |= LogPerformanceWarning(
Mark Young0a6b48f2022-08-18 11:17:02 -06002196 cmd_state.commandBuffer(), kVUID_BestPractices_Zcull_LessGreaterRatio,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002197 "%s Depth attachment %s is primarily rendered with depth compare op %s, but some draws use %s. "
2198 "Z-cull is disabled for the least used direction, which harms depth testing performance. "
2199 "The Z-cull direction can be reset by clearing the depth attachment, transitioning from VK_IMAGE_LAYOUT_UNDEFINED, "
2200 "using VK_ATTACHMENT_LOAD_OP_DONT_CARE, or using VK_ATTACHMENT_STORE_OP_DONT_CARE.",
Mark Young0a6b48f2022-08-18 11:17:02 -06002201 VendorSpecificTag(kBPVendorNVIDIA), report_data->FormatHandle(cmd_state.nv.zcull_scope.image).c_str(), good_mode,
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002202 bad_mode);
2203 }
2204
2205 return skip;
2206}
2207
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002208static std::array<uint32_t, 4> GetRawClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2209 std::array<uint32_t, 4> raw_color{};
2210 std::copy_n(clear_value.uint32, raw_color.size(), raw_color.data());
2211
2212 // Zero out unused components to avoid polluting the cache with garbage
2213 if (!FormatHasRed(format)) raw_color[0] = 0;
2214 if (!FormatHasGreen(format)) raw_color[1] = 0;
2215 if (!FormatHasBlue(format)) raw_color[2] = 0;
2216 if (!FormatHasAlpha(format)) raw_color[3] = 0;
2217
2218 return raw_color;
2219}
2220
2221static bool IsClearColorZeroOrOne(VkFormat format, const std::array<uint32_t, 4> clear_color) {
2222 static_assert(sizeof(float) == sizeof(uint32_t), "Mismatching float <-> uint32 sizes");
2223 const float one = 1.0f;
2224 const float zero = 0.0f;
2225 uint32_t raw_one{};
2226 uint32_t raw_zero{};
2227 memcpy(&raw_one, &one, sizeof(one));
2228 memcpy(&raw_zero, &zero, sizeof(zero));
2229
2230 const bool is_one = (!FormatHasRed(format) || (clear_color[0] == raw_one)) &&
2231 (!FormatHasGreen(format) || (clear_color[1] == raw_one)) &&
2232 (!FormatHasBlue(format) || (clear_color[2] == raw_one)) &&
2233 (!FormatHasAlpha(format) || (clear_color[3] == raw_one));
2234 const bool is_zero = (!FormatHasRed(format) || (clear_color[0] == raw_zero)) &&
2235 (!FormatHasGreen(format) || (clear_color[1] == raw_zero)) &&
2236 (!FormatHasBlue(format) || (clear_color[2] == raw_zero)) &&
2237 (!FormatHasAlpha(format) || (clear_color[3] == raw_zero));
2238 return is_one || is_zero;
2239}
2240
2241static std::string MakeCompressedFormatListNVIDIA() {
2242 std::string format_list;
2243 for (VkFormat compressed_format : kCustomClearColorCompressedFormatsNVIDIA) {
2244 if (compressed_format == kCustomClearColorCompressedFormatsNVIDIA.back()) {
2245 format_list += "or ";
2246 }
2247 format_list += string_VkFormat(compressed_format);
2248 if (compressed_format != kCustomClearColorCompressedFormatsNVIDIA.back()) {
2249 format_list += ", ";
2250 }
2251 }
2252 return format_list;
2253}
2254
2255void BestPractices::RecordClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2256 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2257
2258 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2259 if (IsClearColorZeroOrOne(format, raw_color)) {
2260 // These colors are always compressed
2261 return;
2262 }
2263
2264 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2265 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2266 // The format cannot be compressed with a custom color
2267 return;
2268 }
2269
2270 // Record custom clear color
2271 WriteLockGuard guard{clear_colors_lock_};
2272 if (clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA) {
2273 clear_colors_.insert(raw_color);
2274 }
2275}
2276
2277bool BestPractices::ValidateClearColor(VkCommandBuffer commandBuffer, VkFormat format, const VkClearColorValue& clear_value) const {
2278 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2279
2280 bool skip = false;
2281
2282 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2283 if (IsClearColorZeroOrOne(format, raw_color)) {
2284 return skip;
2285 }
2286
2287 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2288 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2289 // The format is not compressible
2290 static const std::string format_list = MakeCompressedFormatListNVIDIA();
2291
2292 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2293 "%s Clearing image with format %s without a 1.0f or 0.0f clear color. "
2294 "The clear will not get compressed in the GPU, harming performance. "
2295 "This can be fixed using a clear color of VkClearColorValue{0.0f, 0.0f, 0.0f, 0.0f}, or "
2296 "VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f}. Alternatively, use %s.",
2297 VendorSpecificTag(kBPVendorNVIDIA), string_VkFormat(format), format_list.c_str());
2298 } else {
2299 // The format is compressible
2300 bool registered = false;
2301 {
2302 ReadLockGuard guard{clear_colors_lock_};
2303 registered = clear_colors_.find(raw_color) != clear_colors_.end();
2304
2305 if (!registered) {
2306 // If it's not in the list, it might be new. Check if there's still space for new entries.
2307 registered = clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA;
2308 }
2309 }
2310 if (!registered) {
2311 std::string clear_color_str;
2312
2313 if (FormatIsUINT(format)) {
2314 clear_color_str = std::to_string(clear_value.uint32[0]) + ", " + std::to_string(clear_value.uint32[1]) + ", " +
2315 std::to_string(clear_value.uint32[2]) + ", " + std::to_string(clear_value.uint32[3]);
2316 } else if (FormatIsSINT(format)) {
2317 clear_color_str = std::to_string(clear_value.int32[0]) + ", " + std::to_string(clear_value.int32[1]) + ", " +
2318 std::to_string(clear_value.int32[2]) + ", " + std::to_string(clear_value.int32[3]);
2319 } else {
2320 clear_color_str = std::to_string(clear_value.float32[0]) + ", " + std::to_string(clear_value.float32[1]) + ", " +
2321 std::to_string(clear_value.float32[2]) + ", " + std::to_string(clear_value.float32[3]);
2322 }
2323
2324 skip |= LogPerformanceWarning(
2325 commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2326 "%s Clearing image with unregistered VkClearColorValue{%s}. "
2327 "This clear will not get compressed in the GPU, harming performance. "
2328 "The clear color is not registered because too many unique colors have been used. "
2329 "Select a discrete set of clear colors and stick to those. "
2330 "VkClearColorValue{0, 0, 0, 0} and VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f} are always registered.",
2331 VendorSpecificTag(kBPVendorNVIDIA), clear_color_str.c_str());
2332 }
2333 }
2334
2335 return skip;
2336}
2337
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002338static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2339 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
2340 const auto& subpass_info = createInfo.pSubpasses[subpass];
2341 if (subpass_info.pResolveAttachments) {
2342 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2343 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2344 }
2345 }
2346 }
2347
2348 return false;
2349}
2350
Attilio Provenzano02859b22020-02-27 14:17:28 +00002351static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2352 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002353 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002354
2355 // If an attachment is ever used as a color attachment,
2356 // resolve attachment or depth stencil attachment,
2357 // it needs to exist on tile at some point.
2358
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002359 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2360 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002361 }
2362
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002363 if (subpass_info.pResolveAttachments) {
2364 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2365 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2366 }
2367 }
2368
2369 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002370 }
2371
2372 return false;
2373}
2374
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002375static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2376 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
2377 return false;
2378 }
2379
2380 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002381 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002382
2383 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
2384 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
2385 return true;
2386 }
2387 }
2388 }
2389
2390 return false;
2391}
2392
Attilio Provenzano02859b22020-02-27 14:17:28 +00002393bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2394 const VkRenderPassBeginInfo* pRenderPassBegin) const {
2395 bool skip = false;
2396
2397 if (!pRenderPassBegin) {
2398 return skip;
2399 }
2400
Gareth Webbdc6549a2021-06-16 03:52:24 +01002401 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
2402 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
2403 "This render pass has a zero-size render area. It cannot write to any attachments, "
2404 "and can only be used for side effects such as layout transitions.");
2405 }
2406
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002407 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002408 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002409 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07002410 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06002411 if (rpabi) {
2412 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
2413 }
2414 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002415 // Check if any attachments have LOAD operation on them
2416 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002417 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002418
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002419 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02002420 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002421 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002422 }
2423
2424 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002425 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002426 }
2427
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002428 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002429
2430 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002431 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2432 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002433 }
2434
2435 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00002436 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
2437 skip |=
2438 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00002439 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00002440 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04002441 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00002442 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
2443 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
2444 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
2445 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
2446 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002447 }
2448 }
paul-lunarg7089e272022-06-20 22:19:37 +02002449
2450 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
2451
2452 bool clearing = false;
2453
2454 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
2455 const auto& attachment = rp_state->createInfo.pAttachments[att];
2456
2457 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2458 clearing = true;
2459 break;
2460 }
2461 }
2462
2463 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
2464 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
2465 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
2466 skip |= LogWarning(
2467 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
2468 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
2469 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02002470 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02002471 }
paul-lunarga0a149c2022-06-23 16:18:51 +02002472
2473 // Check if there are more clearValues than attachments
2474 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
2475 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
2476 // This could signal a bug and there seems to be no reason for this to happen on purpose.
2477 skip |= LogWarning(
2478 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
2479 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
2480 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
2481 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
2482 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002483
2484 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp_state->createInfo.pAttachments) {
2485 for (uint32_t i = 0; i < pRenderPassBegin->clearValueCount; ++i) {
2486 const auto& attachment = rp_state->createInfo.pAttachments[i];
2487 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2488 const auto& clear_color = pRenderPassBegin->pClearValues[i].color;
2489 skip |= ValidateClearColor(commandBuffer, attachment.format, clear_color);
2490 }
2491 }
2492 }
2493 }
2494
2495 return skip;
2496}
2497
2498bool BestPractices::ValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2499 bool skip = false;
2500
2501 auto cmd_state = Get<bp_state::CommandBuffer>(commandBuffer);
2502 assert(cmd_state);
2503
2504 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2505 for (uint32_t i = 0; i < pRenderingInfo->colorAttachmentCount; ++i) {
2506 const auto& color_attachment = pRenderingInfo->pColorAttachments[i];
2507 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2508 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
2509 skip |= ValidateClearColor(commandBuffer, format, color_attachment.clearValue.color);
2510 }
2511 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002512 }
2513
2514 return skip;
2515}
2516
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002517void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
2518 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002519 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002520 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
2521 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002522 }
2523}
2524
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002525void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2526 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002527 // If we're viewing a 3D slice, ignore base array layer.
2528 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002529 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 +02002530
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002531 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002532 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002533 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
2534 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002535
2536 for (uint32_t layer = 0; layer < array_layers; layer++) {
2537 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002538 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
2539 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002540 }
2541 }
2542}
2543
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002544void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2545 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
2546 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002547 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002548
2549 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002550 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002551 }
2552}
2553
paul-lunarg5eb52062022-06-27 18:57:15 +02002554void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2555 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
2556 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
2557 const CMD_BUFFER_STATE&) -> bool {
2558 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
2559 return false;
2560 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002561}
2562
LawG44d414ba2022-02-23 15:35:41 +00002563void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002564 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002565 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002566 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002567 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 -07002568 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002569 LogPerformanceWarning(
2570 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00002571 "%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 +02002572 "image was used, it was written to with STORE_OP_STORE. "
2573 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
2574 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00002575 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002576 } 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 +02002577 LogPerformanceWarning(
2578 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00002579 "%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 +02002580 "image was used, it was written to with vkCmdClear*Image(). "
2581 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00002582 "tile-based architectures.",
2583 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002584 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002585 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
2586 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002587 const char *last_cmd = nullptr;
2588 const char *vuid = nullptr;
2589 const char *suggestion = nullptr;
2590
2591 switch (last_usage) {
2592 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
2593 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
2594 last_cmd = "vkCmdBlitImage";
2595 suggestion =
2596 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2597 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
2598 "which avoids the memory roundtrip.";
2599 break;
2600 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
2601 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
2602 last_cmd = "vkCmdClear*Image";
2603 suggestion =
2604 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
2605 "tile-based architectures. "
2606 "Use LOAD_OP_CLEAR instead to clear the image for free.";
2607 break;
2608 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
2609 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
2610 last_cmd = "vkCmdCopy*Image";
2611 suggestion =
2612 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2613 "Rather than copying, just render the source image in a fragment shader in this render pass, "
2614 "which avoids the memory roundtrip.";
2615 break;
2616 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
2617 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
2618 last_cmd = "vkCmdResolveImage";
2619 suggestion =
2620 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
2621 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
2622 "which avoids the memory roundtrip.";
2623 break;
2624 default:
2625 break;
2626 }
2627
2628 LogPerformanceWarning(
2629 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00002630 "%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 +01002631 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00002632 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
2633 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002634 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002635}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002636
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002637void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
2638 uint32_t array_layer, uint32_t mip_level) {
2639 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02002640
2641 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
2642 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
2643 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
2644 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
2645 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
2646 "result in undefined behaviour.");
2647 }
2648
LawG44d414ba2022-02-23 15:35:41 +00002649 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
2650 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002651 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002652}
2653
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002654void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
2655 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
2656 cb.queue_submit_functions_after_render_pass.end());
2657 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002658}
2659
2660void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002661 RecordCmdEndRenderingCommon(commandBuffer);
2662
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002663 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002664 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2665 if (cb_node) {
2666 AddDeferredQueueOperations(*cb_node);
2667 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002668}
2669
2670void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002671 RecordCmdEndRenderingCommon(commandBuffer);
2672
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002673 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002674 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2675 if (cb_node) {
2676 AddDeferredQueueOperations(*cb_node);
2677 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002678}
2679
2680void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002681 RecordCmdEndRenderingCommon(commandBuffer);
2682
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002683 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002684 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2685 if (cb_node) {
2686 AddDeferredQueueOperations(*cb_node);
2687 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002688}
2689
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002690void BestPractices::PreCallRecordCmdEndRendering(VkCommandBuffer commandBuffer) {
2691 RecordCmdEndRenderingCommon(commandBuffer);
2692
2693 ValidationStateTracker::PreCallRecordCmdEndRendering(commandBuffer);
2694}
2695
2696void BestPractices::PreCallRecordCmdEndRenderingKHR(VkCommandBuffer commandBuffer) {
2697 RecordCmdEndRenderingCommon(commandBuffer);
2698
2699 ValidationStateTracker::PreCallRecordCmdEndRenderingKHR(commandBuffer);
2700}
2701
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002702void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
2703 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002704 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002705 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002706 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002707 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2708}
2709
2710void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
2711 const VkRenderPassBeginInfo* pRenderPassBegin,
2712 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2713 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002714 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002715 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2716}
2717
2718void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2719 const VkRenderPassBeginInfo* pRenderPassBegin,
2720 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2721 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002722 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002723 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2724}
2725
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002726void BestPractices::PreCallRecordCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2727 ValidationStateTracker::PreCallRecordCmdBeginRendering(commandBuffer, pRenderingInfo);
2728 RecordCmdBeginRenderingCommon(commandBuffer);
2729}
2730
2731void BestPractices::PreCallRecordCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2732 ValidationStateTracker::PreCallRecordCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2733 RecordCmdBeginRenderingCommon(commandBuffer);
2734}
2735
2736void BestPractices::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
2737 ValidationStateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
2738
2739 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2740 auto rp = cmd_state->activeRenderPass.get();
2741 assert(rp);
2742
2743 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2744 IMAGE_VIEW_STATE* depth_image_view = nullptr;
2745
2746 const auto depth_attachment = rp->createInfo.pSubpasses[cmd_state->activeSubpass].pDepthStencilAttachment;
2747 if (depth_attachment) {
2748 const uint32_t attachment_index = depth_attachment->attachment;
2749 if (attachment_index != VK_ATTACHMENT_UNUSED) {
2750 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
2751 }
2752 }
2753 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
2754 const VkImage depth_image = depth_image_view->image_state->image();
2755 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
2756 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
2757 } else {
2758 RecordUnbindZcullScope(*cmd_state);
2759 }
2760 }
2761}
2762
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002763void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002764
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002765 if (!pRenderPassBegin) {
2766 return;
2767 }
2768
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002769 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002770
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002771 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002772 if (rp_state) {
2773 // Check load ops
2774 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002775 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002776
2777 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
2778 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2779 continue;
2780 }
2781
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002782 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002783
2784 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
2785 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002786 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002787 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
2788 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002789 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002790 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002791 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002792 }
2793
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002794 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002795 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002796
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002797 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002798 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2799 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002800 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002801 }
2802 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002803 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002804 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002805
Jeremy Gebben9f537102021-10-05 16:37:12 -06002806 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002807 }
2808
2809 // Check store ops
2810 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002811 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002812
2813 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2814 continue;
2815 }
2816
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002817 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002818
2819 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2820 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002821 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002822 }
2823
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002824 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002825
Jeremy Gebben9f537102021-10-05 16:37:12 -06002826 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002827 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002828 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2829 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002830 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002831 }
2832 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002833 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002834 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002835
Jeremy Gebben9f537102021-10-05 16:37:12 -06002836 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002837 }
2838 }
2839}
2840
Attilio Provenzano02859b22020-02-27 14:17:28 +00002841bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2842 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002843 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2844 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002845 return skip;
2846}
2847
2848bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2849 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002850 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002851 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2852 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002853 return skip;
2854}
2855
2856bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002857 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002858 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2859 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002860 return skip;
2861}
2862
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002863bool BestPractices::PreCallValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2864 bool skip = StateTracker::PreCallValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2865 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2866 return skip;
2867}
2868
2869bool BestPractices::PreCallValidateCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2870 bool skip = StateTracker::PreCallValidateCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2871 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2872 return skip;
2873}
2874
Sam Walls0961ec02020-03-31 16:39:15 +01002875void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2876 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002877 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002878 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002879 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2880 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002881 assert(cb);
2882 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002883 render_pass_state.touchesAttachments.clear();
2884 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002885 render_pass_state.numDrawCallsDepthOnly = 0;
2886 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2887 render_pass_state.colorAttachment = false;
2888 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002889 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002890 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002891
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03002892 // Reset NV state
2893 cb->nv = {};
2894
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002895 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002896
2897 // track depth / color attachment usage within the renderpass
2898 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2899 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002900 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002901
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002902 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002903 }
2904}
2905
2906void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2907 VkSubpassContents contents) {
2908 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2909 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2910}
2911
2912void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2913 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2914 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2915 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2916}
2917
2918void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2919 const VkRenderPassBeginInfo* pRenderPassBegin,
2920 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2921 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2922 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2923}
2924
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002925// Generic function to handle validation for all CmdDraw* type functions
2926bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2927 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002928 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002929 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002930 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2931 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002932 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002933
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002934 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002935 if (pipeline_state && pipeline_state->vertex_input_state &&
2936 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002937 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002938 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002939 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002940 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2941 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002942 }
2943 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002944
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002945 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002946 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002947 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002948 if (rp_state) {
2949 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2950 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002951 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002952 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002953 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2954 const auto* raster_state = pipe->RasterizationState();
2955 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2956 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002957 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2958 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2959 }
2960 }
2961 }
2962 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002963 }
2964 return skip;
2965}
2966
Sam Walls0961ec02020-03-31 16:39:15 +01002967void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002968 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002969 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002970 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002971 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002972 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002973 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2974 RecordCmdDrawTypeNVIDIA(*cb_node);
2975 }
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002976
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002977 if (cb_node->render_pass_state.drawTouchAttachments) {
2978 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2979 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002980 }
2981 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002982 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002983 }
2984}
2985
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002986void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2987 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002988 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2989 // depth prepass warnings First find the lowest enabled draw count
2990 uint32_t lowestEnabledMinDrawCount = 0;
2991 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2992 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2993 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2994
2995 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002996 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
2997 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01002998 }
2999}
3000
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003001void BestPractices::RecordCmdDrawTypeNVIDIA(bp_state::CommandBuffer& cmd_state) {
3002 assert(VendorCheckEnabled(kBPVendorNVIDIA));
3003
3004 if (cmd_state.nv.depth_test_enable && cmd_state.nv.zcull_direction != bp_state::CommandBufferStateNV::ZcullDirection::Unknown) {
3005 RecordSetScopeZcullDirection(cmd_state, cmd_state.nv.zcull_direction);
3006 RecordZcullDraw(cmd_state);
3007 }
3008}
3009
Camden5b184be2019-08-13 07:50:19 -06003010bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003011 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003012 bool skip = false;
3013
3014 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003015 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3016 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003017 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06003018 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06003019
3020 return skip;
3021}
3022
Sam Walls0961ec02020-03-31 16:39:15 +01003023void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3024 uint32_t firstVertex, uint32_t firstInstance) {
3025 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
3026 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
3027}
3028
Camden5b184be2019-08-13 07:50:19 -06003029bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003030 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003031 bool skip = false;
3032
3033 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003034 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3035 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003036 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003037 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
3038
Attilio Provenzano02859b22020-02-27 14:17:28 +00003039 // Check if we reached the limit for small indexed draw calls.
3040 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003041 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003042 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003043 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00003044 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003045 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00003046 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00003047 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
3048 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00003049 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
3050 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003051 }
3052
Sam Walls8e77e4f2020-03-16 20:47:40 +00003053 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003054 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003055 }
3056
3057 return skip;
3058}
3059
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003060bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00003061 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
3062 bool skip = false;
3063
3064 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00003065
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003066 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
3067 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003068
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003069 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003070 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00003071 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
3072 const void* ib_mem = ib_mem_state.p_driver_data;
3073 bool primitive_restart_enable = false;
3074
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003075 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003076 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003077 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003078
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07003079 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
3080 if (ia_state) {
3081 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003082 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00003083
3084 // 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 -06003085 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00003086 uint32_t scan_stride;
3087 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3088 scan_stride = sizeof(uint8_t);
3089 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3090 scan_stride = sizeof(uint16_t);
3091 } else {
3092 scan_stride = sizeof(uint32_t);
3093 }
3094
3095 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
3096 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
3097
3098 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
3099 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
3100 // irrespective of whether or not they're part of the draw call.
3101
3102 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
3103 uint32_t min_index = ~0u;
3104 // start with maximum as 0 and adjust to indices in the buffer
3105 uint32_t max_index = 0u;
3106
3107 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
3108 // for the given index buffer
3109 uint32_t vertex_shade_count = 0;
3110
3111 PostTransformLRUCacheModel post_transform_cache;
3112
3113 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
3114 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
3115 // target architecture.
3116 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
3117 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
3118 post_transform_cache.resize(32);
3119
3120 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3121 uint32_t scan_index;
3122 uint32_t primitive_restart_value;
3123 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3124 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3125 primitive_restart_value = 0xFF;
3126 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3127 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3128 primitive_restart_value = 0xFFFF;
3129 } else {
3130 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3131 primitive_restart_value = 0xFFFFFFFF;
3132 }
3133
3134 max_index = std::max(max_index, scan_index);
3135 min_index = std::min(min_index, scan_index);
3136
3137 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
3138 bool in_cache = post_transform_cache.query_cache(scan_index);
3139 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
3140 if (!in_cache) vertex_shade_count++;
3141 }
3142 }
3143
3144 // 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 +01003145 // 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
3146 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003147
3148 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07003149 skip |=
3150 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3151 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
3152 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
3153 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
3154 "maximum would be loaded, and possibly shaded, whether or not they are used.",
3155 VendorSpecificTag(kBPVendorArm),
3156 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003157 return skip;
3158 }
3159
3160 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
3161 // 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 +01003162 const size_t refs_per_bucket = 64;
3163 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
3164
3165 const uint32_t n_indices = max_index - min_index + 1;
3166 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
3167 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
3168
3169 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
3170 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00003171
3172 // To avoid using too much memory, we run over the indices again.
3173 // Knowing the size from the last scan allows us to record index usage with bitsets
3174 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3175 uint32_t scan_index;
3176 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3177 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3178 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3179 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3180 } else {
3181 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3182 }
3183 // keep track of the set of all indices used to reference vertices in the draw call
3184 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01003185 size_t bitset_bucket_index = index_offset / refs_per_bucket;
3186 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003187 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
3188 }
3189
3190 uint32_t vertex_reference_count = 0;
3191 for (const auto& bitset : vertex_reference_buckets) {
3192 vertex_reference_count += static_cast<uint32_t>(bitset.count());
3193 }
3194
3195 // 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 -07003196 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003197 // 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 -07003198 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003199
3200 if (utilization < 0.5f) {
3201 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3202 "%s The indices which were specified for the draw call only utilise approximately "
3203 "%.02f%% of the bound vertex buffer.",
3204 VendorSpecificTag(kBPVendorArm), utilization);
3205 }
3206
3207 if (cache_hit_rate <= 0.5f) {
3208 skip |=
3209 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
3210 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
3211 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
3212 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
3213 "recently shaded vertices.",
3214 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
3215 }
3216 }
3217
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003218 return skip;
3219}
3220
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003221bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3222 const VkCommandBuffer* pCommandBuffers) const {
3223 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003224 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003225 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003226 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003227 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003228 continue;
3229 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003230 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003231 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003232 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
3233 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003234 }
3235 }
3236 }
Nadav Gevaf0808442021-05-21 13:51:25 -04003237
3238 if (VendorCheckEnabled(kBPVendorAMD)) {
3239 if (commandBufferCount > 0) {
3240 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
3241 "%s Performance warning: Use of secondary command buffers is not recommended. ",
3242 VendorSpecificTag(kBPVendorAMD));
3243 }
3244 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003245 return skip;
3246}
3247
3248void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3249 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003250 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
3251
3252 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3253 if (!primary) {
3254 return;
3255 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003256
3257 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003258 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
3259 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003260 continue;
3261 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003262
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003263 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
3264 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
3265 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
3266 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003267 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003268 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003269 }
3270 }
3271
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003272 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
3273 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003274 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02003275
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003276 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
3277 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003278 }
3279
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003280}
3281
Rodrigo Locatti7d716e12022-03-09 19:15:17 -03003282bool BestPractices::PreCallValidateCmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer,
3283 const VkAccelerationStructureInfoNV* pInfo,
3284 VkBuffer instanceData, VkDeviceSize instanceOffset,
3285 VkBool32 update, VkAccelerationStructureNV dst,
3286 VkAccelerationStructureNV src, VkBuffer scratch,
3287 VkDeviceSize scratchOffset) const {
3288 return ValidateBuildAccelerationStructure(commandBuffer);
3289}
3290
3291bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresIndirectKHR(
3292 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3293 const VkDeviceAddress* pIndirectDeviceAddresses, const uint32_t* pIndirectStrides,
3294 const uint32_t* const* ppMaxPrimitiveCounts) const {
3295 return ValidateBuildAccelerationStructure(commandBuffer);
3296}
3297
3298bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresKHR(
3299 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3300 const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const {
3301 return ValidateBuildAccelerationStructure(commandBuffer);
3302}
3303
3304bool BestPractices::ValidateBuildAccelerationStructure(VkCommandBuffer commandBuffer) const {
3305 bool skip = false;
3306 auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
3307 assert(cb_node);
3308
3309 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3310 if ((cb_node->GetQueueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) {
3311 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_AccelerationStructure_NotAsync,
3312 "%s Performance warning: Prefer building acceleration structures on an asynchronous "
3313 "compute queue, instead of using the universal graphics queue.",
3314 VendorSpecificTag(kBPVendorNVIDIA));
3315 }
3316 }
3317
3318 return skip;
3319}
3320
Rodrigo Locatti66b23352022-03-15 17:28:32 -03003321bool BestPractices::ValidateBindMemory(VkDevice device, VkDeviceMemory memory) const {
3322 bool skip = false;
3323
3324 if (VendorCheckEnabled(kBPVendorNVIDIA) && device_extensions.vk_ext_pageable_device_local_memory) {
3325 auto mem_info = std::static_pointer_cast<const bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
3326 if (!mem_info->dynamic_priority) {
3327 skip |=
3328 LogPerformanceWarning(device, kVUID_BestPractices_BindMemory_NoPriority,
3329 "%s Use vkSetDeviceMemoryPriorityEXT to provide the OS with information on which allocations "
3330 "should stay in memory and which should be demoted first when video memory is limited. The "
3331 "highest priority should be given to GPU-written resources like color attachments, depth "
3332 "attachments, storage images, and buffers written from the GPU.",
3333 VendorSpecificTag(kBPVendorNVIDIA));
3334 }
3335 }
3336
3337 return skip;
3338}
3339
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003340void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
3341 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003342 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003343 auto itr =
3344 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3345 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003346
3347 if (itr != state.touchesAttachments.end()) {
3348 itr->aspects |= aspects;
3349 } else {
3350 state.touchesAttachments.push_back({ fb_attachment, aspects });
3351 }
3352}
3353
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003354void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003355 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
3356 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003357 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003358 // If we observe a full clear before any other access to a frame buffer attachment,
3359 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003360 auto itr =
3361 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3362 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003363
3364 uint32_t new_aspects = aspects;
3365 if (itr != state.touchesAttachments.end()) {
3366 new_aspects = aspects & ~itr->aspects;
3367 itr->aspects |= aspects;
3368 } else {
3369 state.touchesAttachments.push_back({ fb_attachment, aspects });
3370 }
3371
3372 if (new_aspects == 0) {
3373 return;
3374 }
3375
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003376 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003377 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
3378 // CmdExecuteCommands.
3379 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
3380 std::vector<VkClearRect>{pRects, pRects + rectCount} });
3381 }
3382}
3383
3384void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
3385 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
3386 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003387 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
3388
3389 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3390 auto* rp_state = cmd_state->activeRenderPass.get();
3391 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003392 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
3393
3394 if (rectCount == 0 || !rp_state) {
3395 return;
3396 }
3397
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003398 if (!is_secondary && !fb_state && !rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003399 return;
3400 }
3401
3402 // 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 -03003403 const bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003404
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003405 if (rp_state->UsesDynamicRendering()) {
3406 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003407 auto pColorAttachments = rp_state->dynamic_rendering_begin_rendering_info.pColorAttachments;
3408
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003409 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003410 auto& clear_attachment = pClearAttachments[i];
3411
3412 if (clear_attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003413 RecordResetScopeZcullDirection(*cmd_state);
3414 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003415 if ((clear_attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) &&
3416 clear_attachment.colorAttachment != VK_ATTACHMENT_UNUSED &&
3417 pColorAttachments) {
3418 const auto& attachment = pColorAttachments[clear_attachment.colorAttachment];
3419 if (attachment.imageView) {
3420 auto image_view_state = Get<IMAGE_VIEW_STATE>(attachment.imageView);
3421 const VkFormat format = image_view_state->create_info.format;
3422 RecordClearColor(format, clear_attachment.clearValue.color);
3423 }
3424 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003425 }
3426 }
3427
3428 // TODO: Implement other best practices for dynamic rendering
3429
3430 } else {
ziga-lunarg885c6542022-03-07 01:08:25 +01003431 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
3432 for (uint32_t i = 0; i < attachmentCount; i++) {
3433 auto& attachment = pClearAttachments[i];
3434 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
3435 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003436
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003437 if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
3438 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3439 RecordResetScopeZcullDirection(*cmd_state);
3440 }
3441 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003442 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
3443 if (subpass.pDepthStencilAttachment) {
3444 fb_attachment = subpass.pDepthStencilAttachment->attachment;
3445 }
3446 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
3447 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003448 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003449 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
3450 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003451 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01003452 aspects, rectCount, pRects);
3453 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003454 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01003455 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003456 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3457 const VkFormat format = rp_state->createInfo.pAttachments[fb_attachment].format;
3458 RecordClearColor(format, attachment.clearValue.color);
3459 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003460 }
3461 }
3462 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003463}
3464
Attilio Provenzano02859b22020-02-27 14:17:28 +00003465void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3466 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3467 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
3468 firstInstance);
3469
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003470 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003471 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
3472 cmd_state->small_indexed_draw_call_count++;
3473 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003474
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003475 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00003476}
3477
Sam Walls0961ec02020-03-31 16:39:15 +01003478void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3479 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3480 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
3481 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
3482}
3483
Camden5b184be2019-08-13 07:50:19 -06003484bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003485 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003486 bool skip = false;
3487
3488 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003489 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3490 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003491 }
3492
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003493 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
3494
Camden5b184be2019-08-13 07:50:19 -06003495 return skip;
3496}
3497
Sam Walls0961ec02020-03-31 16:39:15 +01003498void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3499 uint32_t count, uint32_t stride) {
3500 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
3501 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
3502}
3503
Camden5b184be2019-08-13 07:50:19 -06003504bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003505 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003506 bool skip = false;
3507
3508 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003509 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3510 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003511 }
3512
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003513 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
3514
Camden5b184be2019-08-13 07:50:19 -06003515 return skip;
3516}
3517
Sam Walls0961ec02020-03-31 16:39:15 +01003518void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3519 uint32_t count, uint32_t stride) {
3520 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
3521 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
3522}
3523
Rodrigo Locatti467344a2022-03-30 18:48:13 -03003524bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3525 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3526 uint32_t maxDrawCount, uint32_t stride) const {
3527 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
3528
3529 return skip;
3530}
3531
3532void BestPractices::PostCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3533 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3534 uint32_t maxDrawCount, uint32_t stride) {
3535 StateTracker::PostCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3536 maxDrawCount, stride);
3537 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCount()");
3538}
3539
3540bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3541 VkDeviceSize offset, VkBuffer countBuffer,
3542 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3543 uint32_t stride) const {
3544 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountAMD");
3545
3546 return skip;
3547}
3548
3549void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3550 VkDeviceSize offset, VkBuffer countBuffer,
3551 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3552 uint32_t stride) {
3553 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3554 maxDrawCount, stride);
3555 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountAMD()");
3556}
3557
3558bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3559 VkDeviceSize offset, VkBuffer countBuffer,
3560 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3561 uint32_t stride) const {
3562 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR");
3563
3564 return skip;
3565}
3566
3567void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3568 VkDeviceSize offset, VkBuffer countBuffer,
3569 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3570 uint32_t stride) {
3571 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3572 maxDrawCount, stride);
3573 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountKHR()");
3574}
3575
3576bool BestPractices::PreCallValidateCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3577 uint32_t firstInstance, VkBuffer counterBuffer,
3578 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3579 uint32_t vertexStride) const {
3580 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectByteCountEXT");
3581
3582 return skip;
3583}
3584
3585void BestPractices::PostCallRecordCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3586 uint32_t firstInstance, VkBuffer counterBuffer,
3587 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3588 uint32_t vertexStride) {
3589 StateTracker::PostCallRecordCmdDrawIndirectByteCountEXT(commandBuffer, instanceCount, firstInstance, counterBuffer,
3590 counterBufferOffset, counterOffset, vertexStride);
3591 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectByteCountEXT()");
3592}
3593
3594bool BestPractices::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3595 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3596 uint32_t stride) const {
3597 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCount");
3598
3599 return skip;
3600}
3601
3602void BestPractices::PostCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3603 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3604 uint32_t stride) {
3605 StateTracker::PostCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3606 stride);
3607 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCount()");
3608}
3609
3610bool BestPractices::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3611 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3612 uint32_t maxDrawCount, uint32_t stride) const {
3613 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountAMD");
3614
3615 return skip;
3616}
3617
3618void BestPractices::PostCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3619 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3620 uint32_t maxDrawCount, uint32_t stride) {
3621 StateTracker::PostCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3622 stride);
3623 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountAMD()");
3624}
3625
3626bool BestPractices::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3627 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3628 uint32_t maxDrawCount, uint32_t stride) const {
3629 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountKHR");
3630
3631 return skip;
3632}
3633
3634void BestPractices::PostCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3635 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3636 uint32_t maxDrawCount, uint32_t stride) {
3637 StateTracker::PostCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3638 stride);
3639 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountKHR()");
3640}
3641
3642bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3643 VkDeviceSize offset, VkBuffer countBuffer,
3644 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3645 uint32_t stride) const {
3646 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectCountNV");
3647
3648 return skip;
3649}
3650
3651void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3652 VkDeviceSize offset, VkBuffer countBuffer,
3653 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3654 uint32_t stride) {
3655 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectCountNV(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3656 maxDrawCount, stride);
3657 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectCountNV()");
3658}
3659
3660bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3661 uint32_t drawCount, uint32_t stride) const {
3662 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectNV");
3663
3664 return skip;
3665}
3666
3667void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3668 uint32_t drawCount, uint32_t stride) {
3669 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectNV(commandBuffer, buffer, offset, drawCount, stride);
3670 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectNV()");
3671}
3672
3673bool BestPractices::PreCallValidateCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) const {
3674 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksNV");
3675
3676 return skip;
3677}
3678
3679void BestPractices::PostCallRecordCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) {
3680 StateTracker::PostCallRecordCmdDrawMeshTasksNV(commandBuffer, taskCount, firstTask);
3681 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksNV()");
3682}
3683
3684bool BestPractices::PreCallValidateCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3685 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3686 uint32_t firstInstance, uint32_t stride,
3687 const int32_t* pVertexOffset) const {
3688 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiIndexedEXT");
3689
3690 return skip;
3691}
3692
3693void BestPractices::PostCallRecordCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3694 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3695 uint32_t firstInstance, uint32_t stride, const int32_t* pVertexOffset) {
3696 StateTracker::PostCallRecordCmdDrawMultiIndexedEXT(commandBuffer, drawCount, pIndexInfo, instanceCount, firstInstance, stride,
3697 pVertexOffset);
3698 uint32_t count = 0;
3699 for (uint32_t i = 0; i < drawCount; ++i) {
3700 count += pIndexInfo[i].indexCount;
3701 }
3702 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiIndexedEXT()");
3703}
3704
3705bool BestPractices::PreCallValidateCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount, const VkMultiDrawInfoEXT* pVertexInfo,
3706 uint32_t instanceCount, uint32_t firstInstance, uint32_t stride) const {
3707 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiEXT");
3708
3709 return skip;
3710}
3711
3712void BestPractices::PostCallRecordCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3713 const VkMultiDrawInfoEXT* pVertexInfo, uint32_t instanceCount,
3714 uint32_t firstInstance, uint32_t stride) {
3715 StateTracker::PostCallRecordCmdDrawMultiEXT(commandBuffer, drawCount, pVertexInfo, instanceCount, firstInstance, stride);
3716 uint32_t count = 0;
3717 for (uint32_t i = 0; i < drawCount; ++i) {
3718 count += pVertexInfo[i].vertexCount;
3719 }
3720 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiEXT()");
3721}
3722
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003723void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
3724 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003725 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003726 // For bindless scenarios, we should not attempt to track descriptor set state.
3727 // It is highly uncertain which resources are actually bound.
3728 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003729 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
3730 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003731 continue;
3732 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003733
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003734 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003735 VkImageView image_view{VK_NULL_HANDLE};
3736
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003737 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02003738 if (!descriptor) {
3739 continue;
3740 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003741 switch (descriptor->GetClass()) {
3742 case cvdescriptorset::DescriptorClass::Image: {
3743 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
3744 image_view = image_descriptor->GetImageView();
3745 }
3746 break;
3747 }
3748 case cvdescriptorset::DescriptorClass::ImageSampler: {
3749 if (const auto image_sampler_descriptor =
3750 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
3751 image_view = image_sampler_descriptor->GetImageView();
3752 }
3753 break;
3754 }
3755 default:
3756 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003757 }
3758
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003759 if (image_view) {
3760 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
3761 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
3762 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003763 }
3764 }
3765 }
3766 }
3767}
3768
3769void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3770 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003771 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3772 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003773}
3774
3775void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3776 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003777 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3778 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003779}
3780
3781void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3782 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003783 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3784 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003785}
3786
Camden5b184be2019-08-13 07:50:19 -06003787bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003788 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06003789 bool skip = false;
3790
3791 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003792 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
3793 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
3794 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
3795 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06003796 }
3797
3798 return skip;
3799}
Camden83a9c372019-08-14 11:41:38 -06003800
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003801bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3802 bool skip = false;
3803 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3804 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003805 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003806 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3807 assert(cmd_state);
3808 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003809 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003810 return skip;
3811}
3812
3813bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3814 bool skip = false;
3815 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3816 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003817 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003818 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3819 assert(cmd_state);
3820 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003821 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003822 return skip;
3823}
3824
Sam Walls0961ec02020-03-31 16:39:15 +01003825bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3826 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01003827 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003828 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003829 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003830 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3831 assert(cmd_state);
3832 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003833 }
3834 return skip;
3835}
3836
3837bool BestPractices::PreCallValidateCmdEndRendering(VkCommandBuffer commandBuffer) const {
3838 bool skip = false;
3839 skip |= StateTracker::PreCallValidateCmdEndRendering(commandBuffer);
3840 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003841 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3842 assert(cmd_state);
3843 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003844 }
3845 return skip;
3846}
3847
3848bool BestPractices::PreCallValidateCmdEndRenderingKHR(VkCommandBuffer commandBuffer) const {
3849 bool skip = false;
3850 skip |= StateTracker::PreCallValidateCmdEndRenderingKHR(commandBuffer);
3851 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06003852 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
3853 assert(cmd_state);
3854 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003855 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003856 return skip;
3857}
3858
3859bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3860 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003861 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01003862
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003863 if (cmd == nullptr) return skip;
3864 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01003865
LawG4b21485c2022-02-28 13:46:48 +00003866 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
3867 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
3868 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
3869 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
3870 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
3871
3872 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01003873 bool uses_depth =
3874 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01003875 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00003876
Sam Walls0961ec02020-03-31 16:39:15 +01003877 if (uses_depth) {
3878 skip |= LogPerformanceWarning(
3879 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00003880 "%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 +00003881 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
3882 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
3883 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
3884 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01003885 }
3886
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003887 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
3888
LawG40da9c3d2022-03-01 09:51:01 +00003889 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003890 // If we use an attachment on-tile, we should access it in some way. Otherwise,
3891 // it is redundant to have it be part of the render pass.
3892 // Only consider it redundant if it will actually consume bandwidth, i.e.
3893 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
3894 // as is using pure input attachments.
3895 // CLEAR -> STORE might be considered a "useful" thing to do, but
3896 // the optimal thing to do is to defer the clear until you're actually
3897 // going to render to the image.
3898
3899 uint32_t num_attachments = rp->createInfo.attachmentCount;
3900 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02003901 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
3902 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003903 continue;
3904 }
3905
3906 auto& attachment = rp->createInfo.pAttachments[i];
3907
3908 VkImageAspectFlags bandwidth_aspects = 0;
3909
3910 if (!FormatIsStencilOnly(attachment.format) &&
3911 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3912 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3913 if (FormatHasDepth(attachment.format)) {
3914 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
3915 } else {
3916 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
3917 }
3918 }
3919
3920 if (FormatHasStencil(attachment.format) &&
3921 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3922 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3923 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
3924 }
3925
3926 if (!bandwidth_aspects) {
3927 continue;
3928 }
3929
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003930 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003931 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003932 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003933 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003934 untouched_aspects &= ~itr->aspects;
3935 }
3936
3937 if (untouched_aspects) {
3938 skip |= LogPerformanceWarning(
3939 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00003940 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003941 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00003942 "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 +00003943 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00003944 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003945 }
3946 }
3947 }
3948
Sam Walls0961ec02020-03-31 16:39:15 +01003949 return skip;
3950}
3951
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003952void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003953 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3954 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003955}
3956
3957void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003958 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3959 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003960}
3961
Camden Stocker9c051442019-11-06 14:28:43 -08003962bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
3963 const char* api_name) const {
3964 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003965 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08003966
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003967 if (bp_pd_state) {
3968 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
3969 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
3970 "Potential problem with calling %s() without first retrieving properties from "
3971 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
3972 api_name);
3973 }
Camden Stocker9c051442019-11-06 14:28:43 -08003974 }
3975
3976 return skip;
3977}
3978
Camden83a9c372019-08-14 11:41:38 -06003979bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003980 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06003981 bool skip = false;
3982
Camden Stocker9c051442019-11-06 14:28:43 -08003983 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06003984
Camden Stocker9c051442019-11-06 14:28:43 -08003985 return skip;
3986}
3987
3988bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
3989 uint32_t planeIndex,
3990 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
3991 bool skip = false;
3992
3993 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
3994
3995 return skip;
3996}
3997
3998bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
3999 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
4000 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
4001 bool skip = false;
4002
4003 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06004004
4005 return skip;
4006}
Camden05de2d42019-08-19 10:23:56 -06004007
4008bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004009 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06004010 bool skip = false;
4011
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004012 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06004013
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004014 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06004015 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004016 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004017 skip |=
4018 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
4019 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
4020 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06004021 }
Camden05de2d42019-08-19 10:23:56 -06004022
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004023 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
4024 skip |= LogWarning(
4025 device, kVUID_BestPractices_Swapchain_InvalidCount,
4026 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04004027 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004028 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
4029 }
4030 }
4031
Camden05de2d42019-08-19 10:23:56 -06004032 return skip;
4033}
4034
4035// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004036bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004037 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004038 const CALL_STATE call_state,
4039 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06004040 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004041 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
4042 if (UNCALLED == call_state) {
4043 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004044 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004045 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
4046 "recommended "
4047 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
4048 caller_name, caller_name);
4049 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004050 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
4051 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004052 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
4053 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
4054 ". It is recommended to instead receive all the properties by calling %s with "
4055 "pQueueFamilyPropertyCount that was "
4056 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004057 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004058 caller_name);
Camden05de2d42019-08-19 10:23:56 -06004059 }
4060
4061 return skip;
4062}
4063
Jeff Bolz5c801d12019-10-09 10:38:45 -05004064bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
4065 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06004066 bool skip = false;
4067
4068 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004069 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06004070 if (!as_state->memory_requirements_checked) {
4071 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
4072 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
4073 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004074 skip |= LogWarning(
4075 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06004076 "vkBindAccelerationStructureMemoryNV(): "
4077 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
4078 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
4079 }
4080 }
4081
4082 return skip;
4083}
4084
Camden05de2d42019-08-19 10:23:56 -06004085bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
4086 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004087 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004088 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004089 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004090 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004091 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
4092 "vkGetPhysicalDeviceQueueFamilyProperties()");
4093 }
4094 return false;
Camden05de2d42019-08-19 10:23:56 -06004095}
4096
Mike Schuchardt2df08912020-12-15 16:28:09 -08004097bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
4098 uint32_t* pQueueFamilyPropertyCount,
4099 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004100 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004101 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004102 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004103 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
4104 "vkGetPhysicalDeviceQueueFamilyProperties2()");
4105 }
4106 return false;
Camden05de2d42019-08-19 10:23:56 -06004107}
4108
Jeff Bolz5c801d12019-10-09 10:38:45 -05004109bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08004110 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004111 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004112 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004113 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004114 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
4115 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
4116 }
4117 return false;
Camden05de2d42019-08-19 10:23:56 -06004118}
4119
4120bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
4121 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004122 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06004123 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004124 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06004125 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06004126 bool skip = false;
4127 if (call_state == UNCALLED) {
4128 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
4129 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004130 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
4131 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
4132 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06004133 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004134 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004135 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
4136 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
4137 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
4138 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004139 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06004140 }
4141 }
4142 return skip;
4143}
Camden Stocker23cc47d2019-09-03 14:53:57 -06004144
4145bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004146 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004147 bool skip = false;
4148
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004149 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4150 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06004151 // 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 -07004152 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004153 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
4154 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07004155 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06004156 // 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 -07004157 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
4158 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004159 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004160 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004161 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004162 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004163 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004164 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4165 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4166 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004167 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004168 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4169 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004170 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004171 }
4172 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004173 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004174 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004175 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004176 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4177 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004178 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004179 }
4180 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004181 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4182 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004183 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004184 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004185 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004186 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004187 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004188 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4189 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4190 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004191 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004192 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4193 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004194 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004195 }
4196 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004197 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004198 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004199 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004200 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4201 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004202 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004203 }
4204 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4205 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004206 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004207 }
4208 }
4209 }
4210 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004211 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
4212 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004213 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004214 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004215 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
4216 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004217 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004218 }
4219 }
4220 }
4221
Rodrigo Locatti7ab778d2022-03-09 18:57:15 -03004222 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4223 auto queue_state = Get<QUEUE_STATE>(queue);
4224 if (queue_state && queue_state->queueFamilyProperties.queueFlags != (VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT)) {
4225 skip |= LogPerformanceWarning(queue, kVUID_BestPractices_QueueBindSparse_NotAsync,
4226 "vkQueueBindSparse() issued on queue %s. All binds should happen on an asynchronous copy "
4227 "queue to hide the OS scheduling and submit costs.",
4228 report_data->FormatHandle(queue).c_str());
4229 }
4230 }
4231
Camden Stocker23cc47d2019-09-03 14:53:57 -06004232 return skip;
4233}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004234
Mark Lobodzinski84101d72020-04-24 09:43:48 -06004235void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
4236 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004237 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004238 return;
4239 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004240
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004241 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4242 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
4243 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4244 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004245 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004246 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004247 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004248 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004249 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4250 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
4251 image_state->sparse_metadata_bound = true;
4252 }
4253 }
4254 }
4255 }
4256}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004257
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004258bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004259 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004260 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004261 // We don't know the accurate render area in a secondary,
4262 // so assume we clear the entire frame buffer.
4263 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
4264 return true;
4265 }
4266
4267 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
4268 for (uint32_t i = 0; i < rectCount; i++) {
4269 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004270 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004271 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
4272 return true;
4273 }
4274 }
4275
4276 return false;
4277}
4278
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004279bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
4280 VkImageAspectFlags aspects, bool secondary) const {
4281 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004282 bool skip = false;
4283
4284 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
4285 return skip;
4286 }
4287
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004288 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004289
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004290 auto attachment_itr =
4291 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
4292 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004293
4294 // Only report aspects which haven't been touched yet.
4295 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004296 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004297 new_aspects &= ~attachment_itr->aspects;
4298 }
4299
4300 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09004301 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004302 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004303 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02004304 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
4305 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004306 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004307 }
4308
4309 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
4310 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
4311 skip |= LogPerformanceWarning(
4312 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4313 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
4314 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4315 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004316 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004317 }
4318
4319 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4320 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004321 skip |=
4322 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4323 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
4324 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4325 "it is more efficient.",
4326 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004327
4328 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004329 const auto cmd_state = GetRead<bp_state::CommandBuffer>(cmd.commandBuffer());
4330 assert(cmd_state);
4331 skip |= ValidateZcullScope(*cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004332 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004333 }
4334
4335 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
4336 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004337 skip |=
4338 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4339 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
4340 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4341 "it is more efficient.",
4342 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004343 }
4344
4345 return skip;
4346}
4347
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004348bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06004349 const VkClearAttachment* pAttachments, uint32_t rectCount,
4350 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004351 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004352 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004353 if (!cb_node) return skip;
4354
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004355 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
4356 // Defer checks to ExecuteCommands.
4357 return skip;
4358 }
4359
4360 // Only care about full clears, partial clears might have legitimate uses.
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004361 const bool is_full_clear = ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004362
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004363 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
4364 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06004365 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004366 if (rp) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004367 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004368 const auto pColorAttachments = rp->dynamic_rendering_begin_rendering_info.pColorAttachments;
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004369
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004370 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4371 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004372 const auto& attachment = pAttachments[i];
4373 if (attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004374 skip |= ValidateZcullScope(*cb_node);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004375 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004376 if ((attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) && attachment.colorAttachment != VK_ATTACHMENT_UNUSED) {
4377 const auto& color_attachment = pColorAttachments[attachment.colorAttachment];
4378 if (color_attachment.imageView) {
4379 auto image_view_state = Get<IMAGE_VIEW_STATE>(color_attachment.imageView);
4380 const VkFormat format = image_view_state->create_info.format;
4381 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4382 }
4383 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004384 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004385 }
4386
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004387 if (is_full_clear) {
4388 // TODO: Implement ValidateClearAttachment for dynamic rendering
4389 }
4390
4391 } else {
4392 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
4393
4394 if (is_full_clear) {
4395 for (uint32_t i = 0; i < attachmentCount; i++) {
4396 const auto& attachment = pAttachments[i];
4397
4398 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4399 uint32_t color_attachment = attachment.colorAttachment;
4400 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
4401 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
4402 }
4403
4404 if (subpass.pDepthStencilAttachment &&
4405 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
4406 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
4407 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
4408 }
4409 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004410 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004411 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp->createInfo.pAttachments) {
4412 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; ++attachment_idx) {
4413 const auto& attachment = pAttachments[attachment_idx];
4414
4415 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4416 const uint32_t fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
4417 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
4418 const VkFormat format = rp->createInfo.pAttachments[fb_attachment].format;
4419 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4420 }
4421 }
4422 }
4423 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004424 }
4425 }
4426
Nadav Gevaf0808442021-05-21 13:51:25 -04004427 if (VendorCheckEnabled(kBPVendorAMD)) {
4428 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
4429 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
4430 bool black_check = false;
4431 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
4432 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
4433 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
4434 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4435 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4436
4437 bool white_check = false;
4438 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
4439 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
4440 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
4441 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4442 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4443
4444 if (black_check && white_check) {
4445 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4446 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
4447 "Consider changing to one of the following:"
4448 "RGBA(0, 0, 0, 0) "
4449 "RGBA(0, 0, 0, 1) "
4450 "RGBA(1, 1, 1, 0) "
4451 "RGBA(1, 1, 1, 1)",
4452 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4453 }
4454 } else {
4455 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
4456 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
4457 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
4458 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4459 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
4460 "attachment %" PRId32 " is not a fast clear value."
4461 "Consider changing to one of the following:"
4462 "D=0.0f, S=0"
4463 "D=1.0f, S=0",
4464 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4465 }
4466 }
4467 }
4468 }
4469
Camden Stockerf55721f2019-09-09 11:04:49 -06004470 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004471}
Attilio Provenzano02859b22020-02-27 14:17:28 +00004472
4473bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4474 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4475 const VkImageResolve* pRegions) const {
4476 bool skip = false;
4477
4478 skip |= VendorCheckEnabled(kBPVendorArm) &&
4479 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
4480 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
4481 "This is a very slow and extremely bandwidth intensive path. "
4482 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4483 VendorSpecificTag(kBPVendorArm));
4484
4485 return skip;
4486}
4487
Jeff Leger178b1e52020-10-05 12:22:23 -04004488bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4489 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
4490 bool skip = false;
4491
4492 skip |= VendorCheckEnabled(kBPVendorArm) &&
4493 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
4494 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
4495 "This is a very slow and extremely bandwidth intensive path. "
4496 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4497 VendorSpecificTag(kBPVendorArm));
4498
4499 return skip;
4500}
4501
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004502bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
4503 const VkResolveImageInfo2* pResolveImageInfo) const {
4504 bool skip = false;
4505
4506 skip |= VendorCheckEnabled(kBPVendorArm) &&
4507 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
4508 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
4509 "This is a very slow and extremely bandwidth intensive path. "
4510 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4511 VendorSpecificTag(kBPVendorArm));
4512
4513 return skip;
4514}
4515
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004516void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4517 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4518 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004519 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004520 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004521 auto src = Get<bp_state::Image>(srcImage);
4522 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004523
4524 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004525 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
4526 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004527 }
4528}
4529
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004530void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4531 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004532 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004533 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004534 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4535 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004536 uint32_t regionCount = pResolveImageInfo->regionCount;
4537
4538 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004539 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
4540 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004541 }
4542}
4543
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004544void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
4545 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004546 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004547 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004548 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4549 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004550 uint32_t regionCount = pResolveImageInfo->regionCount;
4551
4552 for (uint32_t i = 0; i < regionCount; i++) {
4553 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
4554 pResolveImageInfo->pRegions[i].srcSubresource);
4555 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
4556 pResolveImageInfo->pRegions[i].dstSubresource);
4557 }
4558}
4559
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004560void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4561 const VkClearColorValue* pColor, uint32_t rangeCount,
4562 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004563 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004564 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004565 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004566
4567 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004568 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004569 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004570
4571 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4572 RecordClearColor(dst->createInfo.format, *pColor);
4573 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004574}
4575
4576void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4577 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4578 const VkImageSubresourceRange* pRanges) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004579 ValidationStateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount,
4580 pRanges);
4581
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004582 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004583 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004584 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004585
4586 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004587 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004588 }
Rodrigo Locatti6c4c2662022-08-18 14:20:04 -03004589 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4590 for (uint32_t i = 0; i < rangeCount; i++) {
4591 RecordResetZcullDirection(*cb, image, pRanges[i]);
4592 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004593 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004594}
4595
4596void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4597 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4598 const VkImageCopy* pRegions) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004599 ValidationStateTracker::PreCallRecordCmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
4600 regionCount, pRegions);
4601
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004602 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004603 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004604 auto src = Get<bp_state::Image>(srcImage);
4605 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004606
4607 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004608 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
4609 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004610 }
4611}
4612
4613void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4614 VkImageLayout dstImageLayout, uint32_t regionCount,
4615 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004616 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004617 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004618 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004619
4620 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004621 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004622 }
4623}
4624
4625void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4626 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004627 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004628 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004629 auto src = Get<bp_state::Image>(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004630
4631 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004632 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004633 }
4634}
4635
4636void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4637 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4638 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004639 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004640 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004641 auto src = Get<bp_state::Image>(srcImage);
4642 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004643
4644 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004645 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
4646 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004647 }
4648}
4649
Attilio Provenzano02859b22020-02-27 14:17:28 +00004650bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
4651 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
4652 bool skip = false;
4653
4654 if (VendorCheckEnabled(kBPVendorArm)) {
4655 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
4656 skip |= LogPerformanceWarning(
4657 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
4658 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
4659 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
4660 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06004661 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00004662 }
4663
4664 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
4665 skip |= LogPerformanceWarning(
4666 device, kVUID_BestPractices_CreateSampler_LodClamping,
4667 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
4668 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
4669 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
4670 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
4671 }
4672
4673 if (pCreateInfo->mipLodBias != 0.0f) {
4674 skip |=
4675 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
4676 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
4677 "descriptors being created and may cause reduced performance.",
4678 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
4679 }
4680
4681 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4682 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4683 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
4684 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
4685 skip |= LogPerformanceWarning(
4686 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
4687 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
4688 "This will lead to less efficient descriptors being created and may cause reduced performance. "
4689 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
4690 VendorSpecificTag(kBPVendorArm));
4691 }
4692
4693 if (pCreateInfo->unnormalizedCoordinates) {
4694 skip |= LogPerformanceWarning(
4695 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
4696 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
4697 "descriptors being created and may cause reduced performance.",
4698 VendorSpecificTag(kBPVendorArm));
4699 }
4700
4701 if (pCreateInfo->anisotropyEnable) {
4702 skip |= LogPerformanceWarning(
4703 device, kVUID_BestPractices_CreateSampler_Anisotropy,
4704 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
4705 "and may cause reduced performance.",
4706 VendorSpecificTag(kBPVendorArm));
4707 }
4708 }
4709
4710 return skip;
4711}
Sam Walls8e77e4f2020-03-16 20:47:40 +00004712
Nadav Gevaf0808442021-05-21 13:51:25 -04004713void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
4714 const VkGraphicsPipelineCreateInfo* pCreateInfos,
4715 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
4716 void* cgpl_state) {
4717 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
4718 pPipelines);
4719 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004720 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004721}
4722
4723bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
4724 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
4725 const VkCopyDescriptorSet* pDescriptorCopies) const {
4726 bool skip = false;
4727 if (VendorCheckEnabled(kBPVendorAMD)) {
4728 if (descriptorCopyCount > 0) {
4729 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
4730 "%s Performance warning: copying descriptor sets is not recommended",
4731 VendorSpecificTag(kBPVendorAMD));
4732 }
4733 }
4734
4735 return skip;
4736}
4737
4738bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
4739 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
4740 const VkAllocationCallbacks* pAllocator,
4741 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
4742 bool skip = false;
4743 if (VendorCheckEnabled(kBPVendorAMD)) {
4744 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
4745 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
4746 "vkUpdateDescriptorSet instead",
4747 VendorSpecificTag(kBPVendorAMD));
4748 }
4749
4750 return skip;
4751}
4752
4753bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4754 const VkClearColorValue* pColor, uint32_t rangeCount,
4755 const VkImageSubresourceRange* pRanges) const {
4756 bool skip = false;
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004757
4758 auto dst = Get<bp_state::Image>(image);
4759
Nadav Gevaf0808442021-05-21 13:51:25 -04004760 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08004761 skip |= LogPerformanceWarning(
4762 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04004763 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4764 "vkCmdClearAttachments instead",
4765 VendorSpecificTag(kBPVendorAMD));
4766 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004767 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4768 skip |= ValidateClearColor(commandBuffer, dst->createInfo.format, *pColor);
4769 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004770
4771 return skip;
4772}
4773
4774bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4775 VkImageLayout imageLayout,
4776 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4777 const VkImageSubresourceRange* pRanges) const {
4778 bool skip = false;
4779 if (VendorCheckEnabled(kBPVendorAMD)) {
4780 skip |= LogPerformanceWarning(
4781 device, kVUID_BestPractices_ClearAttachment_ClearImage,
4782 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4783 "vkCmdClearAttachments instead",
4784 VendorSpecificTag(kBPVendorAMD));
4785 }
Mark Young0a6b48f2022-08-18 11:17:02 -06004786 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
4787 assert(cmd_state);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004788 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4789 for (uint32_t i = 0; i < rangeCount; i++) {
Mark Young0a6b48f2022-08-18 11:17:02 -06004790 skip |= ValidateZcull(*cmd_state, image, pRanges[i]);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004791 }
4792 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004793
4794 return skip;
4795}
4796
4797bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
4798 const VkAllocationCallbacks* pAllocator,
4799 VkPipelineLayout* pPipelineLayout) const {
4800 bool skip = false;
4801 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004802 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04004803 // Descriptor sets cost 1 DWORD each.
4804 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
4805 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
4806 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
4807 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
4808 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004809 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004810 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04004811 }
4812
4813 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
4814 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
4815 }
4816
4817 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
4818 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
4819 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
4820 "Descriptor sets cost 1 DWORD each. "
4821 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
4822 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
4823 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
4824 VendorSpecificTag(kBPVendorAMD));
4825 }
4826 }
4827
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004828 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4829 bool has_separate_sampler = false;
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004830 size_t fast_space_usage = 0;
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004831
4832 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) {
4833 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
4834 for (const auto& binding : descriptor_set_layout_state->GetBindings()) {
4835 if (binding.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) {
4836 has_separate_sampler = true;
4837 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004838
4839 if ((descriptor_set_layout_state->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) == 0U) {
4840 size_t descriptor_type_size = 0;
4841
4842 switch (binding.descriptorType) {
4843 case VK_DESCRIPTOR_TYPE_SAMPLER:
4844 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
4845 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
4846 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
4847 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
4848 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
4849 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
4850 descriptor_type_size = 4;
4851 break;
4852 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
4853 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
4854 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR:
4855 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV:
4856 descriptor_type_size = 8;
4857 break;
4858 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
4859 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
4860 case VK_DESCRIPTOR_TYPE_MUTABLE_VALVE:
4861 descriptor_type_size = 16;
4862 break;
4863 case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK:
4864 descriptor_type_size = 1;
4865 default:
4866 // Unknown type.
4867 break;
4868 }
4869
4870 size_t descriptor_size = descriptor_type_size * binding.descriptorCount;
4871 fast_space_usage += descriptor_size;
4872 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004873 }
4874 }
4875
4876 if (has_separate_sampler) {
4877 skip |= LogPerformanceWarning(
4878 device, kVUID_BestPractices_CreatePipelineLayout_SeparateSampler,
4879 "%s Consider using combined image samplers instead of separate samplers for marginally better performance.",
4880 VendorSpecificTag(kBPVendorNVIDIA));
4881 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004882
4883 if (fast_space_usage > kPipelineLayoutFastDescriptorSpaceNVIDIA) {
4884 skip |= LogPerformanceWarning(
4885 device, kVUID_BestPractices_CreatePipelinesLayout_LargePipelineLayout,
4886 "%s Pipeline layout size is too large, prefer using pipeline-specific descriptor set layouts. "
4887 "Aim for consuming less than %" PRIu32 " bytes to allow fast reads for all non-bindless descriptors. "
4888 "Samplers, textures, texel buffers, and combined image samplers consume 4 bytes each. "
4889 "Uniform buffers and acceleration structures consume 8 bytes. "
4890 "Storage buffers consume 16 bytes. "
4891 "Push constants do not consume space.",
4892 VendorSpecificTag(kBPVendorNVIDIA), kPipelineLayoutFastDescriptorSpaceNVIDIA);
4893 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004894 }
4895
Nadav Gevaf0808442021-05-21 13:51:25 -04004896 return skip;
4897}
4898
4899bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4900 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4901 const VkImageCopy* pRegions) const {
4902 bool skip = false;
4903 std::stringstream src_image_hex;
4904 std::stringstream dst_image_hex;
4905 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
4906 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
4907
4908 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004909 auto src_state = Get<IMAGE_STATE>(srcImage);
4910 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04004911
4912 if (src_state && dst_state) {
4913 VkImageTiling src_Tiling = src_state->createInfo.tiling;
4914 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
4915 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
4916 skip |=
4917 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
4918 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
4919 "image (vkCmdCopyImageToBuffer) "
4920 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
4921 "copies when converting between linear and optimal images",
4922 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
4923 }
4924 }
4925 }
4926
4927 return skip;
4928}
4929
4930bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
4931 VkPipeline pipeline) const {
4932 bool skip = false;
4933
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004934 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
4935
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004936 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004937 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04004938 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004939 "%s %s Performance warning: Pipeline %s was bound twice in the frame. "
4940 "Keep pipeline state changes to a minimum, for example, by sorting draw calls by pipeline.",
4941 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA),
4942 report_data->FormatHandle(pipeline).c_str());
Nadav Gevaf0808442021-05-21 13:51:25 -04004943 }
4944 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004945 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4946 const auto& tgm = cb->nv.tess_geometry_mesh;
4947 if (tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA && !tgm.threshold_signaled) {
4948 LogPerformanceWarning(commandBuffer, kVUID_BestPractices_BindPipeline_SwitchTessGeometryMesh,
4949 "%s Avoid switching between pipelines with and without tessellation, geometry, task, "
4950 "and/or mesh shaders. Group draw calls using these shader stages together.",
4951 VendorSpecificTag(kBPVendorNVIDIA));
4952 // Do not set 'skip' so the number of switches gets properly counted after the message.
4953 }
4954 }
4955
Nadav Gevaf0808442021-05-21 13:51:25 -04004956 return skip;
4957}
4958
4959void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
4960 VkFence fence, VkResult result) {
4961 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004962 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004963}
4964
4965bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
4966 bool skip = false;
4967
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004968 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004969 auto num = num_queue_submissions_.load();
4970 if (num > kNumberOfSubmissionWarningLimitAMD) {
4971 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004972 "%s %s Performance warning: command buffers submitted %" PRId32
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004973 " times this frame. Submitting command buffers has a CPU "
4974 "and GPU overhead. Submit fewer times to incur less overhead.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004975 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04004976 }
4977 }
4978
4979 return skip;
4980}
4981
4982void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4983 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4984 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
4985 uint32_t bufferMemoryBarrierCount,
4986 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
4987 uint32_t imageMemoryBarrierCount,
4988 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004989 ValidationStateTracker::PostCallRecordCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags,
4990 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
4991 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
4992
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004993 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004994
4995 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
4996 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
4997 }
4998}
4999
5000void BestPractices::PostCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
5001 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2(commandBuffer, pDependencyInfo);
5002
5003 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
5004 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5005 }
5006}
5007
5008void BestPractices::PostCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
5009 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2KHR(commandBuffer, pDependencyInfo);
5010
5011 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
5012 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5013 }
5014}
5015
5016template <typename ImageMemoryBarrier>
5017void BestPractices::RecordCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer, const ImageMemoryBarrier& barrier) {
5018 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
5019 assert(cb);
5020
5021 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
5022 RecordResetZcullDirection(*cb, barrier.image, barrier.subresourceRange);
5023 }
Nadav Gevaf0808442021-05-21 13:51:25 -04005024}
5025
5026bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
5027 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
5028 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005029 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005030 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005031 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005032 "%s %s Performance warning: High number of vkSemaphore objects created. "
Nadav Gevaf0808442021-05-21 13:51:25 -04005033 "Minimize the amount of queue synchronization that is used. "
5034 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005035 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005036 }
5037 }
5038
5039 return skip;
5040}
5041
5042bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
5043 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
5044 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005045 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005046 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005047 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005048 "%s %s Performance warning: High number of VkFence objects created."
Nadav Gevaf0808442021-05-21 13:51:25 -04005049 "Minimize the amount of CPU-GPU synchronization that is used. "
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005050 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
5051 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005052 }
5053 }
5054
5055 return skip;
5056}
5057
Sam Walls8e77e4f2020-03-16 20:47:40 +00005058void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
5059
5060bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
5061 // look for a cache hit
5062 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
5063 if (hit != _entries.end()) {
5064 // mark the cache hit as being most recently used
5065 hit->age = iteration++;
5066 return true;
5067 }
5068
5069 // if there's no cache hit, we need to model the entry being inserted into the cache
5070 CacheEntry new_entry = {value, iteration};
5071 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
5072 // if there is still space left in the cache, use the next available slot
5073 *(_entries.begin() + iteration) = new_entry;
5074 } else {
5075 // otherwise replace the least recently used cache entry
5076 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
5077 *lru = new_entry;
5078 }
5079 iteration++;
5080 return false;
5081}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005082
5083bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
5084 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005085 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005086 bool skip = false;
5087 if (swapchain_data && swapchain_data->images.size() == 0) {
5088 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
5089 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
5090 "vkGetSwapchainImagesKHR after swapchain creation.");
5091 }
5092 return skip;
5093}
5094
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005095void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
5096 if (no_pointer) {
5097 if (UNCALLED == call_state) {
5098 call_state = QUERY_COUNT;
5099 }
5100 } else { // Save queue family properties
5101 call_state = QUERY_DETAILS;
5102 }
5103}
5104
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005105void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
5106 uint32_t* pQueueFamilyPropertyCount,
5107 VkQueueFamilyProperties* pQueueFamilyProperties) {
5108 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
5109 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005110 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005111 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005112 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
5113 nullptr == pQueueFamilyProperties);
5114 }
5115}
5116
5117void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
5118 uint32_t* pQueueFamilyPropertyCount,
5119 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5120 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
5121 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005122 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005123 if (bp_pd_state) {
5124 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
5125 nullptr == pQueueFamilyProperties);
5126 }
5127}
5128
5129void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
5130 uint32_t* pQueueFamilyPropertyCount,
5131 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5132 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
5133 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005134 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005135 if (bp_pd_state) {
5136 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
5137 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005138 }
5139}
5140
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005141void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
5142 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005143 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005144 if (bp_pd_state) {
5145 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5146 }
5147}
5148
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005149void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
5150 VkPhysicalDeviceFeatures2* pFeatures) {
5151 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005152 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005153 if (bp_pd_state) {
5154 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5155 }
5156}
5157
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005158void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
5159 VkPhysicalDeviceFeatures2* pFeatures) {
5160 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005161 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005162 if (bp_pd_state) {
5163 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5164 }
5165}
5166
5167void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
5168 VkSurfaceKHR surface,
5169 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
5170 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005171 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005172 if (bp_pd_state) {
5173 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5174 }
5175}
5176
5177void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
5178 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5179 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005180 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005181 if (bp_pd_state) {
5182 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5183 }
5184}
5185
5186void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
5187 VkSurfaceKHR surface,
5188 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
5189 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005190 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005191 if (bp_pd_state) {
5192 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5193 }
5194}
5195
5196void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
5197 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
5198 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005199 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005200 if (bp_pd_data) {
5201 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
5202
5203 if (*pPresentModeCount) {
5204 if (call_state < QUERY_COUNT) {
5205 call_state = QUERY_COUNT;
5206 }
5207 }
5208 if (pPresentModes) {
5209 if (call_state < QUERY_DETAILS) {
5210 call_state = QUERY_DETAILS;
5211 }
5212 }
5213 }
5214}
5215
5216void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
5217 uint32_t* pSurfaceFormatCount,
5218 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005219 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005220 if (bp_pd_data) {
5221 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
5222
5223 if (*pSurfaceFormatCount) {
5224 if (call_state < QUERY_COUNT) {
5225 call_state = QUERY_COUNT;
5226 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005227 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005228 }
5229 if (pSurfaceFormats) {
5230 if (call_state < QUERY_DETAILS) {
5231 call_state = QUERY_DETAILS;
5232 }
5233 }
5234 }
5235}
5236
5237void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
5238 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5239 uint32_t* pSurfaceFormatCount,
5240 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005241 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005242 if (bp_pd_data) {
5243 if (*pSurfaceFormatCount) {
5244 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
5245 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
5246 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005247 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005248 }
5249 if (pSurfaceFormats) {
5250 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
5251 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
5252 }
5253 }
5254 }
5255}
5256
5257void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
5258 uint32_t* pPropertyCount,
5259 VkDisplayPlanePropertiesKHR* pProperties,
5260 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005261 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005262 if (bp_pd_data) {
5263 if (*pPropertyCount) {
5264 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
5265 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
5266 }
5267 }
5268 if (pProperties) {
5269 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
5270 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
5271 }
5272 }
5273 }
5274}
5275
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005276void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
5277 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
5278 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005279 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06005280 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
5281 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
5282 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005283 }
5284 }
5285}
5286
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005287void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
5288 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
5289
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06005290 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005291 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02005292 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005293 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005294 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005295 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07005296 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005297 }
Rodrigo Locattic789fe82022-07-06 17:42:19 -03005298 cb->num_submits++;
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005299 }
5300 }
5301}