blob: f5ea67e09e11261aaa0b0bba1503d9f5377de334 [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);
1488 if (cb) return;
1489
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
1710 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1711 if (barrier.oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && barrier.newLayout != VK_IMAGE_LAYOUT_UNDEFINED) {
1712 skip |= ValidateZcull(commandBuffer, barrier.image, barrier.subresourceRange);
1713 }
1714 }
1715
1716 return skip;
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001717}
1718
Camden5b184be2019-08-13 07:50:19 -06001719bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001720 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001721 bool skip = false;
1722
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001723 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1724
1725 return skip;
1726}
1727
1728bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1729 VkQueryPool queryPool, uint32_t query) const {
1730 bool skip = false;
1731
1732 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001733
1734 return skip;
1735}
1736
Tony-LunarGd36f5f32022-01-20 11:49:59 -07001737bool BestPractices::PreCallValidateCmdWriteTimestamp2(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 pipelineStage,
1738 VkQueryPool queryPool, uint32_t query) const {
1739 bool skip = false;
1740
1741 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2", pipelineStage);
1742
1743 return skip;
1744}
1745
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001746void BestPractices::PreCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1747 VkPipeline pipeline) {
1748 StateTracker::PreCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1749
1750 auto pipeline_info = Get<PIPELINE_STATE>(pipeline);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001751 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001752
1753 assert(pipeline_info);
1754 assert(cb);
1755
1756 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS && VendorCheckEnabled(kBPVendorNVIDIA)) {
1757 using TessGeometryMeshState = bp_state::CommandBufferStateNV::TessGeometryMesh::State;
1758 auto& tgm = cb->nv.tess_geometry_mesh;
1759
1760 // Make sure the message is only signaled once per command buffer
1761 tgm.threshold_signaled = tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA;
1762
1763 // Track pipeline switches with tessellation, geometry, and/or mesh shaders enabled, and disabled
1764 auto tgm_stages = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT |
1765 VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_TASK_BIT_NV | VK_SHADER_STAGE_MESH_BIT_NV;
1766 auto new_tgm_state = (pipeline_info->active_shaders & tgm_stages) != 0
1767 ? TessGeometryMeshState::Enabled
1768 : TessGeometryMeshState::Disabled;
1769 if (tgm.state != new_tgm_state && tgm.state != TessGeometryMeshState::Unknown) {
1770 tgm.num_switches++;
1771 }
1772 tgm.state = new_tgm_state;
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001773
1774 // Track depthTestEnable and depthCompareOp
1775 auto &pipeline_create_info = pipeline_info->GetCreateInfo<VkGraphicsPipelineCreateInfo>();
1776 auto depth_stencil_state = pipeline_create_info.pDepthStencilState;
1777 auto dynamic_state = pipeline_create_info.pDynamicState;
1778 if (depth_stencil_state && dynamic_state) {
1779 auto dynamic_state_begin = dynamic_state->pDynamicStates;
1780 auto dynamic_state_end = dynamic_state->pDynamicStates + dynamic_state->dynamicStateCount;
1781
1782 bool dynamic_depth_test_enable = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE) != dynamic_state_end;
1783 bool dynamic_depth_func = std::find(dynamic_state_begin, dynamic_state_end, VK_DYNAMIC_STATE_DEPTH_COMPARE_OP) != dynamic_state_end;
1784
1785 if (!dynamic_depth_test_enable) {
1786 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depth_stencil_state->depthTestEnable != VK_FALSE);
1787 }
1788 if (!dynamic_depth_func) {
1789 RecordSetDepthTestState(*cb, depth_stencil_state->depthCompareOp, cb->nv.depth_test_enable);
1790 }
1791 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03001792 }
1793}
1794
Sam Walls0961ec02020-03-31 16:39:15 +01001795void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1796 VkPipeline pipeline) {
1797 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1798
Nadav Gevaf0808442021-05-21 13:51:25 -04001799 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001800 PipelineUsedInFrame(pipeline);
Nadav Gevaf0808442021-05-21 13:51:25 -04001801
Sam Walls0961ec02020-03-31 16:39:15 +01001802 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001803 auto pipeline_state = Get<bp_state::Pipeline>(pipeline);
Sam Walls0961ec02020-03-31 16:39:15 +01001804 // check for depth/blend state tracking
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001805 if (pipeline_state) {
1806 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06001807 assert(cb_node);
1808 auto& render_pass_state = cb_node->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01001809
Jeremy Gebben20da7a12022-02-25 14:07:46 -07001810 render_pass_state.nextDrawTouchesAttachments = pipeline_state->access_framebuffer_attachments;
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001811 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001812
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001813 const auto* blend_state = pipeline_state->ColorBlendState();
1814 const auto* stencil_state = pipeline_state->DepthStencilState();
Sam Walls0961ec02020-03-31 16:39:15 +01001815
1816 if (blend_state) {
1817 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001818 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001819 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1820 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001821 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001822 }
1823 }
1824 }
1825
1826 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001827 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001828
1829 if (stencil_state && stencil_state->depthTestEnable) {
1830 switch (stencil_state->depthCompareOp) {
1831 case VK_COMPARE_OP_EQUAL:
1832 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1833 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001834 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001835 break;
1836 default:
1837 break;
1838 }
1839 }
Sam Walls0961ec02020-03-31 16:39:15 +01001840 }
1841 }
1842}
1843
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001844void BestPractices::PreCallRecordCmdSetDepthCompareOp(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1845 StateTracker::PreCallRecordCmdSetDepthCompareOp(commandBuffer, depthCompareOp);
1846
1847 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1848 assert(cb);
1849
1850 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1851 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1852 }
1853}
1854
1855void BestPractices::PreCallRecordCmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) {
1856 StateTracker::PreCallRecordCmdSetDepthCompareOpEXT(commandBuffer, depthCompareOp);
1857
1858 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1859 assert(cb);
1860
1861 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1862 RecordSetDepthTestState(*cb, depthCompareOp, cb->nv.depth_test_enable);
1863 }
1864}
1865
1866void BestPractices::PreCallRecordCmdSetDepthTestEnable(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1867 StateTracker::PreCallRecordCmdSetDepthTestEnable(commandBuffer, depthTestEnable);
1868
1869 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1870 assert(cb);
1871
1872 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1873 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1874 }
1875}
1876
1877void BestPractices::PreCallRecordCmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) {
1878 StateTracker::PreCallRecordCmdSetDepthTestEnableEXT(commandBuffer, depthTestEnable);
1879
1880 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1881 assert(cb);
1882
1883 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1884 RecordSetDepthTestState(*cb, cb->nv.depth_compare_op, depthTestEnable != VK_FALSE);
1885 }
1886}
1887
1888void BestPractices::RecordSetDepthTestState(bp_state::CommandBuffer& cmd_state, VkCompareOp new_depth_compare_op, bool new_depth_test_enable) {
1889 assert(VendorCheckEnabled(kBPVendorNVIDIA));
1890
1891 if (cmd_state.nv.depth_compare_op != new_depth_compare_op) {
1892 switch (new_depth_compare_op) {
1893 case VK_COMPARE_OP_LESS:
1894 case VK_COMPARE_OP_LESS_OR_EQUAL:
1895 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Less;
1896 break;
1897 case VK_COMPARE_OP_GREATER:
1898 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1899 cmd_state.nv.zcull_direction = bp_state::CommandBufferStateNV::ZcullDirection::Greater;
1900 break;
1901 default:
1902 // The other ops carry over the previous state.
1903 break;
1904 }
1905 }
1906 cmd_state.nv.depth_compare_op = new_depth_compare_op;
1907 cmd_state.nv.depth_test_enable = new_depth_test_enable;
1908}
1909
1910void BestPractices::RecordCmdBeginRenderingCommon(VkCommandBuffer commandBuffer) {
1911 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1912 assert(cmd_state);
1913
1914 auto rp = cmd_state->activeRenderPass.get();
1915 assert(rp);
1916
1917 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1918 std::shared_ptr<IMAGE_VIEW_STATE> depth_image_view_shared_ptr;
1919 IMAGE_VIEW_STATE* depth_image_view = nullptr;
1920 layer_data::optional<VkAttachmentLoadOp> load_op;
1921
1922 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1923 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1924 if (depth_attachment) {
1925 load_op.emplace(depth_attachment->loadOp);
1926 depth_image_view_shared_ptr = Get<IMAGE_VIEW_STATE>(depth_attachment->imageView);
1927 depth_image_view = depth_image_view_shared_ptr.get();
1928 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001929
1930 for (uint32_t i = 0; i < rp->dynamic_rendering_begin_rendering_info.colorAttachmentCount; ++i) {
1931 const auto& color_attachment = rp->dynamic_rendering_begin_rendering_info.pColorAttachments[i];
1932 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1933 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
1934 RecordClearColor(format, color_attachment.clearValue.color);
1935 }
1936 }
1937
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001938 } else {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03001939 if (rp->createInfo.pAttachments) {
1940 if (rp->createInfo.subpassCount > 0) {
1941 const auto depth_attachment = rp->createInfo.pSubpasses[0].pDepthStencilAttachment;
1942 if (depth_attachment) {
1943 const uint32_t attachment_index = depth_attachment->attachment;
1944 if (attachment_index != VK_ATTACHMENT_UNUSED) {
1945 load_op.emplace(rp->createInfo.pAttachments[attachment_index].loadOp);
1946 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
1947 }
1948 }
1949 }
1950 for (uint32_t i = 0; i < cmd_state->activeRenderPassBeginInfo.clearValueCount; ++i) {
1951 const auto& attachment = rp->createInfo.pAttachments[i];
1952 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1953 const auto& clear_color = cmd_state->activeRenderPassBeginInfo.pClearValues[i].color;
1954 RecordClearColor(attachment.format, clear_color);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03001955 }
1956 }
1957 }
1958 }
1959 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
1960 const VkImage depth_image = depth_image_view->image_state->image();
1961 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
1962 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
1963 } else {
1964 RecordUnbindZcullScope(*cmd_state);
1965 }
1966 if (load_op) {
1967 if (*load_op == VK_ATTACHMENT_LOAD_OP_CLEAR || *load_op == VK_ATTACHMENT_LOAD_OP_DONT_CARE) {
1968 RecordResetScopeZcullDirection(*cmd_state);
1969 }
1970 }
1971 }
1972}
1973
1974void BestPractices::RecordCmdEndRenderingCommon(VkCommandBuffer commandBuffer) {
1975 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
1976 assert(cmd_state);
1977
1978 auto rp = cmd_state->activeRenderPass.get();
1979 assert(rp);
1980
1981 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
1982 layer_data::optional<VkAttachmentStoreOp> store_op;
1983
1984 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
1985 const auto depth_attachment = rp->dynamic_rendering_begin_rendering_info.pDepthAttachment;
1986 if (depth_attachment) {
1987 store_op.emplace(depth_attachment->storeOp);
1988 }
1989 } else {
1990 if (rp->createInfo.subpassCount > 0) {
1991 const uint32_t last_subpass = rp->createInfo.subpassCount - 1;
1992 const auto depth_attachment = rp->createInfo.pSubpasses[last_subpass].pDepthStencilAttachment;
1993 if (depth_attachment) {
1994 const uint32_t attachment = depth_attachment->attachment;
1995 if (attachment != VK_ATTACHMENT_UNUSED) {
1996 store_op.emplace(rp->createInfo.pAttachments[attachment].storeOp);
1997 }
1998 }
1999 }
2000 }
2001
2002 if (store_op) {
2003 if (*store_op == VK_ATTACHMENT_STORE_OP_DONT_CARE || *store_op == VK_ATTACHMENT_STORE_OP_NONE) {
2004 RecordResetScopeZcullDirection(*cmd_state);
2005 }
2006 }
2007
2008 RecordUnbindZcullScope(*cmd_state);
2009 }
2010}
2011
2012void BestPractices::RecordBindZcullScope(bp_state::CommandBuffer& cmd_state, VkImage depth_attachment, const VkImageSubresourceRange& subresource_range) {
2013 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2014
2015 if (depth_attachment == VK_NULL_HANDLE) {
2016 cmd_state.nv.zcull_scope = {};
2017 return;
2018 }
2019
2020 assert((subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U);
2021
2022 auto image_state = Get<IMAGE_STATE>(depth_attachment);
2023 assert(image_state);
2024
2025 const uint32_t mip_levels = image_state->createInfo.mipLevels;
2026 const uint32_t array_layers = image_state->createInfo.arrayLayers;
2027
2028 auto& tree = cmd_state.nv.zcull_per_image[depth_attachment];
2029 if (tree.states.empty()) {
2030 tree.mip_levels = mip_levels;
2031 tree.array_layers = array_layers;
2032 tree.states.resize(array_layers * mip_levels);
2033 }
2034
2035 cmd_state.nv.zcull_scope.image = depth_attachment;
2036 cmd_state.nv.zcull_scope.range = subresource_range;
2037 cmd_state.nv.zcull_scope.tree = &tree;
2038}
2039
2040void BestPractices::RecordUnbindZcullScope(bp_state::CommandBuffer& cmd_state) {
2041 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2042
2043 RecordBindZcullScope(cmd_state, VK_NULL_HANDLE, VkImageSubresourceRange{});
2044}
2045
2046void BestPractices::RecordResetScopeZcullDirection(bp_state::CommandBuffer& cmd_state) {
2047 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2048
2049 auto& scope = cmd_state.nv.zcull_scope;
2050 RecordResetZcullDirection(cmd_state, scope.image, scope.range);
2051}
2052
2053void BestPractices::RecordResetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2054 const VkImageSubresourceRange& subresource_range) {
2055 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2056
2057 RecordSetZcullDirection(cmd_state, depth_image, subresource_range, bp_state::CommandBufferStateNV::ZcullDirection::Unknown);
2058
2059 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2060 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2061 return;
2062 }
2063 auto& tree = image_it->second;
2064
2065 for (uint32_t i = 0; i < subresource_range.layerCount; ++i) {
2066 const uint32_t layer = subresource_range.baseArrayLayer + i;
2067
2068 for (uint32_t j = 0; j < subresource_range.levelCount; ++j) {
2069 const uint32_t level = subresource_range.baseMipLevel + j;
2070
2071 auto& subresource = tree.GetState(layer, level);
2072 subresource.num_less_draws = 0;
2073 subresource.num_greater_draws = 0;
2074 }
2075 }
2076}
2077
2078void BestPractices::RecordSetScopeZcullDirection(bp_state::CommandBuffer& cmd_state, bp_state::CommandBufferStateNV::ZcullDirection mode) {
2079 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2080
2081 auto& scope = cmd_state.nv.zcull_scope;
2082 RecordSetZcullDirection(cmd_state, scope.image, scope.range, mode);
2083}
2084
2085void BestPractices::RecordSetZcullDirection(bp_state::CommandBuffer& cmd_state, VkImage depth_image,
2086 const VkImageSubresourceRange& subresource_range,
2087 bp_state::CommandBufferStateNV::ZcullDirection mode) {
2088 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2089
2090 const auto image_it = cmd_state.nv.zcull_per_image.find(depth_image);
2091 if (image_it == cmd_state.nv.zcull_per_image.end()) {
2092 return;
2093 }
2094 auto& tree = image_it->second;
2095
2096 for (uint32_t i = 0; i < subresource_range.layerCount; ++i) {
2097 const uint32_t layer = subresource_range.baseArrayLayer + i;
2098
2099 for (uint32_t j = 0; j < subresource_range.levelCount; ++j) {
2100 const uint32_t level = subresource_range.baseMipLevel + j;
2101 tree.GetState(layer, level).direction = cmd_state.nv.zcull_direction;
2102 }
2103 }
2104}
2105
2106void BestPractices::RecordZcullDraw(bp_state::CommandBuffer& cmd_state) {
2107 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2108
2109 // Add one draw to each subresource depending on the current Z-cull direction
2110 auto& scope = cmd_state.nv.zcull_scope;
2111
2112 for (uint32_t i = 0; i < scope.range.layerCount; ++i) {
2113 const uint32_t layer = scope.range.baseArrayLayer + i;
2114 auto& subresource = scope.tree->GetState(layer, scope.range.baseMipLevel);
2115
2116 switch (subresource.direction) {
2117 case bp_state::CommandBufferStateNV::ZcullDirection::Unknown:
2118 // Unreachable
2119 assert(0);
2120 break;
2121 case bp_state::CommandBufferStateNV::ZcullDirection::Less:
2122 ++subresource.num_less_draws;
2123 break;
2124 case bp_state::CommandBufferStateNV::ZcullDirection::Greater:
2125 ++subresource.num_greater_draws;
2126 break;
2127 }
2128 }
2129}
2130
2131bool BestPractices::ValidateZcullScope(VkCommandBuffer commandBuffer) const {
2132 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2133
2134 bool skip = false;
2135
2136 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
2137 assert(cmd_state);
2138
2139 if (cmd_state->nv.depth_test_enable) {
2140 auto& scope = cmd_state->nv.zcull_scope;
2141 skip |= ValidateZcull(commandBuffer, scope.image, scope.range);
2142 }
2143
2144 return skip;
2145}
2146
2147bool BestPractices::ValidateZcull(VkCommandBuffer commandBuffer, VkImage image,
2148 const VkImageSubresourceRange& subresource_range) const {
2149 bool skip = false;
2150
2151 const char* good_mode = nullptr;
2152 const char* bad_mode = nullptr;
2153
2154 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
2155 assert(cmd_state);
2156
2157 const auto image_it = cmd_state->nv.zcull_per_image.find(image);
2158 if (image_it == cmd_state->nv.zcull_per_image.end()) {
2159 return skip;
2160 }
2161 const auto& tree = image_it->second;
2162
2163 bool is_balanced = false;
2164
2165 for (uint32_t i = 0; i < subresource_range.layerCount; ++i) {
2166 const uint32_t layer = subresource_range.baseArrayLayer + i;
2167
2168 for (uint32_t j = 0; j < subresource_range.levelCount; ++j) {
2169 const uint32_t level = subresource_range.baseMipLevel + j;
2170
2171 const auto& resource = tree.GetState(layer, level);
2172 const uint64_t num_draws = resource.num_less_draws + resource.num_greater_draws;
2173
2174 if (num_draws > 0) {
2175 const uint64_t less_ratio = (resource.num_less_draws * 100) / num_draws;
2176 const uint64_t greater_ratio = (resource.num_greater_draws * 100) / num_draws;
2177
2178 if ((less_ratio > kZcullDirectionBalanceRatioNVIDIA) && (greater_ratio > kZcullDirectionBalanceRatioNVIDIA)) {
2179 is_balanced = true;
2180
2181 if (greater_ratio > less_ratio) {
2182 good_mode = "GREATER";
2183 bad_mode = "LESS";
2184 } else {
2185 good_mode = "LESS";
2186 bad_mode = "GREATER";
2187 }
2188 break;
2189 }
2190 }
2191 }
2192 if (is_balanced) {
2193 break;
2194 }
2195 }
2196
2197 if (is_balanced) {
2198 skip |= LogPerformanceWarning(
2199 commandBuffer, kVUID_BestPractices_Zcull_LessGreaterRatio,
2200 "%s Depth attachment %s is primarily rendered with depth compare op %s, but some draws use %s. "
2201 "Z-cull is disabled for the least used direction, which harms depth testing performance. "
2202 "The Z-cull direction can be reset by clearing the depth attachment, transitioning from VK_IMAGE_LAYOUT_UNDEFINED, "
2203 "using VK_ATTACHMENT_LOAD_OP_DONT_CARE, or using VK_ATTACHMENT_STORE_OP_DONT_CARE.",
2204 VendorSpecificTag(kBPVendorNVIDIA), report_data->FormatHandle(cmd_state->nv.zcull_scope.image).c_str(), good_mode,
2205 bad_mode);
2206 }
2207
2208 return skip;
2209}
2210
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002211static std::array<uint32_t, 4> GetRawClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2212 std::array<uint32_t, 4> raw_color{};
2213 std::copy_n(clear_value.uint32, raw_color.size(), raw_color.data());
2214
2215 // Zero out unused components to avoid polluting the cache with garbage
2216 if (!FormatHasRed(format)) raw_color[0] = 0;
2217 if (!FormatHasGreen(format)) raw_color[1] = 0;
2218 if (!FormatHasBlue(format)) raw_color[2] = 0;
2219 if (!FormatHasAlpha(format)) raw_color[3] = 0;
2220
2221 return raw_color;
2222}
2223
2224static bool IsClearColorZeroOrOne(VkFormat format, const std::array<uint32_t, 4> clear_color) {
2225 static_assert(sizeof(float) == sizeof(uint32_t), "Mismatching float <-> uint32 sizes");
2226 const float one = 1.0f;
2227 const float zero = 0.0f;
2228 uint32_t raw_one{};
2229 uint32_t raw_zero{};
2230 memcpy(&raw_one, &one, sizeof(one));
2231 memcpy(&raw_zero, &zero, sizeof(zero));
2232
2233 const bool is_one = (!FormatHasRed(format) || (clear_color[0] == raw_one)) &&
2234 (!FormatHasGreen(format) || (clear_color[1] == raw_one)) &&
2235 (!FormatHasBlue(format) || (clear_color[2] == raw_one)) &&
2236 (!FormatHasAlpha(format) || (clear_color[3] == raw_one));
2237 const bool is_zero = (!FormatHasRed(format) || (clear_color[0] == raw_zero)) &&
2238 (!FormatHasGreen(format) || (clear_color[1] == raw_zero)) &&
2239 (!FormatHasBlue(format) || (clear_color[2] == raw_zero)) &&
2240 (!FormatHasAlpha(format) || (clear_color[3] == raw_zero));
2241 return is_one || is_zero;
2242}
2243
2244static std::string MakeCompressedFormatListNVIDIA() {
2245 std::string format_list;
2246 for (VkFormat compressed_format : kCustomClearColorCompressedFormatsNVIDIA) {
2247 if (compressed_format == kCustomClearColorCompressedFormatsNVIDIA.back()) {
2248 format_list += "or ";
2249 }
2250 format_list += string_VkFormat(compressed_format);
2251 if (compressed_format != kCustomClearColorCompressedFormatsNVIDIA.back()) {
2252 format_list += ", ";
2253 }
2254 }
2255 return format_list;
2256}
2257
2258void BestPractices::RecordClearColor(VkFormat format, const VkClearColorValue& clear_value) {
2259 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2260
2261 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2262 if (IsClearColorZeroOrOne(format, raw_color)) {
2263 // These colors are always compressed
2264 return;
2265 }
2266
2267 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2268 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2269 // The format cannot be compressed with a custom color
2270 return;
2271 }
2272
2273 // Record custom clear color
2274 WriteLockGuard guard{clear_colors_lock_};
2275 if (clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA) {
2276 clear_colors_.insert(raw_color);
2277 }
2278}
2279
2280bool BestPractices::ValidateClearColor(VkCommandBuffer commandBuffer, VkFormat format, const VkClearColorValue& clear_value) const {
2281 assert(VendorCheckEnabled(kBPVendorNVIDIA));
2282
2283 bool skip = false;
2284
2285 const std::array<uint32_t, 4> raw_color = GetRawClearColor(format, clear_value);
2286 if (IsClearColorZeroOrOne(format, raw_color)) {
2287 return skip;
2288 }
2289
2290 const auto it = std::find(kCustomClearColorCompressedFormatsNVIDIA.begin(), kCustomClearColorCompressedFormatsNVIDIA.end(), format);
2291 if (it == kCustomClearColorCompressedFormatsNVIDIA.end()) {
2292 // The format is not compressible
2293 static const std::string format_list = MakeCompressedFormatListNVIDIA();
2294
2295 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2296 "%s Clearing image with format %s without a 1.0f or 0.0f clear color. "
2297 "The clear will not get compressed in the GPU, harming performance. "
2298 "This can be fixed using a clear color of VkClearColorValue{0.0f, 0.0f, 0.0f, 0.0f}, or "
2299 "VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f}. Alternatively, use %s.",
2300 VendorSpecificTag(kBPVendorNVIDIA), string_VkFormat(format), format_list.c_str());
2301 } else {
2302 // The format is compressible
2303 bool registered = false;
2304 {
2305 ReadLockGuard guard{clear_colors_lock_};
2306 registered = clear_colors_.find(raw_color) != clear_colors_.end();
2307
2308 if (!registered) {
2309 // If it's not in the list, it might be new. Check if there's still space for new entries.
2310 registered = clear_colors_.size() < kMaxRecommendedNumberOfClearColorsNVIDIA;
2311 }
2312 }
2313 if (!registered) {
2314 std::string clear_color_str;
2315
2316 if (FormatIsUINT(format)) {
2317 clear_color_str = std::to_string(clear_value.uint32[0]) + ", " + std::to_string(clear_value.uint32[1]) + ", " +
2318 std::to_string(clear_value.uint32[2]) + ", " + std::to_string(clear_value.uint32[3]);
2319 } else if (FormatIsSINT(format)) {
2320 clear_color_str = std::to_string(clear_value.int32[0]) + ", " + std::to_string(clear_value.int32[1]) + ", " +
2321 std::to_string(clear_value.int32[2]) + ", " + std::to_string(clear_value.int32[3]);
2322 } else {
2323 clear_color_str = std::to_string(clear_value.float32[0]) + ", " + std::to_string(clear_value.float32[1]) + ", " +
2324 std::to_string(clear_value.float32[2]) + ", " + std::to_string(clear_value.float32[3]);
2325 }
2326
2327 skip |= LogPerformanceWarning(
2328 commandBuffer, kVUID_BestPractices_ClearColor_NotCompressed,
2329 "%s Clearing image with unregistered VkClearColorValue{%s}. "
2330 "This clear will not get compressed in the GPU, harming performance. "
2331 "The clear color is not registered because too many unique colors have been used. "
2332 "Select a discrete set of clear colors and stick to those. "
2333 "VkClearColorValue{0, 0, 0, 0} and VkClearColorValue{1.0f, 1.0f, 1.0f, 1.0f} are always registered.",
2334 VendorSpecificTag(kBPVendorNVIDIA), clear_color_str.c_str());
2335 }
2336 }
2337
2338 return skip;
2339}
2340
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002341static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2342 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
2343 const auto& subpass_info = createInfo.pSubpasses[subpass];
2344 if (subpass_info.pResolveAttachments) {
2345 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2346 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2347 }
2348 }
2349 }
2350
2351 return false;
2352}
2353
Attilio Provenzano02859b22020-02-27 14:17:28 +00002354static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2355 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002356 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002357
2358 // If an attachment is ever used as a color attachment,
2359 // resolve attachment or depth stencil attachment,
2360 // it needs to exist on tile at some point.
2361
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002362 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2363 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002364 }
2365
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002366 if (subpass_info.pResolveAttachments) {
2367 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
2368 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
2369 }
2370 }
2371
2372 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002373 }
2374
2375 return false;
2376}
2377
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002378static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
2379 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
2380 return false;
2381 }
2382
2383 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002384 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002385
2386 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
2387 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
2388 return true;
2389 }
2390 }
2391 }
2392
2393 return false;
2394}
2395
Attilio Provenzano02859b22020-02-27 14:17:28 +00002396bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2397 const VkRenderPassBeginInfo* pRenderPassBegin) const {
2398 bool skip = false;
2399
2400 if (!pRenderPassBegin) {
2401 return skip;
2402 }
2403
Gareth Webbdc6549a2021-06-16 03:52:24 +01002404 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
2405 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
2406 "This render pass has a zero-size render area. It cannot write to any attachments, "
2407 "and can only be used for side effects such as layout transitions.");
2408 }
2409
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002410 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002411 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08002412 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07002413 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06002414 if (rpabi) {
2415 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
2416 }
2417 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002418 // Check if any attachments have LOAD operation on them
2419 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002420 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00002421
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002422 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02002423 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002424 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002425 }
2426
2427 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002428 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002429 }
2430
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002431 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002432
2433 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002434 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2435 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00002436 }
2437
2438 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
LawG47747b322022-02-23 16:12:10 +00002439 if (attachment_needs_readback && (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
2440 skip |=
2441 LogPerformanceWarning(device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
LawG4015be1c2022-03-01 10:37:52 +00002442 "%s %s: Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
LawG47747b322022-02-23 16:12:10 +00002443 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
Nadav Gevaf0808442021-05-21 13:51:25 -04002444 "which will copy in total %u pixels (renderArea = "
LawG47747b322022-02-23 16:12:10 +00002445 "{ %" PRId32 ", %" PRId32 ", %" PRIu32 ", %" PRIu32 " }) to the tile buffer.",
2446 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), att,
2447 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
2448 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
2449 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002450 }
2451 }
paul-lunarg7089e272022-06-20 22:19:37 +02002452
2453 // Check if renderpass has at least one VK_ATTACHMENT_LOAD_OP_CLEAR
2454
2455 bool clearing = false;
2456
2457 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
2458 const auto& attachment = rp_state->createInfo.pAttachments[att];
2459
2460 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2461 clearing = true;
2462 break;
2463 }
2464 }
2465
2466 // Check if there are ClearValues passed to BeginRenderPass even though no attachments will be cleared
2467 if (!clearing && pRenderPassBegin->clearValueCount > 0) {
2468 // Flag as warning because nothing will happen per spec, and pClearValues will be ignored
2469 skip |= LogWarning(
2470 device, kVUID_BestPractices_ClearValueWithoutLoadOpClear,
2471 "This render pass does not have VkRenderPassCreateInfo.pAttachments->loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR "
2472 "but VkRenderPassBeginInfo.clearValueCount > 0. VkRenderPassBeginInfo.pClearValues will be ignored and no "
paul-lunarga0a149c2022-06-23 16:18:51 +02002473 "attachments will be cleared.");
paul-lunarg7089e272022-06-20 22:19:37 +02002474 }
paul-lunarga0a149c2022-06-23 16:18:51 +02002475
2476 // Check if there are more clearValues than attachments
2477 if(pRenderPassBegin->clearValueCount > rp_state->createInfo.attachmentCount) {
2478 // Flag as warning because the overflowing clearValues will be ignored and could even be undefined on certain platforms.
2479 // This could signal a bug and there seems to be no reason for this to happen on purpose.
2480 skip |= LogWarning(
2481 device, kVUID_BestPractices_ClearValueCountHigherThanAttachmentCount,
2482 "This render pass has VkRenderPassBeginInfo.clearValueCount > VkRenderPassCreateInfo.attachmentCount "
2483 "(%" PRIu32 " > %" PRIu32 ") and as such the clearValues that do not have a corresponding attachment will be ignored.",
2484 pRenderPassBegin->clearValueCount, rp_state->createInfo.attachmentCount);
2485 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002486
2487 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp_state->createInfo.pAttachments) {
2488 for (uint32_t i = 0; i < pRenderPassBegin->clearValueCount; ++i) {
2489 const auto& attachment = rp_state->createInfo.pAttachments[i];
2490 if (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2491 const auto& clear_color = pRenderPassBegin->pClearValues[i].color;
2492 skip |= ValidateClearColor(commandBuffer, attachment.format, clear_color);
2493 }
2494 }
2495 }
2496 }
2497
2498 return skip;
2499}
2500
2501bool BestPractices::ValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2502 bool skip = false;
2503
2504 auto cmd_state = Get<bp_state::CommandBuffer>(commandBuffer);
2505 assert(cmd_state);
2506
2507 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2508 for (uint32_t i = 0; i < pRenderingInfo->colorAttachmentCount; ++i) {
2509 const auto& color_attachment = pRenderingInfo->pColorAttachments[i];
2510 if (color_attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) {
2511 const VkFormat format = Get<IMAGE_VIEW_STATE>(color_attachment.imageView)->create_info.format;
2512 skip |= ValidateClearColor(commandBuffer, format, color_attachment.clearValue.color);
2513 }
2514 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00002515 }
2516
2517 return skip;
2518}
2519
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002520void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
2521 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002522 if (view) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002523 auto image_state = std::static_pointer_cast<bp_state::Image>(view->image_state);
2524 QueueValidateImage(funcs, function_name, image_state, usage, view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002525 }
2526}
2527
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002528void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2529 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002530 // If we're viewing a 3D slice, ignore base array layer.
2531 // The entire 3D subresource is accessed as one atomic unit.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002532 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 +02002533
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002534 const uint32_t max_layers = state->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002535 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002536 const uint32_t max_levels = state->createInfo.mipLevels - subresource_range.baseMipLevel;
2537 const uint32_t mip_levels = std::min(state->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002538
2539 for (uint32_t layer = 0; layer < array_layers; layer++) {
2540 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02002541 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
2542 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002543 }
2544 }
2545}
2546
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002547void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2548 IMAGE_SUBRESOURCE_USAGE_BP usage, const VkImageSubresourceLayers& subresource_layers) {
2549 const uint32_t max_layers = state->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002550 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002551
2552 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002553 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002554 }
2555}
2556
paul-lunarg5eb52062022-06-27 18:57:15 +02002557void BestPractices::QueueValidateImage(QueueCallbacks& funcs, const char* function_name, std::shared_ptr<bp_state::Image>& state,
2558 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer, uint32_t mip_level) {
2559 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker&, const QUEUE_STATE&,
2560 const CMD_BUFFER_STATE&) -> bool {
2561 ValidateImageInQueue(function_name, *state, usage, array_layer, mip_level);
2562 return false;
2563 });
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002564}
2565
LawG44d414ba2022-02-23 15:35:41 +00002566void BestPractices::ValidateImageInQueueArmImg(const char* function_name, const bp_state::Image& image,
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002567 IMAGE_SUBRESOURCE_USAGE_BP last_usage, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002568 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002569 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002570 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 -07002571 !image.IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002572 LogPerformanceWarning(
2573 device, kVUID_BestPractices_RenderPass_RedundantStore,
LawG4015be1c2022-03-01 10:37:52 +00002574 "%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 +02002575 "image was used, it was written to with STORE_OP_STORE. "
2576 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
2577 "architectures.",
LawG44d414ba2022-02-23 15:35:41 +00002578 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002579 } 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 +02002580 LogPerformanceWarning(
2581 device, kVUID_BestPractices_RenderPass_RedundantClear,
LawG4015be1c2022-03-01 10:37:52 +00002582 "%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 +02002583 "image was used, it was written to with vkCmdClear*Image(). "
2584 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
LawG44d414ba2022-02-23 15:35:41 +00002585 "tile-based architectures.",
2586 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002587 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002588 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
2589 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE || last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01002590 const char *last_cmd = nullptr;
2591 const char *vuid = nullptr;
2592 const char *suggestion = nullptr;
2593
2594 switch (last_usage) {
2595 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
2596 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
2597 last_cmd = "vkCmdBlitImage";
2598 suggestion =
2599 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2600 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
2601 "which avoids the memory roundtrip.";
2602 break;
2603 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
2604 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
2605 last_cmd = "vkCmdClear*Image";
2606 suggestion =
2607 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
2608 "tile-based architectures. "
2609 "Use LOAD_OP_CLEAR instead to clear the image for free.";
2610 break;
2611 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
2612 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
2613 last_cmd = "vkCmdCopy*Image";
2614 suggestion =
2615 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
2616 "Rather than copying, just render the source image in a fragment shader in this render pass, "
2617 "which avoids the memory roundtrip.";
2618 break;
2619 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
2620 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
2621 last_cmd = "vkCmdResolveImage";
2622 suggestion =
2623 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
2624 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
2625 "which avoids the memory roundtrip.";
2626 break;
2627 default:
2628 break;
2629 }
2630
2631 LogPerformanceWarning(
2632 device, vuid,
LawG4015be1c2022-03-01 10:37:52 +00002633 "%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 +01002634 "time image was used, it was written to with %s. %s",
LawG44d414ba2022-02-23 15:35:41 +00002635 function_name, VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), array_layer, mip_level, last_cmd,
2636 suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002637 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002638}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002639
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002640void BestPractices::ValidateImageInQueue(const char* function_name, bp_state::Image& state, IMAGE_SUBRESOURCE_USAGE_BP usage,
2641 uint32_t array_layer, uint32_t mip_level) {
2642 auto last_usage = state.UpdateUsage(array_layer, mip_level, usage);
paul-lunarg5eb52062022-06-27 18:57:15 +02002643
2644 // When image was discarded with StoreOpDontCare but is now being read with LoadOpLoad
2645 if (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED &&
2646 usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE) {
2647 LogWarning(device, kVUID_BestPractices_StoreOpDontCareThenLoadOpLoad,
2648 "Trying to load an attachment with LOAD_OP_LOAD that was previously stored with STORE_OP_DONT_CARE. This may "
2649 "result in undefined behaviour.");
2650 }
2651
LawG44d414ba2022-02-23 15:35:41 +00002652 if (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) {
2653 ValidateImageInQueueArmImg(function_name, state, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02002654 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002655}
2656
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002657void BestPractices::AddDeferredQueueOperations(bp_state::CommandBuffer& cb) {
2658 cb.queue_submit_functions.insert(cb.queue_submit_functions.end(), cb.queue_submit_functions_after_render_pass.begin(),
2659 cb.queue_submit_functions_after_render_pass.end());
2660 cb.queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002661}
2662
2663void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002664 RecordCmdEndRenderingCommon(commandBuffer);
2665
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002666 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002667 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2668 if (cb_node) {
2669 AddDeferredQueueOperations(*cb_node);
2670 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002671}
2672
2673void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002674 RecordCmdEndRenderingCommon(commandBuffer);
2675
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002676 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002677 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2678 if (cb_node) {
2679 AddDeferredQueueOperations(*cb_node);
2680 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002681}
2682
2683void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002684 RecordCmdEndRenderingCommon(commandBuffer);
2685
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002686 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002687 auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2688 if (cb_node) {
2689 AddDeferredQueueOperations(*cb_node);
2690 }
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002691}
2692
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002693void BestPractices::PreCallRecordCmdEndRendering(VkCommandBuffer commandBuffer) {
2694 RecordCmdEndRenderingCommon(commandBuffer);
2695
2696 ValidationStateTracker::PreCallRecordCmdEndRendering(commandBuffer);
2697}
2698
2699void BestPractices::PreCallRecordCmdEndRenderingKHR(VkCommandBuffer commandBuffer) {
2700 RecordCmdEndRenderingCommon(commandBuffer);
2701
2702 ValidationStateTracker::PreCallRecordCmdEndRenderingKHR(commandBuffer);
2703}
2704
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002705void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
2706 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002707 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002708 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002709 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002710 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2711}
2712
2713void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
2714 const VkRenderPassBeginInfo* pRenderPassBegin,
2715 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2716 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002717 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002718 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2719}
2720
2721void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2722 const VkRenderPassBeginInfo* pRenderPassBegin,
2723 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2724 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002725 RecordCmdBeginRenderingCommon(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002726 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
2727}
2728
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002729void BestPractices::PreCallRecordCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2730 ValidationStateTracker::PreCallRecordCmdBeginRendering(commandBuffer, pRenderingInfo);
2731 RecordCmdBeginRenderingCommon(commandBuffer);
2732}
2733
2734void BestPractices::PreCallRecordCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) {
2735 ValidationStateTracker::PreCallRecordCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2736 RecordCmdBeginRenderingCommon(commandBuffer);
2737}
2738
2739void BestPractices::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
2740 ValidationStateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
2741
2742 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
2743 auto rp = cmd_state->activeRenderPass.get();
2744 assert(rp);
2745
2746 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2747 IMAGE_VIEW_STATE* depth_image_view = nullptr;
2748
2749 const auto depth_attachment = rp->createInfo.pSubpasses[cmd_state->activeSubpass].pDepthStencilAttachment;
2750 if (depth_attachment) {
2751 const uint32_t attachment_index = depth_attachment->attachment;
2752 if (attachment_index != VK_ATTACHMENT_UNUSED) {
2753 depth_image_view = (*cmd_state->active_attachments)[attachment_index];
2754 }
2755 }
2756 if (depth_image_view && (depth_image_view->create_info.subresourceRange.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0U) {
2757 const VkImage depth_image = depth_image_view->image_state->image();
2758 const VkImageSubresourceRange& subresource_range = depth_image_view->create_info.subresourceRange;
2759 RecordBindZcullScope(*cmd_state, depth_image, subresource_range);
2760 } else {
2761 RecordUnbindZcullScope(*cmd_state);
2762 }
2763 }
2764}
2765
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002766void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002767
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002768 if (!pRenderPassBegin) {
2769 return;
2770 }
2771
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002772 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002773
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002774 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002775 if (rp_state) {
2776 // Check load ops
2777 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002778 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002779
2780 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
2781 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2782 continue;
2783 }
2784
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002785 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002786
2787 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
2788 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002789 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002790 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
2791 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002792 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02002793 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002794 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002795 }
2796
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002797 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Jeremy Gebben9f537102021-10-05 16:37:12 -06002798 std::shared_ptr<IMAGE_VIEW_STATE> image_view = nullptr;
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002799
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002800 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002801 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2802 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002803 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002804 }
2805 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002806 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002807 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002808
Jeremy Gebben9f537102021-10-05 16:37:12 -06002809 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002810 }
2811
2812 // Check store ops
2813 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002814 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002815
2816 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
2817 continue;
2818 }
2819
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002820 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002821
2822 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
2823 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002824 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002825 }
2826
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002827 auto framebuffer = Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002828
Jeremy Gebben9f537102021-10-05 16:37:12 -06002829 std::shared_ptr<IMAGE_VIEW_STATE> image_view;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06002830 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002831 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
2832 if (rpabi) {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002833 image_view = Get<IMAGE_VIEW_STATE>(rpabi->pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002834 }
2835 } else {
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06002836 image_view = Get<IMAGE_VIEW_STATE>(framebuffer->createInfo.pAttachments[att]);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01002837 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002838
Jeremy Gebben9f537102021-10-05 16:37:12 -06002839 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view.get(), usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002840 }
2841 }
2842}
2843
Attilio Provenzano02859b22020-02-27 14:17:28 +00002844bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2845 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002846 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2847 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002848 return skip;
2849}
2850
2851bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2852 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002853 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002854 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2855 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002856 return skip;
2857}
2858
2859bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08002860 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01002861 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2862 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002863 return skip;
2864}
2865
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03002866bool BestPractices::PreCallValidateCmdBeginRendering(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2867 bool skip = StateTracker::PreCallValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2868 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2869 return skip;
2870}
2871
2872bool BestPractices::PreCallValidateCmdBeginRenderingKHR(VkCommandBuffer commandBuffer, const VkRenderingInfo* pRenderingInfo) const {
2873 bool skip = StateTracker::PreCallValidateCmdBeginRenderingKHR(commandBuffer, pRenderingInfo);
2874 skip |= ValidateCmdBeginRendering(commandBuffer, pRenderingInfo);
2875 return skip;
2876}
2877
Sam Walls0961ec02020-03-31 16:39:15 +01002878void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
2879 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002880 // Reset the renderpass state
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002881 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
sjfricke52defd42022-08-08 16:37:46 +09002882 // TODO - move this logic to the Render Pass state as cb->has_draw_cmd should stay true for lifetime of command buffer
2883 cb->has_draw_cmd = false;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002884 assert(cb);
2885 auto& render_pass_state = cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002886 render_pass_state.touchesAttachments.clear();
2887 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002888 render_pass_state.numDrawCallsDepthOnly = 0;
2889 render_pass_state.numDrawCallsDepthEqualCompare = 0;
2890 render_pass_state.colorAttachment = false;
2891 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002892 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002893 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01002894
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03002895 // Reset NV state
2896 cb->nv = {};
2897
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002898 auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01002899
2900 // track depth / color attachment usage within the renderpass
2901 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
2902 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002903 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002904
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02002905 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01002906 }
2907}
2908
2909void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2910 VkSubpassContents contents) {
2911 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
2912 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
2913}
2914
2915void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
2916 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2917 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2918 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2919}
2920
2921void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
2922 const VkRenderPassBeginInfo* pRenderPassBegin,
2923 const VkSubpassBeginInfo* pSubpassBeginInfo) {
2924 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
2925 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
2926}
2927
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002928// Generic function to handle validation for all CmdDraw* type functions
2929bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
2930 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002931 const auto cb_state = GetRead<bp_state::CommandBuffer>(cmd_buffer);
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002932 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002933 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
2934 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002935 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06002936
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002937 // Verify vertex binding
Tony-LunarG2ffe1f52022-04-11 15:13:30 -06002938 if (pipeline_state && pipeline_state->vertex_input_state &&
2939 pipeline_state->vertex_input_state->binding_descriptions.size() <= 0) {
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002940 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002941 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002942 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002943 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
2944 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002945 }
2946 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002947
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002948 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002949 if (pipe) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002950 const auto& rp_state = pipe->RenderPassState();
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002951 if (rp_state) {
2952 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
2953 const auto& subpass = rp_state->createInfo.pSubpasses[i];
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002954 const auto* ds_state = pipe->DepthStencilState();
Jeremy Gebben11af9792021-08-20 10:20:09 -06002955 const uint32_t depth_stencil_attachment =
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002956 GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
2957 const auto* raster_state = pipe->RasterizationState();
2958 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && raster_state &&
2959 raster_state->depthBiasEnable == VK_TRUE) {
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06002960 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
2961 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
2962 }
2963 }
2964 }
2965 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002966 }
2967 return skip;
2968}
2969
Sam Walls0961ec02020-03-31 16:39:15 +01002970void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002971 auto cb_node = GetWrite<bp_state::CommandBuffer>(cmd_buffer);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06002972 assert(cb_node);
Sam Walls0961ec02020-03-31 16:39:15 +01002973 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002974 RecordCmdDrawTypeArm(*cb_node, draw_count, caller);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002975 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03002976 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
2977 RecordCmdDrawTypeNVIDIA(*cb_node);
2978 }
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002979
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002980 if (cb_node->render_pass_state.drawTouchAttachments) {
2981 for (auto& touch : cb_node->render_pass_state.nextDrawTouchesAttachments) {
2982 RecordAttachmentAccess(*cb_node, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002983 }
2984 // No need to touch the same attachments over and over.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002985 cb_node->render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002986 }
2987}
2988
Jeremy Gebben20da7a12022-02-25 14:07:46 -07002989void BestPractices::RecordCmdDrawTypeArm(bp_state::CommandBuffer& cb_node, uint32_t draw_count, const char* caller) {
2990 auto& render_pass_state = cb_node.render_pass_state;
LawG4b21485c2022-02-28 13:46:48 +00002991 // Each TBDR vendor requires a depth pre-pass draw call to have a minimum number of vertices/indices before it counts towards
2992 // depth prepass warnings First find the lowest enabled draw count
2993 uint32_t lowestEnabledMinDrawCount = 0;
2994 lowestEnabledMinDrawCount = VendorCheckEnabled(kBPVendorArm) * kDepthPrePassMinDrawCountArm;
2995 if (VendorCheckEnabled(kBPVendorIMG) && kDepthPrePassMinDrawCountIMG < lowestEnabledMinDrawCount)
2996 lowestEnabledMinDrawCount = kDepthPrePassMinDrawCountIMG;
2997
2998 if (draw_count >= lowestEnabledMinDrawCount) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002999 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
3000 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01003001 }
3002}
3003
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003004void BestPractices::RecordCmdDrawTypeNVIDIA(bp_state::CommandBuffer& cmd_state) {
3005 assert(VendorCheckEnabled(kBPVendorNVIDIA));
3006
3007 if (cmd_state.nv.depth_test_enable && cmd_state.nv.zcull_direction != bp_state::CommandBufferStateNV::ZcullDirection::Unknown) {
3008 RecordSetScopeZcullDirection(cmd_state, cmd_state.nv.zcull_direction);
3009 RecordZcullDraw(cmd_state);
3010 }
3011}
3012
Camden5b184be2019-08-13 07:50:19 -06003013bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003014 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003015 bool skip = false;
3016
3017 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003018 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3019 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003020 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06003021 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06003022
3023 return skip;
3024}
3025
Sam Walls0961ec02020-03-31 16:39:15 +01003026void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3027 uint32_t firstVertex, uint32_t firstInstance) {
3028 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
3029 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
3030}
3031
Camden5b184be2019-08-13 07:50:19 -06003032bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003033 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06003034 bool skip = false;
3035
3036 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003037 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
3038 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003039 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003040 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
3041
Attilio Provenzano02859b22020-02-27 14:17:28 +00003042 // Check if we reached the limit for small indexed draw calls.
3043 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003044 const auto cmd_state = GetRead<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003045 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003046 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
LawG4ff42d722022-03-01 10:28:25 +00003047 (VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG))) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003048 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
LawG4ff42d722022-03-01 10:28:25 +00003049 "%s %s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00003050 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
3051 "You can try batching drawcalls or instancing when applicable.",
LawG4ff42d722022-03-01 10:28:25 +00003052 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), kMaxSmallIndexedDrawcalls,
3053 kSmallIndexedDrawcallIndices);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003054 }
3055
Sam Walls8e77e4f2020-03-16 20:47:40 +00003056 if (VendorCheckEnabled(kBPVendorArm)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003057 ValidateIndexBufferArm(*cmd_state, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003058 }
3059
3060 return skip;
3061}
3062
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003063bool BestPractices::ValidateIndexBufferArm(const bp_state::CommandBuffer& cmd_state, uint32_t indexCount, uint32_t instanceCount,
Sam Walls8e77e4f2020-03-16 20:47:40 +00003064 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
3065 bool skip = false;
3066
3067 // check for sparse/underutilised index buffer, and post-transform cache thrashing
Sam Walls8e77e4f2020-03-16 20:47:40 +00003068
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003069 const auto* ib_state = cmd_state.index_buffer_binding.buffer_state.get();
3070 if (ib_state == nullptr || cmd_state.index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003071
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003072 const VkIndexType ib_type = cmd_state.index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06003073 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00003074 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
3075 const void* ib_mem = ib_mem_state.p_driver_data;
3076 bool primitive_restart_enable = false;
3077
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003078 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003079 const auto& pipeline_binding_iter = cmd_state.lastBound[lv_bind_point];
locke-lunargb8d7a7a2020-10-25 16:01:52 -06003080 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003081
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07003082 const auto* ia_state = pipeline_state ? pipeline_state->InputAssemblyState() : nullptr;
3083 if (ia_state) {
3084 primitive_restart_enable = ia_state->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07003085 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00003086
3087 // 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 -06003088 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00003089 uint32_t scan_stride;
3090 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3091 scan_stride = sizeof(uint8_t);
3092 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3093 scan_stride = sizeof(uint16_t);
3094 } else {
3095 scan_stride = sizeof(uint32_t);
3096 }
3097
3098 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
3099 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
3100
3101 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
3102 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
3103 // irrespective of whether or not they're part of the draw call.
3104
3105 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
3106 uint32_t min_index = ~0u;
3107 // start with maximum as 0 and adjust to indices in the buffer
3108 uint32_t max_index = 0u;
3109
3110 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
3111 // for the given index buffer
3112 uint32_t vertex_shade_count = 0;
3113
3114 PostTransformLRUCacheModel post_transform_cache;
3115
3116 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
3117 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
3118 // target architecture.
3119 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
3120 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
3121 post_transform_cache.resize(32);
3122
3123 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3124 uint32_t scan_index;
3125 uint32_t primitive_restart_value;
3126 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3127 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3128 primitive_restart_value = 0xFF;
3129 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3130 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3131 primitive_restart_value = 0xFFFF;
3132 } else {
3133 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3134 primitive_restart_value = 0xFFFFFFFF;
3135 }
3136
3137 max_index = std::max(max_index, scan_index);
3138 min_index = std::min(min_index, scan_index);
3139
3140 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
3141 bool in_cache = post_transform_cache.query_cache(scan_index);
3142 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
3143 if (!in_cache) vertex_shade_count++;
3144 }
3145 }
3146
3147 // 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 +01003148 // 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
3149 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00003150
3151 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07003152 skip |=
3153 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3154 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
3155 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
3156 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
3157 "maximum would be loaded, and possibly shaded, whether or not they are used.",
3158 VendorSpecificTag(kBPVendorArm),
3159 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003160 return skip;
3161 }
3162
3163 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
3164 // 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 +01003165 const size_t refs_per_bucket = 64;
3166 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
3167
3168 const uint32_t n_indices = max_index - min_index + 1;
3169 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
3170 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
3171
3172 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
3173 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00003174
3175 // To avoid using too much memory, we run over the indices again.
3176 // Knowing the size from the last scan allows us to record index usage with bitsets
3177 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
3178 uint32_t scan_index;
3179 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
3180 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
3181 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
3182 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
3183 } else {
3184 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
3185 }
3186 // keep track of the set of all indices used to reference vertices in the draw call
3187 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01003188 size_t bitset_bucket_index = index_offset / refs_per_bucket;
3189 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003190 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
3191 }
3192
3193 uint32_t vertex_reference_count = 0;
3194 for (const auto& bitset : vertex_reference_buckets) {
3195 vertex_reference_count += static_cast<uint32_t>(bitset.count());
3196 }
3197
3198 // 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 -07003199 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003200 // 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 -07003201 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00003202
3203 if (utilization < 0.5f) {
3204 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
3205 "%s The indices which were specified for the draw call only utilise approximately "
3206 "%.02f%% of the bound vertex buffer.",
3207 VendorSpecificTag(kBPVendorArm), utilization);
3208 }
3209
3210 if (cache_hit_rate <= 0.5f) {
3211 skip |=
3212 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
3213 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
3214 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
3215 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
3216 "recently shaded vertices.",
3217 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
3218 }
3219 }
3220
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07003221 return skip;
3222}
3223
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003224bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3225 const VkCommandBuffer* pCommandBuffers) const {
3226 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003227 const auto primary = GetRead<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003228 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003229 const auto secondary_cb = GetRead<bp_state::CommandBuffer>(pCommandBuffers[i]);
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003230 if (secondary_cb == nullptr) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003231 continue;
3232 }
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003233 const auto& secondary = secondary_cb->render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003234 for (auto& clear : secondary.earlyClearAttachments) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003235 if (ClearAttachmentsIsFullClear(*primary, uint32_t(clear.rects.size()), clear.rects.data())) {
3236 skip |= ValidateClearAttachment(*primary, clear.framebufferAttachment, clear.colorAttachment, clear.aspects, true);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003237 }
3238 }
3239 }
Nadav Gevaf0808442021-05-21 13:51:25 -04003240
3241 if (VendorCheckEnabled(kBPVendorAMD)) {
3242 if (commandBufferCount > 0) {
3243 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdBuffer_AvoidSecondaryCmdBuffers,
3244 "%s Performance warning: Use of secondary command buffers is not recommended. ",
3245 VendorSpecificTag(kBPVendorAMD));
3246 }
3247 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003248 return skip;
3249}
3250
3251void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
3252 const VkCommandBuffer* pCommandBuffers) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003253 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
3254
3255 auto primary = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3256 if (!primary) {
3257 return;
3258 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003259
3260 for (uint32_t i = 0; i < commandBufferCount; i++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003261 auto secondary = GetWrite<bp_state::CommandBuffer>(pCommandBuffers[i]);
3262 if (!secondary) {
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003263 continue;
3264 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003265
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003266 for (auto& early_clear : secondary->render_pass_state.earlyClearAttachments) {
3267 if (ClearAttachmentsIsFullClear(*primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
3268 RecordAttachmentClearAttachments(*primary, early_clear.framebufferAttachment, early_clear.colorAttachment,
3269 early_clear.aspects, uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003270 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003271 RecordAttachmentAccess(*primary, early_clear.framebufferAttachment, early_clear.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003272 }
3273 }
3274
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003275 for (auto& touch : secondary->render_pass_state.touchesAttachments) {
3276 RecordAttachmentAccess(*primary, touch.framebufferAttachment, touch.aspects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003277 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02003278
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003279 primary->render_pass_state.numDrawCallsDepthEqualCompare += secondary->render_pass_state.numDrawCallsDepthEqualCompare;
3280 primary->render_pass_state.numDrawCallsDepthOnly += secondary->render_pass_state.numDrawCallsDepthOnly;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003281 }
3282
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003283}
3284
Rodrigo Locatti7d716e12022-03-09 19:15:17 -03003285bool BestPractices::PreCallValidateCmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer,
3286 const VkAccelerationStructureInfoNV* pInfo,
3287 VkBuffer instanceData, VkDeviceSize instanceOffset,
3288 VkBool32 update, VkAccelerationStructureNV dst,
3289 VkAccelerationStructureNV src, VkBuffer scratch,
3290 VkDeviceSize scratchOffset) const {
3291 return ValidateBuildAccelerationStructure(commandBuffer);
3292}
3293
3294bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresIndirectKHR(
3295 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3296 const VkDeviceAddress* pIndirectDeviceAddresses, const uint32_t* pIndirectStrides,
3297 const uint32_t* const* ppMaxPrimitiveCounts) const {
3298 return ValidateBuildAccelerationStructure(commandBuffer);
3299}
3300
3301bool BestPractices::PreCallValidateCmdBuildAccelerationStructuresKHR(
3302 VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR* pInfos,
3303 const VkAccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const {
3304 return ValidateBuildAccelerationStructure(commandBuffer);
3305}
3306
3307bool BestPractices::ValidateBuildAccelerationStructure(VkCommandBuffer commandBuffer) const {
3308 bool skip = false;
3309 auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
3310 assert(cb_node);
3311
3312 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3313 if ((cb_node->GetQueueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) {
3314 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_AccelerationStructure_NotAsync,
3315 "%s Performance warning: Prefer building acceleration structures on an asynchronous "
3316 "compute queue, instead of using the universal graphics queue.",
3317 VendorSpecificTag(kBPVendorNVIDIA));
3318 }
3319 }
3320
3321 return skip;
3322}
3323
Rodrigo Locatti66b23352022-03-15 17:28:32 -03003324bool BestPractices::ValidateBindMemory(VkDevice device, VkDeviceMemory memory) const {
3325 bool skip = false;
3326
3327 if (VendorCheckEnabled(kBPVendorNVIDIA) && device_extensions.vk_ext_pageable_device_local_memory) {
3328 auto mem_info = std::static_pointer_cast<const bp_state::DeviceMemory>(Get<DEVICE_MEMORY_STATE>(memory));
3329 if (!mem_info->dynamic_priority) {
3330 skip |=
3331 LogPerformanceWarning(device, kVUID_BestPractices_BindMemory_NoPriority,
3332 "%s Use vkSetDeviceMemoryPriorityEXT to provide the OS with information on which allocations "
3333 "should stay in memory and which should be demoted first when video memory is limited. The "
3334 "highest priority should be given to GPU-written resources like color attachments, depth "
3335 "attachments, storage images, and buffers written from the GPU.",
3336 VendorSpecificTag(kBPVendorNVIDIA));
3337 }
3338 }
3339
3340 return skip;
3341}
3342
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003343void BestPractices::RecordAttachmentAccess(bp_state::CommandBuffer& cb_state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
3344 auto& state = cb_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003345 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003346 auto itr =
3347 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3348 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003349
3350 if (itr != state.touchesAttachments.end()) {
3351 itr->aspects |= aspects;
3352 } else {
3353 state.touchesAttachments.push_back({ fb_attachment, aspects });
3354 }
3355}
3356
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003357void BestPractices::RecordAttachmentClearAttachments(bp_state::CommandBuffer& cmd_state, uint32_t fb_attachment,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003358 uint32_t color_attachment, VkImageAspectFlags aspects, uint32_t rectCount,
3359 const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003360 auto& state = cmd_state.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003361 // If we observe a full clear before any other access to a frame buffer attachment,
3362 // we have candidate for redundant clear attachments.
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003363 auto itr =
3364 std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
3365 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003366
3367 uint32_t new_aspects = aspects;
3368 if (itr != state.touchesAttachments.end()) {
3369 new_aspects = aspects & ~itr->aspects;
3370 itr->aspects |= aspects;
3371 } else {
3372 state.touchesAttachments.push_back({ fb_attachment, aspects });
3373 }
3374
3375 if (new_aspects == 0) {
3376 return;
3377 }
3378
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003379 if (cmd_state.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003380 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
3381 // CmdExecuteCommands.
3382 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
3383 std::vector<VkClearRect>{pRects, pRects + rectCount} });
3384 }
3385}
3386
3387void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
3388 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
3389 uint32_t rectCount, const VkClearRect* pRects) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003390 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments, rectCount, pRects);
3391
3392 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3393 auto* rp_state = cmd_state->activeRenderPass.get();
3394 auto* fb_state = cmd_state->activeFramebuffer.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003395 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
3396
3397 if (rectCount == 0 || !rp_state) {
3398 return;
3399 }
3400
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003401 if (!is_secondary && !fb_state && !rp_state->use_dynamic_rendering && !rp_state->use_dynamic_rendering_inherited) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003402 return;
3403 }
3404
3405 // 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 -03003406 const bool full_clear = ClearAttachmentsIsFullClear(*cmd_state, rectCount, pRects);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003407
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003408 if (rp_state->UsesDynamicRendering()) {
3409 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003410 auto pColorAttachments = rp_state->dynamic_rendering_begin_rendering_info.pColorAttachments;
3411
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003412 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003413 auto& clear_attachment = pClearAttachments[i];
3414
3415 if (clear_attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003416 RecordResetScopeZcullDirection(*cmd_state);
3417 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003418 if ((clear_attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) &&
3419 clear_attachment.colorAttachment != VK_ATTACHMENT_UNUSED &&
3420 pColorAttachments) {
3421 const auto& attachment = pColorAttachments[clear_attachment.colorAttachment];
3422 if (attachment.imageView) {
3423 auto image_view_state = Get<IMAGE_VIEW_STATE>(attachment.imageView);
3424 const VkFormat format = image_view_state->create_info.format;
3425 RecordClearColor(format, clear_attachment.clearValue.color);
3426 }
3427 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003428 }
3429 }
3430
3431 // TODO: Implement other best practices for dynamic rendering
3432
3433 } else {
ziga-lunarg885c6542022-03-07 01:08:25 +01003434 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
3435 for (uint32_t i = 0; i < attachmentCount; i++) {
3436 auto& attachment = pClearAttachments[i];
3437 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
3438 VkImageAspectFlags aspects = attachment.aspectMask;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003439
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003440 if (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
3441 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3442 RecordResetScopeZcullDirection(*cmd_state);
3443 }
3444 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003445 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
3446 if (subpass.pDepthStencilAttachment) {
3447 fb_attachment = subpass.pDepthStencilAttachment->attachment;
3448 }
3449 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
3450 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003451 }
ziga-lunarg885c6542022-03-07 01:08:25 +01003452 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
3453 if (full_clear) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003454 RecordAttachmentClearAttachments(*cmd_state, fb_attachment, attachment.colorAttachment,
ziga-lunarg885c6542022-03-07 01:08:25 +01003455 aspects, rectCount, pRects);
3456 } else {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003457 RecordAttachmentAccess(*cmd_state, fb_attachment, aspects);
ziga-lunarg885c6542022-03-07 01:08:25 +01003458 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03003459 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3460 const VkFormat format = rp_state->createInfo.pAttachments[fb_attachment].format;
3461 RecordClearColor(format, attachment.clearValue.color);
3462 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003463 }
3464 }
3465 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02003466}
3467
Attilio Provenzano02859b22020-02-27 14:17:28 +00003468void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3469 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3470 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
3471 firstInstance);
3472
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003473 auto cmd_state = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003474 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
3475 cmd_state->small_indexed_draw_call_count++;
3476 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003477
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003478 ValidateBoundDescriptorSets(*cmd_state, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00003479}
3480
Sam Walls0961ec02020-03-31 16:39:15 +01003481void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
3482 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
3483 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
3484 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
3485}
3486
Camden5b184be2019-08-13 07:50:19 -06003487bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003488 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003489 bool skip = false;
3490
3491 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003492 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3493 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003494 }
3495
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003496 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
3497
Camden5b184be2019-08-13 07:50:19 -06003498 return skip;
3499}
3500
Sam Walls0961ec02020-03-31 16:39:15 +01003501void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3502 uint32_t count, uint32_t stride) {
3503 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
3504 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
3505}
3506
Camden5b184be2019-08-13 07:50:19 -06003507bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003508 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06003509 bool skip = false;
3510
3511 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003512 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
3513 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06003514 }
3515
Rodrigo Locatti8419cde2022-03-30 18:45:13 -03003516 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
3517
Camden5b184be2019-08-13 07:50:19 -06003518 return skip;
3519}
3520
Sam Walls0961ec02020-03-31 16:39:15 +01003521void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3522 uint32_t count, uint32_t stride) {
3523 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
3524 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
3525}
3526
Rodrigo Locatti467344a2022-03-30 18:48:13 -03003527bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3528 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3529 uint32_t maxDrawCount, uint32_t stride) const {
3530 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
3531
3532 return skip;
3533}
3534
3535void BestPractices::PostCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3536 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3537 uint32_t maxDrawCount, uint32_t stride) {
3538 StateTracker::PostCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3539 maxDrawCount, stride);
3540 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCount()");
3541}
3542
3543bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3544 VkDeviceSize offset, VkBuffer countBuffer,
3545 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3546 uint32_t stride) const {
3547 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountAMD");
3548
3549 return skip;
3550}
3551
3552void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
3553 VkDeviceSize offset, VkBuffer countBuffer,
3554 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3555 uint32_t stride) {
3556 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3557 maxDrawCount, stride);
3558 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountAMD()");
3559}
3560
3561bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3562 VkDeviceSize offset, VkBuffer countBuffer,
3563 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3564 uint32_t stride) const {
3565 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR");
3566
3567 return skip;
3568}
3569
3570void BestPractices::PostCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
3571 VkDeviceSize offset, VkBuffer countBuffer,
3572 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3573 uint32_t stride) {
3574 StateTracker::PostCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3575 maxDrawCount, stride);
3576 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndexedIndirectCountKHR()");
3577}
3578
3579bool BestPractices::PreCallValidateCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3580 uint32_t firstInstance, VkBuffer counterBuffer,
3581 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3582 uint32_t vertexStride) const {
3583 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectByteCountEXT");
3584
3585 return skip;
3586}
3587
3588void BestPractices::PostCallRecordCmdDrawIndirectByteCountEXT(VkCommandBuffer commandBuffer, uint32_t instanceCount,
3589 uint32_t firstInstance, VkBuffer counterBuffer,
3590 VkDeviceSize counterBufferOffset, uint32_t counterOffset,
3591 uint32_t vertexStride) {
3592 StateTracker::PostCallRecordCmdDrawIndirectByteCountEXT(commandBuffer, instanceCount, firstInstance, counterBuffer,
3593 counterBufferOffset, counterOffset, vertexStride);
3594 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectByteCountEXT()");
3595}
3596
3597bool BestPractices::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3598 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3599 uint32_t stride) const {
3600 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCount");
3601
3602 return skip;
3603}
3604
3605void BestPractices::PostCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3606 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3607 uint32_t stride) {
3608 StateTracker::PostCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3609 stride);
3610 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCount()");
3611}
3612
3613bool BestPractices::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3614 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3615 uint32_t maxDrawCount, uint32_t stride) const {
3616 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountAMD");
3617
3618 return skip;
3619}
3620
3621void BestPractices::PostCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3622 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3623 uint32_t maxDrawCount, uint32_t stride) {
3624 StateTracker::PostCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3625 stride);
3626 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountAMD()");
3627}
3628
3629bool BestPractices::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3630 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3631 uint32_t maxDrawCount, uint32_t stride) const {
3632 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirectCountKHR");
3633
3634 return skip;
3635}
3636
3637void BestPractices::PostCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3638 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
3639 uint32_t maxDrawCount, uint32_t stride) {
3640 StateTracker::PostCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
3641 stride);
3642 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawIndirectCountKHR()");
3643}
3644
3645bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3646 VkDeviceSize offset, VkBuffer countBuffer,
3647 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3648 uint32_t stride) const {
3649 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectCountNV");
3650
3651 return skip;
3652}
3653
3654void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectCountNV(VkCommandBuffer commandBuffer, VkBuffer buffer,
3655 VkDeviceSize offset, VkBuffer countBuffer,
3656 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
3657 uint32_t stride) {
3658 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectCountNV(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
3659 maxDrawCount, stride);
3660 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectCountNV()");
3661}
3662
3663bool BestPractices::PreCallValidateCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3664 uint32_t drawCount, uint32_t stride) const {
3665 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksIndirectNV");
3666
3667 return skip;
3668}
3669
3670void BestPractices::PostCallRecordCmdDrawMeshTasksIndirectNV(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3671 uint32_t drawCount, uint32_t stride) {
3672 StateTracker::PostCallRecordCmdDrawMeshTasksIndirectNV(commandBuffer, buffer, offset, drawCount, stride);
3673 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksIndirectNV()");
3674}
3675
3676bool BestPractices::PreCallValidateCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) const {
3677 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMeshTasksNV");
3678
3679 return skip;
3680}
3681
3682void BestPractices::PostCallRecordCmdDrawMeshTasksNV(VkCommandBuffer commandBuffer, uint32_t taskCount, uint32_t firstTask) {
3683 StateTracker::PostCallRecordCmdDrawMeshTasksNV(commandBuffer, taskCount, firstTask);
3684 RecordCmdDrawType(commandBuffer, 0, "vkCmdDrawMeshTasksNV()");
3685}
3686
3687bool BestPractices::PreCallValidateCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3688 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3689 uint32_t firstInstance, uint32_t stride,
3690 const int32_t* pVertexOffset) const {
3691 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiIndexedEXT");
3692
3693 return skip;
3694}
3695
3696void BestPractices::PostCallRecordCmdDrawMultiIndexedEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3697 const VkMultiDrawIndexedInfoEXT* pIndexInfo, uint32_t instanceCount,
3698 uint32_t firstInstance, uint32_t stride, const int32_t* pVertexOffset) {
3699 StateTracker::PostCallRecordCmdDrawMultiIndexedEXT(commandBuffer, drawCount, pIndexInfo, instanceCount, firstInstance, stride,
3700 pVertexOffset);
3701 uint32_t count = 0;
3702 for (uint32_t i = 0; i < drawCount; ++i) {
3703 count += pIndexInfo[i].indexCount;
3704 }
3705 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiIndexedEXT()");
3706}
3707
3708bool BestPractices::PreCallValidateCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount, const VkMultiDrawInfoEXT* pVertexInfo,
3709 uint32_t instanceCount, uint32_t firstInstance, uint32_t stride) const {
3710 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawMultiEXT");
3711
3712 return skip;
3713}
3714
3715void BestPractices::PostCallRecordCmdDrawMultiEXT(VkCommandBuffer commandBuffer, uint32_t drawCount,
3716 const VkMultiDrawInfoEXT* pVertexInfo, uint32_t instanceCount,
3717 uint32_t firstInstance, uint32_t stride) {
3718 StateTracker::PostCallRecordCmdDrawMultiEXT(commandBuffer, drawCount, pVertexInfo, instanceCount, firstInstance, stride);
3719 uint32_t count = 0;
3720 for (uint32_t i = 0; i < drawCount; ++i) {
3721 count += pVertexInfo[i].vertexCount;
3722 }
3723 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawMultiEXT()");
3724}
3725
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003726void BestPractices::ValidateBoundDescriptorSets(bp_state::CommandBuffer& cb_state, const char* function_name) {
3727 for (auto descriptor_set : cb_state.validated_descriptor_sets) {
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003728 for (const auto& binding : *descriptor_set) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003729 // For bindless scenarios, we should not attempt to track descriptor set state.
3730 // It is highly uncertain which resources are actually bound.
3731 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003732 if (binding->binding_flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
3733 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003734 continue;
3735 }
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003736
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003737 for (uint32_t i = 0; i < binding->count; ++i) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003738 VkImageView image_view{VK_NULL_HANDLE};
3739
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06003740 auto descriptor = binding->GetDescriptor(i);
ziga-lunarg33d806c2022-05-05 17:00:52 +02003741 if (!descriptor) {
3742 continue;
3743 }
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003744 switch (descriptor->GetClass()) {
3745 case cvdescriptorset::DescriptorClass::Image: {
3746 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
3747 image_view = image_descriptor->GetImageView();
3748 }
3749 break;
3750 }
3751 case cvdescriptorset::DescriptorClass::ImageSampler: {
3752 if (const auto image_sampler_descriptor =
3753 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
3754 image_view = image_sampler_descriptor->GetImageView();
3755 }
3756 break;
3757 }
3758 default:
3759 break;
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01003760 }
3761
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003762 if (image_view) {
3763 auto image_view_state = Get<IMAGE_VIEW_STATE>(image_view);
3764 QueueValidateImageView(cb_state.queue_submit_functions, function_name, image_view_state.get(),
3765 IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003766 }
3767 }
3768 }
3769 }
3770}
3771
3772void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
3773 uint32_t firstVertex, uint32_t firstInstance) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003774 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3775 ValidateBoundDescriptorSets(*cb_node, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003776}
3777
3778void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3779 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003780 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3781 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003782}
3783
3784void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
3785 uint32_t drawCount, uint32_t stride) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003786 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3787 ValidateBoundDescriptorSets(*cb_node, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003788}
3789
Camden5b184be2019-08-13 07:50:19 -06003790bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003791 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06003792 bool skip = false;
3793
3794 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07003795 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
3796 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
3797 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
3798 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06003799 }
3800
3801 return skip;
3802}
Camden83a9c372019-08-14 11:41:38 -06003803
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003804bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3805 bool skip = false;
3806 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
3807 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003808 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3809 skip |= ValidateZcullScope(commandBuffer);
3810 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003811 return skip;
3812}
3813
3814bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
3815 bool skip = false;
3816 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
3817 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003818 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3819 skip |= ValidateZcullScope(commandBuffer);
3820 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003821 return skip;
3822}
3823
Sam Walls0961ec02020-03-31 16:39:15 +01003824bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3825 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01003826 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003827 skip |= ValidateCmdEndRenderPass(commandBuffer);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03003828 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3829 skip |= ValidateZcullScope(commandBuffer);
3830 }
3831 return skip;
3832}
3833
3834bool BestPractices::PreCallValidateCmdEndRendering(VkCommandBuffer commandBuffer) const {
3835 bool skip = false;
3836 skip |= StateTracker::PreCallValidateCmdEndRendering(commandBuffer);
3837 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3838 skip |= ValidateZcullScope(commandBuffer);
3839 }
3840 return skip;
3841}
3842
3843bool BestPractices::PreCallValidateCmdEndRenderingKHR(VkCommandBuffer commandBuffer) const {
3844 bool skip = false;
3845 skip |= StateTracker::PreCallValidateCmdEndRenderingKHR(commandBuffer);
3846 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
3847 skip |= ValidateZcullScope(commandBuffer);
3848 }
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02003849 return skip;
3850}
3851
3852bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
3853 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003854 const auto cmd = GetRead<bp_state::CommandBuffer>(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01003855
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003856 if (cmd == nullptr) return skip;
3857 auto &render_pass_state = cmd->render_pass_state;
Sam Walls0961ec02020-03-31 16:39:15 +01003858
LawG4b21485c2022-02-28 13:46:48 +00003859 // Does the number of draw calls classified as depth only surpass the vendor limit for a specified vendor
3860 bool depth_only_arm = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
3861 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
3862 bool depth_only_img = render_pass_state.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsIMG &&
3863 render_pass_state.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsIMG;
3864
3865 // Only send the warning when the vendor is enabled and a depth prepass is detected
LawG498ec4502022-04-05 09:08:25 +01003866 bool uses_depth =
3867 (render_pass_state.depthAttachment || render_pass_state.colorAttachment) &&
LawG45507e142022-04-08 09:36:54 +01003868 ((depth_only_arm && VendorCheckEnabled(kBPVendorArm)) || (depth_only_img && VendorCheckEnabled(kBPVendorIMG)));
LawG4b21485c2022-02-28 13:46:48 +00003869
Sam Walls0961ec02020-03-31 16:39:15 +01003870 if (uses_depth) {
3871 skip |= LogPerformanceWarning(
3872 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
LawG4015be1c2022-03-01 10:37:52 +00003873 "%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 +00003874 "renderering architectures; such as those in Arm Mali or PowerVR GPUs. Since they can remove geometry "
3875 "hidden by other opaque geometry. Mali has Forward Pixel Killing (FPK), PowerVR has Hiden Surface "
3876 "Remover (HSR) in which case, using depth pre-passes for hidden surface removal may worsen performance.",
3877 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG));
Sam Walls0961ec02020-03-31 16:39:15 +01003878 }
3879
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003880 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
3881
LawG40da9c3d2022-03-01 09:51:01 +00003882 if ((VendorCheckEnabled(kBPVendorArm) || VendorCheckEnabled(kBPVendorIMG)) && rp) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003883 // If we use an attachment on-tile, we should access it in some way. Otherwise,
3884 // it is redundant to have it be part of the render pass.
3885 // Only consider it redundant if it will actually consume bandwidth, i.e.
3886 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
3887 // as is using pure input attachments.
3888 // CLEAR -> STORE might be considered a "useful" thing to do, but
3889 // the optimal thing to do is to defer the clear until you're actually
3890 // going to render to the image.
3891
3892 uint32_t num_attachments = rp->createInfo.attachmentCount;
3893 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02003894 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
3895 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003896 continue;
3897 }
3898
3899 auto& attachment = rp->createInfo.pAttachments[i];
3900
3901 VkImageAspectFlags bandwidth_aspects = 0;
3902
3903 if (!FormatIsStencilOnly(attachment.format) &&
3904 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3905 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3906 if (FormatHasDepth(attachment.format)) {
3907 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
3908 } else {
3909 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
3910 }
3911 }
3912
3913 if (FormatHasStencil(attachment.format) &&
3914 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
3915 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
3916 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
3917 }
3918
3919 if (!bandwidth_aspects) {
3920 continue;
3921 }
3922
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003923 auto itr = std::find_if(render_pass_state.touchesAttachments.begin(), render_pass_state.touchesAttachments.end(),
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003924 [i](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == i; });
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003925 uint32_t untouched_aspects = bandwidth_aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06003926 if (itr != render_pass_state.touchesAttachments.end()) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003927 untouched_aspects &= ~itr->aspects;
3928 }
3929
3930 if (untouched_aspects) {
3931 skip |= LogPerformanceWarning(
3932 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
LawG4015be1c2022-03-01 10:37:52 +00003933 "%s %s: Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003934 "was never accessed by a pipeline or clear command. "
LawG40da9c3d2022-03-01 09:51:01 +00003935 "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 +00003936 "render pass if the attachments are not intended to be accessed.",
LawG40da9c3d2022-03-01 09:51:01 +00003937 VendorSpecificTag(kBPVendorArm), VendorSpecificTag(kBPVendorIMG), i, attachment.format, untouched_aspects);
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02003938 }
3939 }
3940 }
3941
Sam Walls0961ec02020-03-31 16:39:15 +01003942 return skip;
3943}
3944
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003945void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003946 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3947 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003948}
3949
3950void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003951 const auto cb_node = GetWrite<bp_state::CommandBuffer>(commandBuffer);
3952 ValidateBoundDescriptorSets(*cb_node, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003953}
3954
Camden Stocker9c051442019-11-06 14:28:43 -08003955bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
3956 const char* api_name) const {
3957 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07003958 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08003959
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003960 if (bp_pd_state) {
3961 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
3962 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
3963 "Potential problem with calling %s() without first retrieving properties from "
3964 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
3965 api_name);
3966 }
Camden Stocker9c051442019-11-06 14:28:43 -08003967 }
3968
3969 return skip;
3970}
3971
Camden83a9c372019-08-14 11:41:38 -06003972bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05003973 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06003974 bool skip = false;
3975
Camden Stocker9c051442019-11-06 14:28:43 -08003976 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06003977
Camden Stocker9c051442019-11-06 14:28:43 -08003978 return skip;
3979}
3980
3981bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
3982 uint32_t planeIndex,
3983 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
3984 bool skip = false;
3985
3986 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
3987
3988 return skip;
3989}
3990
3991bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
3992 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
3993 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
3994 bool skip = false;
3995
3996 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06003997
3998 return skip;
3999}
Camden05de2d42019-08-19 10:23:56 -06004000
4001bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004002 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06004003 bool skip = false;
4004
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004005 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Camden05de2d42019-08-19 10:23:56 -06004006
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004007 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06004008 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06004009 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004010 skip |=
4011 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
4012 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
4013 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06004014 }
Camden05de2d42019-08-19 10:23:56 -06004015
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004016 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
4017 skip |= LogWarning(
4018 device, kVUID_BestPractices_Swapchain_InvalidCount,
4019 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
Nadav Gevaf0808442021-05-21 13:51:25 -04004020 "value (%" PRId32 ") that is greater than the value (%" PRId32 ") that was returned when pSwapchainImages was NULL.",
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06004021 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
4022 }
4023 }
4024
Camden05de2d42019-08-19 10:23:56 -06004025 return skip;
4026}
4027
4028// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004029bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* bp_pd_state,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004030 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004031 const CALL_STATE call_state,
4032 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06004033 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004034 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
4035 if (UNCALLED == call_state) {
4036 skip |= LogWarning(
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004037 bp_pd_state->Handle(), kVUID_Core_DevLimit_MissingQueryCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004038 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
4039 "recommended "
4040 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
4041 caller_name, caller_name);
4042 // Then verify that pCount that is passed in on second call matches what was returned
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004043 } else if (bp_pd_state->queue_family_known_count != requested_queue_family_property_count) {
4044 skip |= LogWarning(bp_pd_state->Handle(), kVUID_Core_DevLimit_CountMismatch,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004045 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
4046 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
4047 ". It is recommended to instead receive all the properties by calling %s with "
4048 "pQueueFamilyPropertyCount that was "
4049 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
Jeremy Gebben383b9a32021-09-08 16:31:33 -06004050 caller_name, requested_queue_family_property_count, bp_pd_state->queue_family_known_count, caller_name,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004051 caller_name);
Camden05de2d42019-08-19 10:23:56 -06004052 }
4053
4054 return skip;
4055}
4056
Jeff Bolz5c801d12019-10-09 10:38:45 -05004057bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
4058 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06004059 bool skip = false;
4060
4061 for (uint32_t i = 0; i < bindInfoCount; i++) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004062 auto as_state = Get<ACCELERATION_STRUCTURE_STATE>(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06004063 if (!as_state->memory_requirements_checked) {
4064 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
4065 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
4066 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004067 skip |= LogWarning(
4068 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06004069 "vkBindAccelerationStructureMemoryNV(): "
4070 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
4071 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
4072 }
4073 }
4074
4075 return skip;
4076}
4077
Camden05de2d42019-08-19 10:23:56 -06004078bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
4079 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004080 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004081 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004082 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004083 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004084 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
4085 "vkGetPhysicalDeviceQueueFamilyProperties()");
4086 }
4087 return false;
Camden05de2d42019-08-19 10:23:56 -06004088}
4089
Mike Schuchardt2df08912020-12-15 16:28:09 -08004090bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
4091 uint32_t* pQueueFamilyPropertyCount,
4092 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004093 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004094 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004095 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004096 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
4097 "vkGetPhysicalDeviceQueueFamilyProperties2()");
4098 }
4099 return false;
Camden05de2d42019-08-19 10:23:56 -06004100}
4101
Jeff Bolz5c801d12019-10-09 10:38:45 -05004102bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08004103 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004104 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004105 if (pQueueFamilyProperties && bp_pd_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004106 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(bp_pd_state.get(), *pQueueFamilyPropertyCount,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07004107 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
4108 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
4109 }
4110 return false;
Camden05de2d42019-08-19 10:23:56 -06004111}
4112
4113bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
4114 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004115 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06004116 if (!pSurfaceFormats) return false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004117 const auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06004118 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06004119 bool skip = false;
4120 if (call_state == UNCALLED) {
4121 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
4122 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004123 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
4124 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
4125 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06004126 } else {
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004127 if (*pSurfaceFormatCount > bp_pd_state->surface_formats_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004128 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
4129 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
4130 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
4131 "when pSurfaceFormatCount was NULL.",
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06004132 *pSurfaceFormatCount, bp_pd_state->surface_formats_count);
Camden05de2d42019-08-19 10:23:56 -06004133 }
4134 }
4135 return skip;
4136}
Camden Stocker23cc47d2019-09-03 14:53:57 -06004137
4138bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05004139 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004140 bool skip = false;
4141
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004142 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4143 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06004144 // 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 -07004145 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004146 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
4147 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07004148 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06004149 // 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 -07004150 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
4151 const auto& image_bind = bind_info.pImageBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004152 auto image_state = Get<IMAGE_STATE>(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004153 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004154 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004155 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004156 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004157 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4158 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4159 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004160 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004161 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4162 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004163 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004164 }
4165 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004166 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004167 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004168 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004169 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
4170 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004171 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004172 }
4173 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004174 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4175 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004176 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004177 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004178 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004179 }
Jeremy Gebben9f537102021-10-05 16:37:12 -06004180 sparse_images.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004181 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
4182 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
4183 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004184 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004185 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4186 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004187 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004188 }
4189 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004190 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004191 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004192 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004193 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
4194 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004195 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004196 }
4197 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4198 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004199 sparse_images_with_metadata.insert(image_state.get());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004200 }
4201 }
4202 }
4203 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004204 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
4205 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06004206 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004207 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07004208 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
4209 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004210 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06004211 }
4212 }
4213 }
4214
Rodrigo Locatti7ab778d2022-03-09 18:57:15 -03004215 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4216 auto queue_state = Get<QUEUE_STATE>(queue);
4217 if (queue_state && queue_state->queueFamilyProperties.queueFlags != (VK_QUEUE_TRANSFER_BIT | VK_QUEUE_SPARSE_BINDING_BIT)) {
4218 skip |= LogPerformanceWarning(queue, kVUID_BestPractices_QueueBindSparse_NotAsync,
4219 "vkQueueBindSparse() issued on queue %s. All binds should happen on an asynchronous copy "
4220 "queue to hide the OS scheduling and submit costs.",
4221 report_data->FormatHandle(queue).c_str());
4222 }
4223 }
4224
Camden Stocker23cc47d2019-09-03 14:53:57 -06004225 return skip;
4226}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004227
Mark Lobodzinski84101d72020-04-24 09:43:48 -06004228void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
4229 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004230 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07004231 return;
4232 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004233
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004234 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
4235 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
4236 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
4237 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
Nadav Gevaf0808442021-05-21 13:51:25 -04004238 auto image_state = Get<IMAGE_STATE>(bind_info.pImageOpaqueBinds[i].image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004239 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004240 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07004241 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05004242 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
4243 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
4244 image_state->sparse_metadata_bound = true;
4245 }
4246 }
4247 }
4248 }
4249}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004250
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004251bool BestPractices::ClearAttachmentsIsFullClear(const bp_state::CommandBuffer& cmd, uint32_t rectCount,
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004252 const VkClearRect* pRects) const {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004253 if (cmd.createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004254 // We don't know the accurate render area in a secondary,
4255 // so assume we clear the entire frame buffer.
4256 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
4257 return true;
4258 }
4259
4260 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
4261 for (uint32_t i = 0; i < rectCount; i++) {
4262 auto& rect = pRects[i];
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004263 auto& render_area = cmd.activeRenderPassBeginInfo.renderArea;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004264 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
4265 return true;
4266 }
4267 }
4268
4269 return false;
4270}
4271
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004272bool BestPractices::ValidateClearAttachment(const bp_state::CommandBuffer& cmd, uint32_t fb_attachment, uint32_t color_attachment,
4273 VkImageAspectFlags aspects, bool secondary) const {
4274 const RENDER_PASS_STATE* rp = cmd.activeRenderPass.get();
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004275 bool skip = false;
4276
4277 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
4278 return skip;
4279 }
4280
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004281 const auto& rp_state = cmd.render_pass_state;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004282
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004283 auto attachment_itr =
4284 std::find_if(rp_state.touchesAttachments.begin(), rp_state.touchesAttachments.end(),
4285 [fb_attachment](const bp_state::AttachmentInfo& info) { return info.framebufferAttachment == fb_attachment; });
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004286
4287 // Only report aspects which haven't been touched yet.
4288 VkImageAspectFlags new_aspects = aspects;
Jeremy Gebben7c2cd8b2021-08-11 15:40:38 -06004289 if (attachment_itr != rp_state.touchesAttachments.end()) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004290 new_aspects &= ~attachment_itr->aspects;
4291 }
4292
4293 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
sjfricke52defd42022-08-08 16:37:46 +09004294 if (!cmd.has_draw_cmd) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004295 skip |= LogPerformanceWarning(
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004296 cmd.Handle(), kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02004297 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
4298 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004299 report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004300 }
4301
4302 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
4303 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
4304 skip |= LogPerformanceWarning(
4305 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4306 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
4307 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4308 "it is more efficient.",
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004309 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str(), color_attachment);
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004310 }
4311
4312 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4313 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004314 skip |=
4315 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4316 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
4317 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4318 "it is more efficient.",
4319 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004320
4321 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4322 skip |= ValidateZcullScope(cmd.commandBuffer());
4323 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004324 }
4325
4326 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
4327 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004328 skip |=
4329 LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
4330 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
4331 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
4332 "it is more efficient.",
4333 secondary ? "vkCmdExecuteCommands(): " : "", report_data->FormatHandle(cmd.Handle()).c_str());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004334 }
4335
4336 return skip;
4337}
4338
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004339bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06004340 const VkClearAttachment* pAttachments, uint32_t rectCount,
4341 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004342 bool skip = false;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004343 const auto cb_node = GetRead<bp_state::CommandBuffer>(commandBuffer);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004344 if (!cb_node) return skip;
4345
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02004346 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
4347 // Defer checks to ExecuteCommands.
4348 return skip;
4349 }
4350
4351 // Only care about full clears, partial clears might have legitimate uses.
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004352 const bool is_full_clear = ClearAttachmentsIsFullClear(*cb_node, rectCount, pRects);
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004353
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004354 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
4355 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06004356 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004357 if (rp) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004358 if (rp->use_dynamic_rendering || rp->use_dynamic_rendering_inherited) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004359 const auto pColorAttachments = rp->dynamic_rendering_begin_rendering_info.pColorAttachments;
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004360
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004361 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4362 for (uint32_t i = 0; i < attachmentCount; i++) {
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004363 const auto& attachment = pAttachments[i];
4364 if (attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004365 skip |= ValidateZcullScope(commandBuffer);
4366 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004367 if ((attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) && attachment.colorAttachment != VK_ATTACHMENT_UNUSED) {
4368 const auto& color_attachment = pColorAttachments[attachment.colorAttachment];
4369 if (color_attachment.imageView) {
4370 auto image_view_state = Get<IMAGE_VIEW_STATE>(color_attachment.imageView);
4371 const VkFormat format = image_view_state->create_info.format;
4372 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4373 }
4374 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004375 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004376 }
4377
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004378 if (is_full_clear) {
4379 // TODO: Implement ValidateClearAttachment for dynamic rendering
4380 }
4381
4382 } else {
4383 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
4384
4385 if (is_full_clear) {
4386 for (uint32_t i = 0; i < attachmentCount; i++) {
4387 const auto& attachment = pAttachments[i];
4388
4389 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4390 uint32_t color_attachment = attachment.colorAttachment;
4391 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
4392 skip |= ValidateClearAttachment(*cb_node, fb_attachment, color_attachment, attachment.aspectMask, false);
4393 }
4394
4395 if (subpass.pDepthStencilAttachment &&
4396 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
4397 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
4398 skip |= ValidateClearAttachment(*cb_node, fb_attachment, VK_ATTACHMENT_UNUSED, attachment.aspectMask, false);
4399 }
4400 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004401 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004402 if (VendorCheckEnabled(kBPVendorNVIDIA) && rp->createInfo.pAttachments) {
4403 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; ++attachment_idx) {
4404 const auto& attachment = pAttachments[attachment_idx];
4405
4406 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
4407 const uint32_t fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
4408 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
4409 const VkFormat format = rp->createInfo.pAttachments[fb_attachment].format;
4410 skip |= ValidateClearColor(commandBuffer, format, attachment.clearValue.color);
4411 }
4412 }
4413 }
4414 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00004415 }
4416 }
4417
Nadav Gevaf0808442021-05-21 13:51:25 -04004418 if (VendorCheckEnabled(kBPVendorAMD)) {
4419 for (uint32_t attachment_idx = 0; attachment_idx < attachmentCount; attachment_idx++) {
4420 if (pAttachments[attachment_idx].aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) {
4421 bool black_check = false;
4422 black_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 0.0f;
4423 black_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 0.0f;
4424 black_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 0.0f;
4425 black_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4426 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4427
4428 bool white_check = false;
4429 white_check |= pAttachments[attachment_idx].clearValue.color.float32[0] != 1.0f;
4430 white_check |= pAttachments[attachment_idx].clearValue.color.float32[1] != 1.0f;
4431 white_check |= pAttachments[attachment_idx].clearValue.color.float32[2] != 1.0f;
4432 white_check |= pAttachments[attachment_idx].clearValue.color.float32[3] != 0.0f &&
4433 pAttachments[attachment_idx].clearValue.color.float32[3] != 1.0f;
4434
4435 if (black_check && white_check) {
4436 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4437 "%s Performance warning: vkCmdClearAttachments() clear value for color attachment %" PRId32 " is not a fast clear value."
4438 "Consider changing to one of the following:"
4439 "RGBA(0, 0, 0, 0) "
4440 "RGBA(0, 0, 0, 1) "
4441 "RGBA(1, 1, 1, 0) "
4442 "RGBA(1, 1, 1, 1)",
4443 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4444 }
4445 } else {
4446 if ((pAttachments[attachment_idx].clearValue.depthStencil.depth != 0 &&
4447 pAttachments[attachment_idx].clearValue.depthStencil.depth != 1) &&
4448 pAttachments[attachment_idx].clearValue.depthStencil.stencil != 0) {
4449 skip |= LogPerformanceWarning(device, kVUID_BestPractices_ClearAttachment_FastClearValues,
4450 "%s Performance warning: vkCmdClearAttachments() clear value for depth/stencil "
4451 "attachment %" PRId32 " is not a fast clear value."
4452 "Consider changing to one of the following:"
4453 "D=0.0f, S=0"
4454 "D=1.0f, S=0",
4455 VendorSpecificTag(kBPVendorAMD), attachment_idx);
4456 }
4457 }
4458 }
4459 }
4460
Camden Stockerf55721f2019-09-09 11:04:49 -06004461 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07004462}
Attilio Provenzano02859b22020-02-27 14:17:28 +00004463
4464bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4465 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4466 const VkImageResolve* pRegions) const {
4467 bool skip = false;
4468
4469 skip |= VendorCheckEnabled(kBPVendorArm) &&
4470 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
4471 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
4472 "This is a very slow and extremely bandwidth intensive path. "
4473 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4474 VendorSpecificTag(kBPVendorArm));
4475
4476 return skip;
4477}
4478
Jeff Leger178b1e52020-10-05 12:22:23 -04004479bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4480 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
4481 bool skip = false;
4482
4483 skip |= VendorCheckEnabled(kBPVendorArm) &&
4484 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
4485 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
4486 "This is a very slow and extremely bandwidth intensive path. "
4487 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4488 VendorSpecificTag(kBPVendorArm));
4489
4490 return skip;
4491}
4492
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004493bool BestPractices::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
4494 const VkResolveImageInfo2* pResolveImageInfo) const {
4495 bool skip = false;
4496
4497 skip |= VendorCheckEnabled(kBPVendorArm) &&
4498 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2_ResolvingImage,
4499 "%s Attempting to use vkCmdResolveImage2 to resolve a multisampled image. "
4500 "This is a very slow and extremely bandwidth intensive path. "
4501 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
4502 VendorSpecificTag(kBPVendorArm));
4503
4504 return skip;
4505}
4506
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004507void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4508 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4509 const VkImageResolve* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004510 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004511 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004512 auto src = Get<bp_state::Image>(srcImage);
4513 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004514
4515 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004516 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
4517 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004518 }
4519}
4520
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004521void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
4522 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004523 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004524 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004525 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4526 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004527 uint32_t regionCount = pResolveImageInfo->regionCount;
4528
4529 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004530 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
4531 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01004532 }
4533}
4534
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004535void BestPractices::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer,
4536 const VkResolveImageInfo2* pResolveImageInfo) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004537 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004538 auto& funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004539 auto src = Get<bp_state::Image>(pResolveImageInfo->srcImage);
4540 auto dst = Get<bp_state::Image>(pResolveImageInfo->dstImage);
Tony-LunarGd36f5f32022-01-20 11:49:59 -07004541 uint32_t regionCount = pResolveImageInfo->regionCount;
4542
4543 for (uint32_t i = 0; i < regionCount; i++) {
4544 QueueValidateImage(funcs, "vkCmdResolveImage2()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ,
4545 pResolveImageInfo->pRegions[i].srcSubresource);
4546 QueueValidateImage(funcs, "vkCmdResolveImage2()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE,
4547 pResolveImageInfo->pRegions[i].dstSubresource);
4548 }
4549}
4550
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004551void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4552 const VkClearColorValue* pColor, uint32_t rangeCount,
4553 const VkImageSubresourceRange* pRanges) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004554 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004555 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004556 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004557
4558 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004559 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004560 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004561
4562 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4563 RecordClearColor(dst->createInfo.format, *pColor);
4564 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004565}
4566
4567void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4568 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4569 const VkImageSubresourceRange* pRanges) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004570 ValidationStateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount,
4571 pRanges);
4572
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004573 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004574 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004575 auto dst = Get<bp_state::Image>(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004576
4577 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004578 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004579 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004580 for (uint32_t i = 0; i < rangeCount; i++) {
4581 RecordResetZcullDirection(*cb, image, pRanges[i]);
4582 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004583}
4584
4585void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4586 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4587 const VkImageCopy* pRegions) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004588 ValidationStateTracker::PreCallRecordCmdCopyImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout,
4589 regionCount, pRegions);
4590
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004591 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004592 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004593 auto src = Get<bp_state::Image>(srcImage);
4594 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004595
4596 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004597 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
4598 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004599 }
4600}
4601
4602void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4603 VkImageLayout dstImageLayout, uint32_t regionCount,
4604 const VkBufferImageCopy* pRegions) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004605 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004606 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004607 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004608
4609 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004610 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004611 }
4612}
4613
4614void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4615 VkBuffer dstBuffer, uint32_t regionCount, 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 src = Get<bp_state::Image>(srcImage);
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, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004622 }
4623}
4624
4625void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4626 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4627 const VkImageBlit* pRegions, VkFilter filter) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004628 auto cb = GetWrite<bp_state::CommandBuffer>(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01004629 auto &funcs = cb->queue_submit_functions;
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004630 auto src = Get<bp_state::Image>(srcImage);
4631 auto dst = Get<bp_state::Image>(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004632
4633 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02004634 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
4635 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01004636 }
4637}
4638
Attilio Provenzano02859b22020-02-27 14:17:28 +00004639bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
4640 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
4641 bool skip = false;
4642
4643 if (VendorCheckEnabled(kBPVendorArm)) {
4644 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
4645 skip |= LogPerformanceWarning(
4646 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
4647 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
4648 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
4649 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06004650 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00004651 }
4652
4653 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
4654 skip |= LogPerformanceWarning(
4655 device, kVUID_BestPractices_CreateSampler_LodClamping,
4656 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
4657 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
4658 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
4659 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
4660 }
4661
4662 if (pCreateInfo->mipLodBias != 0.0f) {
4663 skip |=
4664 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
4665 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
4666 "descriptors being created and may cause reduced performance.",
4667 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
4668 }
4669
4670 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4671 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
4672 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
4673 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
4674 skip |= LogPerformanceWarning(
4675 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
4676 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
4677 "This will lead to less efficient descriptors being created and may cause reduced performance. "
4678 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
4679 VendorSpecificTag(kBPVendorArm));
4680 }
4681
4682 if (pCreateInfo->unnormalizedCoordinates) {
4683 skip |= LogPerformanceWarning(
4684 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
4685 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
4686 "descriptors being created and may cause reduced performance.",
4687 VendorSpecificTag(kBPVendorArm));
4688 }
4689
4690 if (pCreateInfo->anisotropyEnable) {
4691 skip |= LogPerformanceWarning(
4692 device, kVUID_BestPractices_CreateSampler_Anisotropy,
4693 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
4694 "and may cause reduced performance.",
4695 VendorSpecificTag(kBPVendorArm));
4696 }
4697 }
4698
4699 return skip;
4700}
Sam Walls8e77e4f2020-03-16 20:47:40 +00004701
Nadav Gevaf0808442021-05-21 13:51:25 -04004702void BestPractices::PreCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
4703 const VkGraphicsPipelineCreateInfo* pCreateInfos,
4704 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
4705 void* cgpl_state) {
4706 ValidationStateTracker::PreCallRecordCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator,
4707 pPipelines);
4708 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004709 num_pso_ += createInfoCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004710}
4711
4712bool BestPractices::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount,
4713 const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount,
4714 const VkCopyDescriptorSet* pDescriptorCopies) const {
4715 bool skip = false;
4716 if (VendorCheckEnabled(kBPVendorAMD)) {
4717 if (descriptorCopyCount > 0) {
4718 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_AvoidCopyingDescriptors,
4719 "%s Performance warning: copying descriptor sets is not recommended",
4720 VendorSpecificTag(kBPVendorAMD));
4721 }
4722 }
4723
4724 return skip;
4725}
4726
4727bool BestPractices::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device,
4728 const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
4729 const VkAllocationCallbacks* pAllocator,
4730 VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate) const {
4731 bool skip = false;
4732 if (VendorCheckEnabled(kBPVendorAMD)) {
4733 skip |= LogPerformanceWarning(device, kVUID_BestPractices_UpdateDescriptors_PreferNonTemplate,
4734 "%s Performance warning: using DescriptorSetWithTemplate is not recommended. Prefer using "
4735 "vkUpdateDescriptorSet instead",
4736 VendorSpecificTag(kBPVendorAMD));
4737 }
4738
4739 return skip;
4740}
4741
4742bool BestPractices::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
4743 const VkClearColorValue* pColor, uint32_t rangeCount,
4744 const VkImageSubresourceRange* pRanges) const {
4745 bool skip = false;
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004746
4747 auto dst = Get<bp_state::Image>(image);
4748
Nadav Gevaf0808442021-05-21 13:51:25 -04004749 if (VendorCheckEnabled(kBPVendorAMD)) {
sfricke-samsungef15e482022-01-26 11:32:49 -08004750 skip |= LogPerformanceWarning(
4751 device, kVUID_BestPractices_ClearAttachment_ClearImage,
Nadav Gevaf0808442021-05-21 13:51:25 -04004752 "%s Performance warning: using vkCmdClearColorImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4753 "vkCmdClearAttachments instead",
4754 VendorSpecificTag(kBPVendorAMD));
4755 }
Rodrigo Locattie4c08a02022-04-04 18:12:18 -03004756 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4757 skip |= ValidateClearColor(commandBuffer, dst->createInfo.format, *pColor);
4758 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004759
4760 return skip;
4761}
4762
4763bool BestPractices::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
4764 VkImageLayout imageLayout,
4765 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
4766 const VkImageSubresourceRange* pRanges) const {
4767 bool skip = false;
4768 if (VendorCheckEnabled(kBPVendorAMD)) {
4769 skip |= LogPerformanceWarning(
4770 device, kVUID_BestPractices_ClearAttachment_ClearImage,
4771 "%s Performance warning: using vkCmdClearDepthStencilImage is not recommended. Prefer using LOAD_OP_CLEAR or "
4772 "vkCmdClearAttachments instead",
4773 VendorSpecificTag(kBPVendorAMD));
4774 }
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004775 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4776 for (uint32_t i = 0; i < rangeCount; i++) {
4777 skip |= ValidateZcull(commandBuffer, image, pRanges[i]);
4778 }
4779 }
Nadav Gevaf0808442021-05-21 13:51:25 -04004780
4781 return skip;
4782}
4783
4784bool BestPractices::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo,
4785 const VkAllocationCallbacks* pAllocator,
4786 VkPipelineLayout* pPipelineLayout) const {
4787 bool skip = false;
4788 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004789 uint32_t descriptor_size = enabled_features.core.robustBufferAccess ? 4 : 2;
Nadav Gevaf0808442021-05-21 13:51:25 -04004790 // Descriptor sets cost 1 DWORD each.
4791 // Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF.
4792 // Dynamic buffers cost 4 DWORDs each when robust buffer access is ON.
4793 // Push constants cost 1 DWORD per 4 bytes in the Push constant range.
4794 uint32_t pipeline_size = pCreateInfo->setLayoutCount; // in DWORDS
4795 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; i++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06004796 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004797 pipeline_size += descriptor_set_layout_state->GetDynamicDescriptorCount() * descriptor_size;
Nadav Gevaf0808442021-05-21 13:51:25 -04004798 }
4799
4800 for (uint32_t i = 0; i < pCreateInfo->pushConstantRangeCount; i++) {
4801 pipeline_size += pCreateInfo->pPushConstantRanges[i].size / 4;
4802 }
4803
4804 if (pipeline_size > kPipelineLayoutSizeWarningLimitAMD) {
4805 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelinesLayout_KeepLayoutSmall,
4806 "%s Performance warning: pipeline layout size is too large. Prefer smaller pipeline layouts."
4807 "Descriptor sets cost 1 DWORD each. "
4808 "Dynamic buffers cost 2 DWORDs each when robust buffer access is OFF. "
4809 "Dynamic buffers cost 4 DWORDs each when robust buffer access is ON. "
4810 "Push constants cost 1 DWORD per 4 bytes in the Push constant range. ",
4811 VendorSpecificTag(kBPVendorAMD));
4812 }
4813 }
4814
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004815 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4816 bool has_separate_sampler = false;
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004817 size_t fast_space_usage = 0;
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004818
4819 for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) {
4820 auto descriptor_set_layout_state = Get<cvdescriptorset::DescriptorSetLayout>(pCreateInfo->pSetLayouts[i]);
4821 for (const auto& binding : descriptor_set_layout_state->GetBindings()) {
4822 if (binding.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) {
4823 has_separate_sampler = true;
4824 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004825
4826 if ((descriptor_set_layout_state->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) == 0U) {
4827 size_t descriptor_type_size = 0;
4828
4829 switch (binding.descriptorType) {
4830 case VK_DESCRIPTOR_TYPE_SAMPLER:
4831 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
4832 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
4833 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
4834 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
4835 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
4836 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
4837 descriptor_type_size = 4;
4838 break;
4839 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
4840 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
4841 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR:
4842 case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV:
4843 descriptor_type_size = 8;
4844 break;
4845 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
4846 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
4847 case VK_DESCRIPTOR_TYPE_MUTABLE_VALVE:
4848 descriptor_type_size = 16;
4849 break;
4850 case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK:
4851 descriptor_type_size = 1;
4852 default:
4853 // Unknown type.
4854 break;
4855 }
4856
4857 size_t descriptor_size = descriptor_type_size * binding.descriptorCount;
4858 fast_space_usage += descriptor_size;
4859 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004860 }
4861 }
4862
4863 if (has_separate_sampler) {
4864 skip |= LogPerformanceWarning(
4865 device, kVUID_BestPractices_CreatePipelineLayout_SeparateSampler,
4866 "%s Consider using combined image samplers instead of separate samplers for marginally better performance.",
4867 VendorSpecificTag(kBPVendorNVIDIA));
4868 }
Rodrigo Locatti12f6ffc2022-03-15 18:29:11 -03004869
4870 if (fast_space_usage > kPipelineLayoutFastDescriptorSpaceNVIDIA) {
4871 skip |= LogPerformanceWarning(
4872 device, kVUID_BestPractices_CreatePipelinesLayout_LargePipelineLayout,
4873 "%s Pipeline layout size is too large, prefer using pipeline-specific descriptor set layouts. "
4874 "Aim for consuming less than %" PRIu32 " bytes to allow fast reads for all non-bindless descriptors. "
4875 "Samplers, textures, texel buffers, and combined image samplers consume 4 bytes each. "
4876 "Uniform buffers and acceleration structures consume 8 bytes. "
4877 "Storage buffers consume 16 bytes. "
4878 "Push constants do not consume space.",
4879 VendorSpecificTag(kBPVendorNVIDIA), kPipelineLayoutFastDescriptorSpaceNVIDIA);
4880 }
Rodrigo Locatti65b33832022-03-15 17:57:30 -03004881 }
4882
Nadav Gevaf0808442021-05-21 13:51:25 -04004883 return skip;
4884}
4885
4886bool BestPractices::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4887 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4888 const VkImageCopy* pRegions) const {
4889 bool skip = false;
4890 std::stringstream src_image_hex;
4891 std::stringstream dst_image_hex;
4892 src_image_hex << "0x" << std::hex << HandleToUint64(srcImage);
4893 dst_image_hex << "0x" << std::hex << HandleToUint64(dstImage);
4894
4895 if (VendorCheckEnabled(kBPVendorAMD)) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004896 auto src_state = Get<IMAGE_STATE>(srcImage);
4897 auto dst_state = Get<IMAGE_STATE>(dstImage);
Nadav Gevaf0808442021-05-21 13:51:25 -04004898
4899 if (src_state && dst_state) {
4900 VkImageTiling src_Tiling = src_state->createInfo.tiling;
4901 VkImageTiling dst_Tiling = dst_state->createInfo.tiling;
4902 if (src_Tiling != dst_Tiling && (src_Tiling == VK_IMAGE_TILING_LINEAR || dst_Tiling == VK_IMAGE_TILING_LINEAR)) {
4903 skip |=
4904 LogPerformanceWarning(device, kVUID_BestPractices_vkImage_AvoidImageToImageCopy,
4905 "%s Performance warning: image %s and image %s have differing tilings. Use buffer to "
4906 "image (vkCmdCopyImageToBuffer) "
4907 "and image to buffer (vkCmdCopyBufferToImage) copies instead of image to image "
4908 "copies when converting between linear and optimal images",
4909 VendorSpecificTag(kBPVendorAMD), src_image_hex.str().c_str(), dst_image_hex.str().c_str());
4910 }
4911 }
4912 }
4913
4914 return skip;
4915}
4916
4917bool BestPractices::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
4918 VkPipeline pipeline) const {
4919 bool skip = false;
4920
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004921 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
4922
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004923 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004924 if (IsPipelineUsedInFrame(pipeline)) {
Nadav Gevaf0808442021-05-21 13:51:25 -04004925 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Pipeline_SortAndBind,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004926 "%s %s Performance warning: Pipeline %s was bound twice in the frame. "
4927 "Keep pipeline state changes to a minimum, for example, by sorting draw calls by pipeline.",
4928 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA),
4929 report_data->FormatHandle(pipeline).c_str());
Nadav Gevaf0808442021-05-21 13:51:25 -04004930 }
4931 }
Rodrigo Locattia5eaf6e2022-04-01 18:05:23 -03004932 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
4933 const auto& tgm = cb->nv.tess_geometry_mesh;
4934 if (tgm.num_switches >= kNumBindPipelineTessGeometryMeshSwitchesThresholdNVIDIA && !tgm.threshold_signaled) {
4935 LogPerformanceWarning(commandBuffer, kVUID_BestPractices_BindPipeline_SwitchTessGeometryMesh,
4936 "%s Avoid switching between pipelines with and without tessellation, geometry, task, "
4937 "and/or mesh shaders. Group draw calls using these shader stages together.",
4938 VendorSpecificTag(kBPVendorNVIDIA));
4939 // Do not set 'skip' so the number of switches gets properly counted after the message.
4940 }
4941 }
4942
Nadav Gevaf0808442021-05-21 13:51:25 -04004943 return skip;
4944}
4945
4946void BestPractices::ManualPostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
4947 VkFence fence, VkResult result) {
4948 // AMD best practice
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004949 num_queue_submissions_ += submitCount;
Nadav Gevaf0808442021-05-21 13:51:25 -04004950}
4951
4952bool BestPractices::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo) const {
4953 bool skip = false;
4954
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004955 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004956 auto num = num_queue_submissions_.load();
4957 if (num > kNumberOfSubmissionWarningLimitAMD) {
4958 skip |= LogPerformanceWarning(device, kVUID_BestPractices_Submission_ReduceNumberOfSubmissions,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004959 "%s %s Performance warning: command buffers submitted %" PRId32
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004960 " times this frame. Submitting command buffers has a CPU "
4961 "and GPU overhead. Submit fewer times to incur less overhead.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03004962 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA), num);
Nadav Gevaf0808442021-05-21 13:51:25 -04004963 }
4964 }
4965
4966 return skip;
4967}
4968
4969void BestPractices::PostCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4970 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4971 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
4972 uint32_t bufferMemoryBarrierCount,
4973 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
4974 uint32_t imageMemoryBarrierCount,
4975 const VkImageMemoryBarrier* pImageMemoryBarriers) {
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004976 ValidationStateTracker::PostCallRecordCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags,
4977 memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
4978 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
4979
Jeremy Gebben20da7a12022-02-25 14:07:46 -07004980 num_barriers_objects_ += (memoryBarrierCount + imageMemoryBarrierCount + bufferMemoryBarrierCount);
Rodrigo Locatti0b16cda2022-04-01 17:59:53 -03004981
4982 for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) {
4983 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pImageMemoryBarriers[i]);
4984 }
4985}
4986
4987void BestPractices::PostCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4988 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2(commandBuffer, pDependencyInfo);
4989
4990 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
4991 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
4992 }
4993}
4994
4995void BestPractices::PostCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4996 ValidationStateTracker::PostCallRecordCmdPipelineBarrier2KHR(commandBuffer, pDependencyInfo);
4997
4998 for (uint32_t i = 0; i < pDependencyInfo->imageMemoryBarrierCount; ++i) {
4999 RecordCmdPipelineBarrierImageBarrier(commandBuffer, pDependencyInfo->pImageMemoryBarriers[i]);
5000 }
5001}
5002
5003template <typename ImageMemoryBarrier>
5004void BestPractices::RecordCmdPipelineBarrierImageBarrier(VkCommandBuffer commandBuffer, const ImageMemoryBarrier& barrier) {
5005 auto cb = Get<bp_state::CommandBuffer>(commandBuffer);
5006 assert(cb);
5007
5008 if (VendorCheckEnabled(kBPVendorNVIDIA)) {
5009 RecordResetZcullDirection(*cb, barrier.image, barrier.subresourceRange);
5010 }
Nadav Gevaf0808442021-05-21 13:51:25 -04005011}
5012
5013bool BestPractices::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo,
5014 const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore) const {
5015 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005016 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005017 if (Count<SEMAPHORE_STATE>() > kMaxRecommendedSemaphoreObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005018 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfSemaphores,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005019 "%s %s Performance warning: High number of vkSemaphore objects created. "
Nadav Gevaf0808442021-05-21 13:51:25 -04005020 "Minimize the amount of queue synchronization that is used. "
5021 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005022 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005023 }
5024 }
5025
5026 return skip;
5027}
5028
5029bool BestPractices::PreCallValidateCreateFence(VkDevice device, const VkFenceCreateInfo* pCreateInfo,
5030 const VkAllocationCallbacks* pAllocator, VkFence* pFence) const {
5031 bool skip = false;
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005032 if (VendorCheckEnabled(kBPVendorAMD) || VendorCheckEnabled(kBPVendorNVIDIA)) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005033 if (Count<FENCE_STATE>() > kMaxRecommendedFenceObjectsSizeAMD) {
Nadav Gevaf0808442021-05-21 13:51:25 -04005034 skip |= LogPerformanceWarning(device, kVUID_BestPractices_SyncObjects_HighNumberOfFences,
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005035 "%s %s Performance warning: High number of VkFence objects created."
Nadav Gevaf0808442021-05-21 13:51:25 -04005036 "Minimize the amount of CPU-GPU synchronization that is used. "
Rodrigo Locatti494e4482022-03-30 16:37:40 -03005037 "Semaphores and fences have overhead. Each fence has a CPU and GPU cost with it.",
5038 VendorSpecificTag(kBPVendorAMD), VendorSpecificTag(kBPVendorNVIDIA));
Nadav Gevaf0808442021-05-21 13:51:25 -04005039 }
5040 }
5041
5042 return skip;
5043}
5044
Sam Walls8e77e4f2020-03-16 20:47:40 +00005045void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
5046
5047bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
5048 // look for a cache hit
5049 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
5050 if (hit != _entries.end()) {
5051 // mark the cache hit as being most recently used
5052 hit->age = iteration++;
5053 return true;
5054 }
5055
5056 // if there's no cache hit, we need to model the entry being inserted into the cache
5057 CacheEntry new_entry = {value, iteration};
5058 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
5059 // if there is still space left in the cache, use the next available slot
5060 *(_entries.begin() + iteration) = new_entry;
5061 } else {
5062 // otherwise replace the least recently used cache entry
5063 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
5064 *lru = new_entry;
5065 }
5066 iteration++;
5067 return false;
5068}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005069
5070bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
5071 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005072 auto swapchain_data = Get<SWAPCHAIN_NODE>(swapchain);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005073 bool skip = false;
5074 if (swapchain_data && swapchain_data->images.size() == 0) {
5075 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
5076 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
5077 "vkGetSwapchainImagesKHR after swapchain creation.");
5078 }
5079 return skip;
5080}
5081
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005082void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
5083 if (no_pointer) {
5084 if (UNCALLED == call_state) {
5085 call_state = QUERY_COUNT;
5086 }
5087 } else { // Save queue family properties
5088 call_state = QUERY_DETAILS;
5089 }
5090}
5091
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005092void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
5093 uint32_t* pQueueFamilyPropertyCount,
5094 VkQueueFamilyProperties* pQueueFamilyProperties) {
5095 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
5096 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005097 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005098 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005099 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
5100 nullptr == pQueueFamilyProperties);
5101 }
5102}
5103
5104void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
5105 uint32_t* pQueueFamilyPropertyCount,
5106 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5107 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
5108 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005109 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005110 if (bp_pd_state) {
5111 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
5112 nullptr == pQueueFamilyProperties);
5113 }
5114}
5115
5116void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
5117 uint32_t* pQueueFamilyPropertyCount,
5118 VkQueueFamilyProperties2* pQueueFamilyProperties) {
5119 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
5120 pQueueFamilyProperties);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005121 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07005122 if (bp_pd_state) {
5123 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
5124 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005125 }
5126}
5127
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005128void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
5129 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005130 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005131 if (bp_pd_state) {
5132 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5133 }
5134}
5135
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005136void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
5137 VkPhysicalDeviceFeatures2* pFeatures) {
5138 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005139 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005140 if (bp_pd_state) {
5141 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5142 }
5143}
5144
Nathaniel Cesariof121d122020-10-08 13:09:46 -06005145void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
5146 VkPhysicalDeviceFeatures2* pFeatures) {
5147 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005148 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005149 if (bp_pd_state) {
5150 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
5151 }
5152}
5153
5154void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
5155 VkSurfaceKHR surface,
5156 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
5157 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005158 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005159 if (bp_pd_state) {
5160 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5161 }
5162}
5163
5164void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
5165 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5166 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005167 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005168 if (bp_pd_state) {
5169 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5170 }
5171}
5172
5173void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
5174 VkSurfaceKHR surface,
5175 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
5176 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005177 auto bp_pd_state = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005178 if (bp_pd_state) {
5179 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
5180 }
5181}
5182
5183void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
5184 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
5185 VkPresentModeKHR* pPresentModes, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005186 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005187 if (bp_pd_data) {
5188 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
5189
5190 if (*pPresentModeCount) {
5191 if (call_state < QUERY_COUNT) {
5192 call_state = QUERY_COUNT;
5193 }
5194 }
5195 if (pPresentModes) {
5196 if (call_state < QUERY_DETAILS) {
5197 call_state = QUERY_DETAILS;
5198 }
5199 }
5200 }
5201}
5202
5203void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
5204 uint32_t* pSurfaceFormatCount,
5205 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005206 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005207 if (bp_pd_data) {
5208 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
5209
5210 if (*pSurfaceFormatCount) {
5211 if (call_state < QUERY_COUNT) {
5212 call_state = QUERY_COUNT;
5213 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005214 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005215 }
5216 if (pSurfaceFormats) {
5217 if (call_state < QUERY_DETAILS) {
5218 call_state = QUERY_DETAILS;
5219 }
5220 }
5221 }
5222}
5223
5224void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
5225 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
5226 uint32_t* pSurfaceFormatCount,
5227 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005228 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005229 if (bp_pd_data) {
5230 if (*pSurfaceFormatCount) {
5231 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
5232 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
5233 }
Jeremy Gebbenc7a834a2021-09-08 18:39:30 -06005234 bp_pd_data->surface_formats_count = *pSurfaceFormatCount;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005235 }
5236 if (pSurfaceFormats) {
5237 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
5238 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
5239 }
5240 }
5241 }
5242}
5243
5244void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
5245 uint32_t* pPropertyCount,
5246 VkDisplayPlanePropertiesKHR* pProperties,
5247 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005248 auto bp_pd_data = Get<bp_state::PhysicalDevice>(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005249 if (bp_pd_data) {
5250 if (*pPropertyCount) {
5251 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
5252 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
5253 }
5254 }
5255 if (pProperties) {
5256 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
5257 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
5258 }
5259 }
5260 }
5261}
5262
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005263void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
5264 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
5265 VkResult result) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005266 auto swapchain_state = Get<bp_state::Swapchain>(swapchain);
Nathaniel Cesario39152e62021-07-02 13:04:16 -06005267 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
5268 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
5269 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06005270 }
5271 }
5272}
5273
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005274void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
5275 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
5276
Jeremy Gebbenb20a8242021-11-05 15:14:43 -06005277 auto queue_state = Get<QUEUE_STATE>(queue);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005278 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02005279 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005280 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
Jeremy Gebben20da7a12022-02-25 14:07:46 -07005281 auto cb = GetWrite<bp_state::CommandBuffer>(submit_info.pCommandBuffers[cb_index]);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005282 for (auto &func : cb->queue_submit_functions) {
Jeremy Gebbene5361dd2021-11-18 14:23:56 -07005283 func(*this, *queue_state, *cb);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005284 }
Rodrigo Locattic789fe82022-07-06 17:42:19 -03005285 cb->num_submits++;
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01005286 }
5287 }
5288}