blob: 0d1cda0245493bea00425a759b194bc456bd4b64 [file] [log] [blame]
Gareth Webbdc6549a2021-06-16 03:52:24 +01001/* Copyright (c) 2015-2021 The Khronos Group Inc.
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
Camdeneaa86ea2019-07-26 11:00:09 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Camden Stocker <camden@lunarg.com>
18 */
19
Mark Lobodzinski57b8ae82020-02-20 16:37:14 -070020#include "best_practices_validation.h"
Camden5b184be2019-08-13 07:50:19 -060021#include "layer_chassis_dispatch.h"
Camden Stocker0a660ce2019-08-27 15:30:40 -060022#include "best_practices_error_enums.h"
Sam Wallsd7ab6db2020-06-19 20:41:54 +010023#include "shader_validation.h"
Jeremy Gebbena3705f42021-01-19 16:47:43 -070024#include "sync_utils.h"
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060025#include "cmd_buffer_state.h"
26#include "device_state.h"
27#include "render_pass_state.h"
Camden5b184be2019-08-13 07:50:19 -060028
29#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000030#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010031#include <memory>
Camden5b184be2019-08-13 07:50:19 -060032
Attilio Provenzano19d6a982020-02-27 12:41:41 +000033struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060034 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000035 std::string name;
36};
37
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070038const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060039 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000040};
41
Hannes Harnisch607d1d92021-07-10 18:44:56 +020042const SpecialUseVUIDs kSpecialUseInstanceVUIDs {
43 kVUID_BestPractices_CreateInstance_SpecialUseExtension_CADSupport,
44 kVUID_BestPractices_CreateInstance_SpecialUseExtension_D3DEmulation,
45 kVUID_BestPractices_CreateInstance_SpecialUseExtension_DevTools,
46 kVUID_BestPractices_CreateInstance_SpecialUseExtension_Debugging,
47 kVUID_BestPractices_CreateInstance_SpecialUseExtension_GLEmulation,
48};
49
50const SpecialUseVUIDs kSpecialUseDeviceVUIDs {
51 kVUID_BestPractices_CreateDevice_SpecialUseExtension_CADSupport,
52 kVUID_BestPractices_CreateDevice_SpecialUseExtension_D3DEmulation,
53 kVUID_BestPractices_CreateDevice_SpecialUseExtension_DevTools,
54 kVUID_BestPractices_CreateDevice_SpecialUseExtension_Debugging,
55 kVUID_BestPractices_CreateDevice_SpecialUseExtension_GLEmulation,
56};
57
Attilio Provenzano19d6a982020-02-27 12:41:41 +000058bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070059 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060060 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000061 return true;
62 }
63 }
64 return false;
65}
66
67const char* VendorSpecificTag(BPVendorFlags vendors) {
68 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070069 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000070
71 auto res = tag_map.find(vendors);
72 if (res == tag_map.end()) {
73 // Build the vendor tag string
74 std::stringstream vendor_tag;
75
76 vendor_tag << "[";
77 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070078 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000079 if (vendors & vendor.first) {
80 if (!first_vendor) {
81 vendor_tag << ", ";
82 }
83 vendor_tag << vendor.second.name;
84 first_vendor = false;
85 }
86 }
87 vendor_tag << "]";
88
89 tag_map[vendors] = vendor_tag.str();
90 res = tag_map.find(vendors);
91 }
92
93 return res->second.c_str();
94}
95
Mark Lobodzinski6167e102020-02-24 17:03:55 -070096const char* DepReasonToString(ExtDeprecationReason reason) {
97 switch (reason) {
98 case kExtPromoted:
99 return "promoted to";
100 break;
101 case kExtObsoleted:
102 return "obsoleted by";
103 break;
104 case kExtDeprecated:
105 return "deprecated by";
106 break;
107 default:
108 return "";
109 break;
110 }
111}
112
113bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
114 const char* vuid) const {
115 bool skip = false;
116 auto dep_info_it = deprecated_extensions.find(extension_name);
117 if (dep_info_it != deprecated_extensions.end()) {
118 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600119 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
120 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700121 skip |=
122 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
123 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600124 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700125 if (dep_info.target.length() == 0) {
126 skip |= LogWarning(instance, vuid,
127 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
128 "without replacement.",
129 api_name, extension_name);
130 } else {
131 skip |= LogWarning(instance, vuid,
132 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
133 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
134 }
135 }
136 }
137 return skip;
138}
139
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200140bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const SpecialUseVUIDs& special_use_vuids) const
141{
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700142 bool skip = false;
143 auto dep_info_it = special_use_extensions.find(extension_name);
144
145 if (dep_info_it != special_use_extensions.end()) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200146 const char* const format = "%s(): Attempting to enable extension %s, but this extension is intended to support %s "
147 "and it is strongly recommended that it be otherwise avoided.";
148 auto& special_uses = dep_info_it->second;
149
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700150 if (special_uses.find("cadsupport") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200151 skip |= LogWarning(instance, special_use_vuids.cadsupport, format, api_name, extension_name,
152 "specialized functionality used by CAD/CAM applications");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700153 }
154 if (special_uses.find("d3demulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200155 skip |= LogWarning(instance, special_use_vuids.d3demulation, format, api_name, extension_name,
156 "D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700157 }
158 if (special_uses.find("devtools") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200159 skip |= LogWarning(instance, special_use_vuids.devtools, format, api_name, extension_name,
160 "developer tools such as capture-replay libraries");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700161 }
162 if (special_uses.find("debugging") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200163 skip |= LogWarning(instance, special_use_vuids.debugging, format, api_name, extension_name,
164 "use by applications when debugging");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700165 }
166 if (special_uses.find("glemulation") != std::string::npos) {
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200167 skip |= LogWarning(instance, special_use_vuids.glemulation, format, api_name, extension_name,
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700168 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200169 "specific to those APIs");
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700170 }
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700171 }
172 return skip;
173}
174
Camden5b184be2019-08-13 07:50:19 -0600175bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500176 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600177 bool skip = false;
178
179 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
180 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800181 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700182 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
183 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600184 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600185 uint32_t specified_version =
186 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
187 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700188 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200189 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseInstanceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600190 }
191
192 return skip;
193}
194
195void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
196 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700197 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100198
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700199 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100200 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700201 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100202 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700203 }
Camden5b184be2019-08-13 07:50:19 -0600204}
205
206bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500207 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600208 bool skip = false;
209
210 // get API version of physical device passed when creating device.
211 VkPhysicalDeviceProperties physical_device_properties{};
212 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500213 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600214
215 // check api versions and warn if instance api Version is higher than version on device.
216 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600217 std::string inst_api_name = StringAPIVersion(instance_api_version);
218 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600219
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700220 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
221 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
222 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600223 }
224
225 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
226 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800227 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700228 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
229 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600230 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700231 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
232 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Hannes Harnisch607d1d92021-07-10 18:44:56 +0200233 skip |= ValidateSpecialUseExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], kSpecialUseDeviceVUIDs);
Camden5b184be2019-08-13 07:50:19 -0600234 }
235
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600236 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
237 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700238 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
239 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600240 }
241
Szilard Papp7d2c7952020-06-22 14:38:13 +0100242 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
243 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
244 skip |= LogPerformanceWarning(
245 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
246 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
247 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
248 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
249 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
250 VendorSpecificTag(kBPVendorArm));
251 }
252
Camden5b184be2019-08-13 07:50:19 -0600253 return skip;
254}
255
256bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500257 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600258 bool skip = false;
259
260 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700261 std::stringstream buffer_hex;
262 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600263
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700264 skip |= LogWarning(
265 device, kVUID_BestPractices_SharingModeExclusive,
266 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
267 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700268 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600269 }
270
271 return skip;
272}
273
274bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500275 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600276 bool skip = false;
277
278 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700279 std::stringstream image_hex;
280 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600281
282 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700283 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
284 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
285 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700286 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600287 }
288
Attilio Provenzano02859b22020-02-27 14:17:28 +0000289 if (VendorCheckEnabled(kBPVendorArm)) {
290 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
291 skip |= LogPerformanceWarning(
292 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
293 "%s vkCreateImage(): Trying to create an image with %u samples. "
294 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
295 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
296 }
297
298 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
299 skip |= LogPerformanceWarning(
300 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
301 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
302 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
303 "and do not need to be backed by physical storage. "
304 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
305 VendorSpecificTag(kBPVendorArm));
306 }
307 }
308
Camden5b184be2019-08-13 07:50:19 -0600309 return skip;
310}
311
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100312void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
313 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
314 ReleaseImageUsageState(image);
315}
316
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200317void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
Tony-LunarG299187b2021-05-28 09:29:12 -0600318 if (VK_NULL_HANDLE != swapchain) {
319 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
320 for (auto& image : chain->images) {
321 if (image.image_state) {
322 ReleaseImageUsageState(image.image_state->image());
323 }
324 }
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200325 }
326 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
327}
328
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100329IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
330 auto itr = imageUsageMap.find(vk_image);
331 if (itr != imageUsageMap.end()) {
332 return &itr->second;
333 } else {
334 auto& state = imageUsageMap[vk_image];
335 IMAGE_STATE* image = GetImageState(vk_image);
336 state.image = image;
337 state.usages.resize(image->createInfo.arrayLayers);
338 for (auto& mips : state.usages) {
339 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
340 }
341 return &state;
342 }
343}
344
345void BestPractices::ReleaseImageUsageState(VkImage image) {
346 auto itr = imageUsageMap.find(image);
347 if (itr != imageUsageMap.end()) {
348 imageUsageMap.erase(itr);
349 }
350}
351
Camden5b184be2019-08-13 07:50:19 -0600352bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500353 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600354 bool skip = false;
355
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600356 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
357 if (bp_pd_state) {
358 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
359 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
360 "vkCreateSwapchainKHR() called before getting surface capabilities from "
361 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
362 }
Camden83a9c372019-08-14 11:41:38 -0600363
Shannon McPherson73e58c82021-03-05 17:14:26 -0700364 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
365 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600366 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
367 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
368 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
369 }
Camden83a9c372019-08-14 11:41:38 -0600370
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600371 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
372 skip |= LogWarning(
373 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
374 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
375 }
Camden83a9c372019-08-14 11:41:38 -0600376 }
377
Camden5b184be2019-08-13 07:50:19 -0600378 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700379 skip |=
380 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600381 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700382 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
383 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600384 }
385
Szilard Papp48a6da32020-06-10 14:41:59 +0100386 if (pCreateInfo->minImageCount == 2) {
387 skip |= LogPerformanceWarning(
388 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
389 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
390 ", which means double buffering is going "
391 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
392 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
393 "3 to use triple buffering to maximize performance in such cases.",
394 pCreateInfo->minImageCount);
395 }
396
Szilard Pappd5f0f812020-06-22 09:01:29 +0100397 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
398 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
399 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
400 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
401 "Presentation modes which are not FIFO will present the latest available frame and discard other "
402 "frame(s) if any.",
403 VendorSpecificTag(kBPVendorArm));
404 }
405
Camden5b184be2019-08-13 07:50:19 -0600406 return skip;
407}
408
409bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
410 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500411 const VkAllocationCallbacks* pAllocator,
412 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600413 bool skip = false;
414
415 for (uint32_t i = 0; i < swapchainCount; i++) {
416 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700417 skip |= LogWarning(
418 device, kVUID_BestPractices_SharingModeExclusive,
419 "Warning: A shared swapchain (index %" PRIu32
420 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
421 "queues (queueFamilyIndexCount of %" PRIu32 ").",
422 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600423 }
424 }
425
426 return skip;
427}
428
429bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500430 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600431 bool skip = false;
432
433 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
434 VkFormat format = pCreateInfo->pAttachments[i].format;
435 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
436 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
437 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700438 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
439 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
440 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
441 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
442 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600443 }
444 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700445 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
446 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
447 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
448 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
449 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600450 }
451 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000452
453 const auto& attachment = pCreateInfo->pAttachments[i];
454 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
455 bool access_requires_memory =
456 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
457
458 if (FormatHasStencil(format)) {
459 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
460 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
461 }
462
463 if (access_requires_memory) {
464 skip |= LogPerformanceWarning(
465 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
466 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
467 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
468 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
469 i, static_cast<uint32_t>(attachment.samples));
470 }
471 }
Camden5b184be2019-08-13 07:50:19 -0600472 }
473
474 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
475 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
476 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
477 }
478
479 return skip;
480}
481
Tony-LunarG767180f2020-04-23 14:03:59 -0600482bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
483 const VkImageView* image_views) const {
484 bool skip = false;
485
486 // Check for non-transient attachments that should be transient and vice versa
487 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200488 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600489 bool attachment_should_be_transient =
490 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
491
492 if (FormatHasStencil(attachment.format)) {
493 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
494 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
495 }
496
497 auto view_state = GetImageViewState(image_views[i]);
498 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200499 const auto& ivci = view_state->create_info;
500 const auto& ici = GetImageState(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600501
502 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
503
504 // The check for an image that should not be transient applies to all GPUs
505 if (!attachment_should_be_transient && image_is_transient) {
506 skip |= LogPerformanceWarning(
507 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
508 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
509 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
510 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
511 i);
512 }
513
514 bool supports_lazy = false;
515 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
516 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
517 supports_lazy = true;
518 }
519 }
520
521 // The check for an image that should be transient only applies to GPUs supporting
522 // lazily allocated memory
523 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
524 skip |= LogPerformanceWarning(
525 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
526 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
527 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
528 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
529 i);
530 }
531 }
532 }
533 return skip;
534}
535
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000536bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
537 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
538 bool skip = false;
539
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000540 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800541 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600542 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000543 }
544
545 return skip;
546}
547
Sam Wallse746d522020-03-16 21:20:23 +0000548bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
549 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
550 bool skip = false;
551 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
552
553 if (!skip) {
554 const auto& pool_handle = pAllocateInfo->descriptorPool;
555 auto iter = descriptor_pool_freed_count.find(pool_handle);
556 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
557 // this warning is specific to Arm
558 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
559 skip |= LogPerformanceWarning(
560 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
561 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
562 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
563 VendorSpecificTag(kBPVendorArm));
564 }
565 }
566
567 return skip;
568}
569
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600570void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
571 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000572 if (result == VK_SUCCESS) {
573 // find the free count for the pool we allocated into
574 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
575 if (iter != descriptor_pool_freed_count.end()) {
576 // we record successful allocations by subtracting the allocation count from the last recorded free count
577 const auto alloc_count = pAllocateInfo->descriptorSetCount;
578 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700579 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000580 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700581 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000582 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700583 }
Sam Wallse746d522020-03-16 21:20:23 +0000584 }
585 }
586}
587
588void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
589 const VkDescriptorSet* pDescriptorSets, VkResult result) {
590 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
591 if (result == VK_SUCCESS) {
592 // we want to track frees because we're interested in suggesting re-use
593 auto iter = descriptor_pool_freed_count.find(descriptorPool);
594 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700595 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000596 } else {
597 iter->second += descriptorSetCount;
598 }
599 }
600}
601
Camden5b184be2019-08-13 07:50:19 -0600602bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500603 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600604 bool skip = false;
605
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500606 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700607 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
608 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600609 }
610
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000611 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
612 skip |= LogPerformanceWarning(
613 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600614 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
615 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000616 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
617 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
618 }
619
Camden83a9c372019-08-14 11:41:38 -0600620 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
621
622 return skip;
623}
624
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600625void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
626 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
627 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700628 if (result != VK_SUCCESS) {
629 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
630 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800631 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700632 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600633 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700634 return;
635 }
636 num_mem_objects++;
637}
Camden Stocker9738af92019-10-16 13:54:03 -0700638
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600639void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
640 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700641 auto error = std::find(error_codes.begin(), error_codes.end(), result);
642 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000643 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
644 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
645
646 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
647 if (common_failure != common_failure_codes.end()) {
648 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
649 } else {
650 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
651 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700652 return;
653 }
654 auto success = std::find(success_codes.begin(), success_codes.end(), result);
655 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600656 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
657 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500658 }
659}
660
Jeff Bolz5c801d12019-10-09 10:38:45 -0500661bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
662 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700663 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600664 bool skip = false;
665
Camden Stocker9738af92019-10-16 13:54:03 -0700666 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600667
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600668 for (const auto& node: mem_info->ObjectBindings()) {
669 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600670 LogObjectList objlist(device);
671 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600672 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600673 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 -0600674 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600675 }
676
Camden5b184be2019-08-13 07:50:19 -0600677 return skip;
678}
679
680void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700681 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600682 if (memory != VK_NULL_HANDLE) {
683 num_mem_objects--;
684 }
685}
686
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000687bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600688 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500689 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600690
sfricke-samsunge2441192019-11-06 14:07:57 -0800691 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700692 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
693 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
694 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600695 }
696
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000697 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
698
699 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
700 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
701 skip |= LogPerformanceWarning(
702 device, kVUID_BestPractices_SmallDedicatedAllocation,
703 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600704 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
705 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000706 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
707 }
708
Camden Stockerb603cc82019-09-03 10:09:02 -0600709 return skip;
710}
711
712bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500713 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600714 bool skip = false;
715 const char* api_name = "BindBufferMemory()";
716
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000717 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600718
719 return skip;
720}
721
722bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500723 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600724 char api_name[64];
725 bool skip = false;
726
727 for (uint32_t i = 0; i < bindInfoCount; i++) {
728 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000729 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600730 }
731
732 return skip;
733}
Camden Stockerb603cc82019-09-03 10:09:02 -0600734
735bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500736 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737 char api_name[64];
738 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600739
Camden Stocker8b798ab2019-09-03 10:33:28 -0600740 for (uint32_t i = 0; i < bindInfoCount; i++) {
741 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000742 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600743 }
744
745 return skip;
746}
747
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000748bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600749 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500750 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600751
sfricke-samsung71bc6572020-04-29 15:49:43 -0700752 if (image_state->disjoint == false) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600753 if (!image_state->memory_requirements_checked[0] && !image_state->external_memory_handle) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700754 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
755 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
756 api_name, report_data->FormatHandle(image).c_str());
757 }
758 } else {
759 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
760 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600761 }
762
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000763 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
764
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600765 if (mem_state->alloc_info.allocationSize == image_state->requirements[0].size &&
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000766 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
767 skip |= LogPerformanceWarning(
768 device, kVUID_BestPractices_SmallDedicatedAllocation,
769 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600770 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
771 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000772 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
773 }
774
775 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
776 // make sure this type is actually used.
777 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
778 // (i.e.most tile - based renderers)
779 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
780 bool supports_lazy = false;
781 uint32_t suggested_type = 0;
782
783 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600784 if ((1u << i) & image_state->requirements[0].memoryTypeBits) {
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000785 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
786 supports_lazy = true;
787 suggested_type = i;
788 break;
789 }
790 }
791 }
792
793 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
794
795 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
796 skip |= LogPerformanceWarning(
797 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600798 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000799 "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 -0600800 "%" PRIu64 " bytes of physical memory.",
Jeremy Gebben6fbf8242021-06-21 09:14:46 -0600801 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements[0].size);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000802 }
803 }
804
Camden Stocker8b798ab2019-09-03 10:33:28 -0600805 return skip;
806}
807
808bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500809 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600810 bool skip = false;
811 const char* api_name = "vkBindImageMemory()";
812
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000813 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600814
815 return skip;
816}
817
818bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500819 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600820 char api_name[64];
821 bool skip = false;
822
823 for (uint32_t i = 0; i < bindInfoCount; i++) {
824 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700825 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600826 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
827 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600828 }
829
830 return skip;
831}
832
833bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500834 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600835 char api_name[64];
836 bool skip = false;
837
838 for (uint32_t i = 0; i < bindInfoCount; i++) {
839 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000840 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600841 }
842
843 return skip;
844}
Camden83a9c372019-08-14 11:41:38 -0600845
Attilio Provenzano02859b22020-02-27 14:17:28 +0000846static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
847 switch (format) {
848 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
849 case VK_FORMAT_R16_SFLOAT:
850 case VK_FORMAT_R16G16_SFLOAT:
851 case VK_FORMAT_R16G16B16_SFLOAT:
852 case VK_FORMAT_R16G16B16A16_SFLOAT:
853 case VK_FORMAT_R32_SFLOAT:
854 case VK_FORMAT_R32G32_SFLOAT:
855 case VK_FORMAT_R32G32B32_SFLOAT:
856 case VK_FORMAT_R32G32B32A32_SFLOAT:
857 return false;
858
859 default:
860 return true;
861 }
862}
863
864bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
865 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
866 bool skip = false;
867
868 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700869 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000870
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700871 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
872 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
873 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000874 return skip;
875 }
876
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700877 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200878 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000879
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200880 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
881 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, create_info->pColorBlendState->attachmentCount);
882
883 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200884 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000885 uint32_t att = subpass.pColorAttachments[j].attachment;
886
887 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
888 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
889 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
890 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
891 "color attachment #%u makes use "
892 "of a format which cannot be blended at full throughput when using MSAA.",
893 VendorSpecificTag(kBPVendorArm), i, j);
894 }
895 }
896 }
897 }
898
899 return skip;
900}
901
Camden5b184be2019-08-13 07:50:19 -0600902bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
903 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600904 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500905 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600906 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
907 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600908 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600909
910 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700911 skip |= LogPerformanceWarning(
912 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
913 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
914 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600915 }
916
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000917 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200918 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000919
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600920 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200921 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600922 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700923 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
924 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600925 count++;
926 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000927 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600928 if (count > kMaxInstancedVertexBuffers) {
929 skip |= LogPerformanceWarning(
930 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
931 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
932 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
933 count, kMaxInstancedVertexBuffers);
934 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000935 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000936
Szilard Pappaaf2da32020-06-22 10:37:35 +0100937 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
938 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200939 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
940 VendorCheckEnabled(kBPVendorArm)) {
941 skip |= LogPerformanceWarning(
942 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
943 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
944 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
945 "efficiency during rasterization. Consider disabling depthBias or increasing either "
946 "depthBiasConstantFactor or depthBiasSlopeFactor.",
947 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100948 }
949
Attilio Provenzano02859b22020-02-27 14:17:28 +0000950 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000951 }
952
Camden5b184be2019-08-13 07:50:19 -0600953 return skip;
954}
955
Hans-Kristian Arntzenb033ab12021-06-16 11:16:59 +0200956void BestPractices::PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator)
957{
958 auto itr = graphicsPipelineCIs.find(pipeline);
959 if (itr != graphicsPipelineCIs.end()) {
960 graphicsPipelineCIs.erase(itr);
961 }
962 ValidationStateTracker::PreCallRecordDestroyPipeline(device, pipeline, pAllocator);
963}
964
Sam Walls0961ec02020-03-31 16:39:15 +0100965void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
966 const VkGraphicsPipelineCreateInfo* pCreateInfos,
967 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
968 VkResult result, void* cgpl_state_data) {
969 for (size_t i = 0; i < count; i++) {
970 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
971 const VkPipeline pipeline_handle = pPipelines[i];
972
973 // record depth stencil state and color blend states for depth pre-pass tracking purposes
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +0200974 GraphicsPipelineCIs& cis = graphicsPipelineCIs[pipeline_handle];
Sam Walls0961ec02020-03-31 16:39:15 +0100975
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200976 auto& create_info = cgpl_state->pCreateInfos[i];
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200977
Jeremy Gebben396d06a2021-08-12 11:03:04 -0600978 if (create_info.pColorBlendState) {
979 cis.colorBlendStateCI.emplace(create_info.pColorBlendState);
980 }
981
982 if (create_info.pDepthStencilState) {
983 cis.depthStencilStateCI.emplace(create_info.pDepthStencilState);
984 }
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200985
986 // Record which frame buffer attachments we should consider to be accessed when a draw call is performed.
987 RENDER_PASS_STATE* rp = GetRenderPassState(create_info.renderPass);
988 auto& subpass = rp->createInfo.pSubpasses[create_info.subpass];
989 cis.accessFramebufferAttachments.clear();
990
991 if (cis.colorBlendStateCI) {
Hans-Kristian Arntzenc2742e72021-07-01 14:31:06 +0200992 // According to spec, pColorBlendState must be ignored if subpass does not have color attachments.
993 uint32_t num_color_attachments = std::min(subpass.colorAttachmentCount, cis.colorBlendStateCI->attachmentCount);
994 for (uint32_t j = 0; j < num_color_attachments; j++) {
Hans-Kristian Arntzen42c0ef52021-06-14 14:46:25 +0200995 if (cis.colorBlendStateCI->pAttachments[j].colorWriteMask != 0) {
996 uint32_t attachment = subpass.pColorAttachments[j].attachment;
997 if (attachment != VK_ATTACHMENT_UNUSED) {
998 cis.accessFramebufferAttachments.push_back({ attachment, VK_IMAGE_ASPECT_COLOR_BIT });
999 }
1000 }
1001 }
1002 }
1003
1004 if (cis.depthStencilStateCI && (cis.depthStencilStateCI->depthTestEnable ||
1005 cis.depthStencilStateCI->depthBoundsTestEnable ||
1006 cis.depthStencilStateCI->stencilTestEnable)) {
1007 uint32_t attachment = subpass.pDepthStencilAttachment ?
1008 subpass.pDepthStencilAttachment->attachment :
1009 VK_ATTACHMENT_UNUSED;
1010 if (attachment != VK_ATTACHMENT_UNUSED) {
1011 VkImageAspectFlags aspects = 0;
1012 if (cis.depthStencilStateCI->depthTestEnable || cis.depthStencilStateCI->depthBoundsTestEnable) {
1013 aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1014 }
1015 if (cis.depthStencilStateCI->stencilTestEnable) {
1016 aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1017 }
1018 cis.accessFramebufferAttachments.push_back({ attachment, aspects });
1019 }
1020 }
Sam Walls0961ec02020-03-31 16:39:15 +01001021 }
1022}
1023
Camden5b184be2019-08-13 07:50:19 -06001024bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
1025 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -06001026 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001027 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -06001028 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
1029 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -06001030
1031 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001032 skip |= LogPerformanceWarning(
1033 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
1034 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
1035 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -06001036 }
1037
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001038 if (VendorCheckEnabled(kBPVendorArm)) {
1039 for (size_t i = 0; i < createInfoCount; i++) {
1040 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
1041 }
1042 }
1043
1044 return skip;
1045}
1046
1047bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
1048 bool skip = false;
1049 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001050 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -07001051 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -08001052 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001053
1054 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -07001055 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001056
1057 uint32_t thread_count = x * y * z;
1058
1059 // Generate a priori warnings about work group sizes.
1060 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
1061 skip |= LogPerformanceWarning(
1062 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
1063 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1064 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1065 "groups with less than %u threads, especially when using barrier() or shared memory.",
1066 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1067 }
1068
1069 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1070 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1071 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1072 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1073 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1074 "%u, %u) is not aligned to %u "
1075 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1076 "leave threads idle on the shader "
1077 "core.",
1078 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1079 kThreadGroupDispatchCountAlignmentArm);
1080 }
1081
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001082 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001083 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001084 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001085 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001086 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001087
1088 unsigned dimensions = 0;
1089 if (x > 1) dimensions++;
1090 if (y > 1) dimensions++;
1091 if (z > 1) dimensions++;
1092 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1093 dimensions = std::max(dimensions, 1u);
1094
1095 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1096 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1097 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1098 bool accesses_2d = false;
1099 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001100 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001101 if (dim < 0) continue;
1102 auto spvdim = spv::Dim(dim);
1103 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1104 }
1105
1106 if (accesses_2d && dimensions < 2) {
1107 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1108 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1109 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1110 "exhibiting poor spatial locality with respect to one or more shader resources.",
1111 VendorSpecificTag(kBPVendorArm), x, y, z);
1112 }
1113
Camden5b184be2019-08-13 07:50:19 -06001114 return skip;
1115}
1116
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001117bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001118 bool skip = false;
1119
1120 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001121 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1122 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001123 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001124 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1125 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001126 }
1127
1128 return skip;
1129}
1130
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001131bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1132 bool skip = false;
1133
1134 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1135 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1136 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1137 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1138 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1139 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1140 }
1141
1142 return skip;
1143}
1144
1145bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1146 bool skip = false;
1147 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1148
1149 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1150 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1151
1152 return skip;
1153}
1154
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001155void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001156 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1157 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1158 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1159 LogPerformanceWarning(
1160 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1161 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1162 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1163 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1164 "convenient opportunity.",
1165 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1166 }
1167 }
1168}
1169
Jeff Bolz5c801d12019-10-09 10:38:45 -05001170bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1171 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001172 bool skip = false;
1173
1174 for (uint32_t submit = 0; submit < submitCount; submit++) {
1175 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1176 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1177 }
1178 }
1179
1180 return skip;
1181}
1182
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001183bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1184 VkFence fence) const {
1185 bool skip = false;
1186
1187 for (uint32_t submit = 0; submit < submitCount; submit++) {
1188 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1189 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1190 }
1191 }
1192
1193 return skip;
1194}
1195
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001196bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1197 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1198 bool skip = false;
1199
1200 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1201 skip |= LogPerformanceWarning(
1202 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1203 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1204 "pool instead.");
1205 }
1206
1207 return skip;
1208}
1209
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001210void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo)
1211{
1212 // Clear state in case we are a secondary command buffer.
1213 auto& state = cbRenderPassState[commandBuffer];
1214 state = {};
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02001215 auto* cb = GetCBState(commandBuffer);
1216 cb->hasDrawCmd = false;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001217 ValidationStateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
1218}
1219
1220void BestPractices::PreCallRecordDestroyCommandPool(VkDevice device, VkCommandPool commandPool,
1221 const VkAllocationCallbacks *pAllocation)
1222{
1223 COMMAND_POOL_STATE* pool = GetCommandPoolState(commandPool);
1224 if (pool) {
1225 for (auto& cb : pool->commandBuffers) {
1226 auto itr = cbRenderPassState.find(cb);
1227 if (itr != cbRenderPassState.end()) {
1228 cbRenderPassState.erase(itr);
1229 }
1230 }
1231 }
1232 ValidationStateTracker::PreCallRecordDestroyCommandPool(device, commandPool, pAllocation);
1233}
1234
1235void BestPractices::PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool,
1236 uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers) {
1237 for (uint32_t i = 0; i < commandBufferCount; i++) {
1238 auto itr = cbRenderPassState.find(pCommandBuffers[i]);
1239 if (itr != cbRenderPassState.end()) {
1240 cbRenderPassState.erase(itr);
1241 }
1242 }
1243 ValidationStateTracker::PreCallRecordFreeCommandBuffers(device, commandPool, commandBufferCount, pCommandBuffers);
1244}
1245
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001246bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1247 const VkCommandBufferBeginInfo* pBeginInfo) const {
1248 bool skip = false;
1249
1250 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1251 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1252 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1253 }
1254
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001255 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1256 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001257 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1258 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1259 VendorSpecificTag(kBPVendorArm));
1260 }
1261
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001262 return skip;
1263}
1264
Jeff Bolz5c801d12019-10-09 10:38:45 -05001265bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001266 bool skip = false;
1267
1268 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1269
1270 return skip;
1271}
1272
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001273bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1274 const VkDependencyInfoKHR* pDependencyInfo) const {
1275 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1276}
1277
Jeff Bolz5c801d12019-10-09 10:38:45 -05001278bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1279 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001280 bool skip = false;
1281
1282 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1283
1284 return skip;
1285}
1286
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001287bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1288 VkPipelineStageFlags2KHR stageMask) const {
1289 bool skip = false;
1290
1291 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1292
1293 return skip;
1294}
1295
Camden5b184be2019-08-13 07:50:19 -06001296bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1297 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1298 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1299 uint32_t bufferMemoryBarrierCount,
1300 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1301 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001302 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001303 bool skip = false;
1304
1305 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1306 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1307
1308 return skip;
1309}
1310
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001311bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1312 const VkDependencyInfoKHR* pDependencyInfos) const {
1313 bool skip = false;
1314 for (uint32_t i = 0; i < eventCount; i++) {
1315 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1316 }
1317
1318 return skip;
1319}
1320
Camden5b184be2019-08-13 07:50:19 -06001321bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1322 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1323 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1324 uint32_t bufferMemoryBarrierCount,
1325 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1326 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001327 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001328 bool skip = false;
1329
1330 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1331 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1332
1333 return skip;
1334}
1335
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001336bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1337 const VkDependencyInfoKHR* pDependencyInfo) const {
1338 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1339}
1340
Camden5b184be2019-08-13 07:50:19 -06001341bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001342 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001343 bool skip = false;
1344
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001345 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1346
1347 return skip;
1348}
1349
1350bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1351 VkQueryPool queryPool, uint32_t query) const {
1352 bool skip = false;
1353
1354 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001355
1356 return skip;
1357}
1358
Sam Walls0961ec02020-03-31 16:39:15 +01001359void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1360 VkPipeline pipeline) {
1361 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1362
1363 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1364 // check for depth/blend state tracking
1365 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1366 if (gp_cis != graphicsPipelineCIs.end()) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001367 auto& render_pass_state = cbRenderPassState[commandBuffer];
Sam Walls0961ec02020-03-31 16:39:15 +01001368
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001369 render_pass_state.nextDrawTouchesAttachments = gp_cis->second.accessFramebufferAttachments;
1370 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001371
Jeremy Gebben396d06a2021-08-12 11:03:04 -06001372 const auto& blend_state = gp_cis->second.colorBlendStateCI;
1373 const auto& stencil_state = gp_cis->second.depthStencilStateCI;
Sam Walls0961ec02020-03-31 16:39:15 +01001374
1375 if (blend_state) {
1376 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001377 render_pass_state.depthOnly = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001378 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1379 if (blend_state->pAttachments[i].colorWriteMask != 0) {
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001380 render_pass_state.depthOnly = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001381 }
1382 }
1383 }
1384
1385 // check for depth value usage
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001386 render_pass_state.depthEqualComparison = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001387
1388 if (stencil_state && stencil_state->depthTestEnable) {
1389 switch (stencil_state->depthCompareOp) {
1390 case VK_COMPARE_OP_EQUAL:
1391 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1392 case VK_COMPARE_OP_LESS_OR_EQUAL:
Hans-Kristian Arntzen56232b92021-06-16 14:37:48 +02001393 render_pass_state.depthEqualComparison = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001394 break;
1395 default:
1396 break;
1397 }
1398 }
Sam Walls0961ec02020-03-31 16:39:15 +01001399 }
1400 }
1401}
1402
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02001403static inline bool RenderPassUsesAttachmentAsResolve(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1404 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
1405 const auto& subpass_info = createInfo.pSubpasses[subpass];
1406 if (subpass_info.pResolveAttachments) {
1407 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1408 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1409 }
1410 }
1411 }
1412
1413 return false;
1414}
1415
Attilio Provenzano02859b22020-02-27 14:17:28 +00001416static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1417 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001418 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001419
1420 // If an attachment is ever used as a color attachment,
1421 // resolve attachment or depth stencil attachment,
1422 // it needs to exist on tile at some point.
1423
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001424 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1425 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001426 }
1427
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001428 if (subpass_info.pResolveAttachments) {
1429 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1430 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1431 }
1432 }
1433
1434 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001435 }
1436
1437 return false;
1438}
1439
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001440static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1441 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1442 return false;
1443 }
1444
1445 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001446 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001447
1448 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1449 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1450 return true;
1451 }
1452 }
1453 }
1454
1455 return false;
1456}
1457
Attilio Provenzano02859b22020-02-27 14:17:28 +00001458bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1459 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1460 bool skip = false;
1461
1462 if (!pRenderPassBegin) {
1463 return skip;
1464 }
1465
Gareth Webbdc6549a2021-06-16 03:52:24 +01001466 if (pRenderPassBegin->renderArea.extent.width == 0 || pRenderPassBegin->renderArea.extent.height == 0) {
1467 skip |= LogWarning(device, kVUID_BestPractices_BeginRenderPass_ZeroSizeRenderArea,
1468 "This render pass has a zero-size render area. It cannot write to any attachments, "
1469 "and can only be used for side effects such as layout transitions.");
1470 }
1471
Attilio Provenzano02859b22020-02-27 14:17:28 +00001472 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1473 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001474 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001475 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001476 if (rpabi) {
1477 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1478 }
1479 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001480 // Check if any attachments have LOAD operation on them
1481 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001482 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001483
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001484 bool attachment_has_readback = false;
Hans-Kristian Arntzen4afb59b2021-06-18 12:41:36 +02001485 if (!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001486 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001487 }
1488
1489 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001490 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001491 }
1492
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001493 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001494
1495 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001496 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1497 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001498 }
1499
1500 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001501 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1502 skip |= LogPerformanceWarning(
1503 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1504 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1505 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1506 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1507 VendorSpecificTag(kBPVendorArm), att,
1508 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1509 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1510 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001511 }
1512 }
1513 }
1514
1515 return skip;
1516}
1517
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001518void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1519 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001520 if (view) {
Jeremy Gebbenb4d17012021-07-08 13:18:15 -06001521 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage,
1522 view->normalized_subresource_range);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001523 }
1524}
1525
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001526void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1527 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001528 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001529 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001530
1531 // If we're viewing a 3D slice, ignore base array layer.
1532 // The entire 3D subresource is accessed as one atomic unit.
1533 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1534
1535 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001536 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1537 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1538 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001539
1540 for (uint32_t layer = 0; layer < array_layers; layer++) {
1541 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001542 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1543 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001544 }
1545 }
1546}
1547
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001548void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1549 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001550 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001551 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001552 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1553 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001554
1555 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001556 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001557 }
1558}
1559
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001560void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1561 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001562 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001563 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1564 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001565 return false;
1566 });
1567}
1568
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001569void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001570 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1571 IMAGE_SUBRESOURCE_USAGE_BP usage,
1572 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001573 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001574 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
Jeremy Gebben82e11d52021-07-26 09:19:37 -06001575 !image->IsSwapchainImage()) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001576 LogPerformanceWarning(
1577 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001578 "%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 +02001579 "image was used, it was written to with STORE_OP_STORE. "
1580 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1581 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001582 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001583 } 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 +02001584 LogPerformanceWarning(
1585 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001586 "%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 +02001587 "image was used, it was written to with vkCmdClear*Image(). "
1588 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1589 "tile-based architectures."
1590 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001591 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001592 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1593 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1594 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1595 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001596 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001597 const char *last_cmd = nullptr;
1598 const char *vuid = nullptr;
1599 const char *suggestion = nullptr;
1600
1601 switch (last_usage) {
1602 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1603 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1604 last_cmd = "vkCmdBlitImage";
1605 suggestion =
1606 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1607 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1608 "which avoids the memory roundtrip.";
1609 break;
1610 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1611 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1612 last_cmd = "vkCmdClear*Image";
1613 suggestion =
1614 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1615 "tile-based architectures. "
1616 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1617 break;
1618 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1619 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1620 last_cmd = "vkCmdCopy*Image";
1621 suggestion =
1622 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1623 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1624 "which avoids the memory roundtrip.";
1625 break;
1626 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1627 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1628 last_cmd = "vkCmdResolveImage";
1629 suggestion =
1630 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1631 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1632 "which avoids the memory roundtrip.";
1633 break;
1634 default:
1635 break;
1636 }
1637
1638 LogPerformanceWarning(
1639 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001640 "%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 +01001641 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001642 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001643 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001644}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001645
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001646void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001647 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1648 uint32_t mip_level) {
1649 IMAGE_STATE* image = state->image;
1650 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001651 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001652 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001653 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001654 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001655}
1656
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001657void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001658 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001659 cb->queue_submit_functions_after_render_pass.begin(),
1660 cb->queue_submit_functions_after_render_pass.end());
1661 cb->queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001662}
1663
1664void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1665 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001666 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001667}
1668
1669void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1670 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001671 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001672}
1673
1674void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1675 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001676 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001677}
1678
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001679void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer,
1680 const VkRenderPassBeginInfo* pRenderPassBegin,
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001681 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001682 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02001683 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1684}
1685
1686void BestPractices::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer,
1687 const VkRenderPassBeginInfo* pRenderPassBegin,
1688 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1689 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1690 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1691}
1692
1693void BestPractices::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1694 const VkRenderPassBeginInfo* pRenderPassBegin,
1695 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1696 ValidationStateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1697 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin);
1698}
1699
1700void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001701
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001702 if (!pRenderPassBegin) {
1703 return;
1704 }
1705
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001706 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
1707
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001708 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1709 if (rp_state) {
1710 // Check load ops
1711 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001712 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001713
1714 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1715 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1716 continue;
1717 }
1718
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001719 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001720
1721 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1722 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001723 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001724 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1725 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001726 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001727 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001728 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001729 }
1730
1731 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001732 IMAGE_VIEW_STATE* image_view = nullptr;
1733
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001734 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001735 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1736 if (rpabi) {
1737 image_view = GetImageViewState(rpabi->pAttachments[att]);
1738 }
1739 } else {
1740 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1741 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001742
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001743 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001744 }
1745
1746 // Check store ops
1747 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001748 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001749
1750 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1751 continue;
1752 }
1753
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001754 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001755
1756 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1757 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001758 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001759 }
1760
1761 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001762
1763 IMAGE_VIEW_STATE* image_view = nullptr;
Tony-LunarGb3ab3572021-07-02 09:45:17 -06001764 if (framebuffer->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001765 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1766 if (rpabi) {
1767 image_view = GetImageViewState(rpabi->pAttachments[att]);
1768 }
1769 } else {
1770 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1771 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001772
Hans-Kristian Arntzenf44df192021-06-14 11:42:08 +02001773 QueueValidateImageView(cb->queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001774 }
1775 }
1776}
1777
Attilio Provenzano02859b22020-02-27 14:17:28 +00001778bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1779 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001780 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1781 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001782 return skip;
1783}
1784
1785bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1786 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001787 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001788 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1789 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001790 return skip;
1791}
1792
1793bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001794 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001795 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1796 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001797 return skip;
1798}
1799
Sam Walls0961ec02020-03-31 16:39:15 +01001800void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1801 const VkRenderPassBeginInfo* pRenderPassBegin) {
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001802 // Reset the renderpass state
1803 auto& render_pass_state = cbRenderPassState[commandBuffer];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02001804 render_pass_state.touchesAttachments.clear();
1805 render_pass_state.earlyClearAttachments.clear();
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001806 render_pass_state.numDrawCallsDepthOnly = 0;
1807 render_pass_state.numDrawCallsDepthEqualCompare = 0;
1808 render_pass_state.colorAttachment = false;
1809 render_pass_state.depthAttachment = false;
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001810 render_pass_state.drawTouchAttachments = true;
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001811 // Don't reset state related to pipeline state.
Sam Walls0961ec02020-03-31 16:39:15 +01001812
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02001813 auto* cb = GetCBState(commandBuffer);
1814 cb->hasDrawCmd = false;
1815
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001816 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001817
1818 // track depth / color attachment usage within the renderpass
1819 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1820 // record if depth/color attachments are in use for this renderpass
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001821 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) render_pass_state.depthAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001822
Hans-Kristian Arntzena900f5d2021-06-14 15:09:31 +02001823 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) render_pass_state.colorAttachment = true;
Sam Walls0961ec02020-03-31 16:39:15 +01001824 }
1825}
1826
1827void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1828 VkSubpassContents contents) {
1829 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1830 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1831}
1832
1833void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1834 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1835 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1836 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1837}
1838
1839void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1840 const VkRenderPassBeginInfo* pRenderPassBegin,
1841 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1842 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1843 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1844}
1845
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001846// Generic function to handle validation for all CmdDraw* type functions
1847bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1848 bool skip = false;
1849 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1850 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001851 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1852 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001853 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001854
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001855 // Verify vertex binding
1856 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1857 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001858 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001859 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001860 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1861 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001862 }
1863 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001864
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001865 const auto* pipe = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001866 if (pipe) {
1867 const auto* rp_state = pipe->rp_state.get();
1868 if (rp_state) {
1869 for (uint32_t i = 0; i < rp_state->createInfo.subpassCount; ++i) {
1870 const auto& subpass = rp_state->createInfo.pSubpasses[i];
1871 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(
1872 pipe->graphicsPipelineCI.pDepthStencilState, subpass.pDepthStencilAttachment);
1873 if ((depth_stencil_attachment == VK_ATTACHMENT_UNUSED) && pipe->graphicsPipelineCI.pRasterizationState &&
1874 pipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE) {
1875 skip |= LogWarning(cb_state->commandBuffer(), kVUID_BestPractices_DepthBiasNoAttachment,
1876 "%s: depthBiasEnable == VK_TRUE without a depth-stencil attachment.", caller);
1877 }
1878 }
1879 }
1880 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001881 }
1882 return skip;
1883}
1884
Sam Walls0961ec02020-03-31 16:39:15 +01001885void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001886 auto& render_pass_state = cbRenderPassState[cmd_buffer];
Sam Walls0961ec02020-03-31 16:39:15 +01001887 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001888 RecordCmdDrawTypeArm(render_pass_state, draw_count, caller);
1889 }
1890
1891 if (render_pass_state.drawTouchAttachments) {
1892 for (auto& touch : render_pass_state.nextDrawTouchesAttachments) {
1893 RecordAttachmentAccess(render_pass_state, touch.framebufferAttachment, touch.aspects);
1894 }
1895 // No need to touch the same attachments over and over.
1896 render_pass_state.drawTouchAttachments = false;
Sam Walls0961ec02020-03-31 16:39:15 +01001897 }
1898}
1899
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02001900void BestPractices::RecordCmdDrawTypeArm(RenderPassState& render_pass_state, uint32_t draw_count, const char* caller) {
1901 if (draw_count >= kDepthPrePassMinDrawCountArm) {
1902 if (render_pass_state.depthOnly) render_pass_state.numDrawCallsDepthOnly++;
1903 if (render_pass_state.depthEqualComparison) render_pass_state.numDrawCallsDepthEqualCompare++;
Sam Walls0961ec02020-03-31 16:39:15 +01001904 }
1905}
1906
Camden5b184be2019-08-13 07:50:19 -06001907bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001908 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001909 bool skip = false;
1910
1911 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001912 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1913 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001914 }
Nathaniel Cesariof7b732a2021-06-03 14:08:27 -06001915 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001916
1917 return skip;
1918}
1919
Sam Walls0961ec02020-03-31 16:39:15 +01001920void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1921 uint32_t firstVertex, uint32_t firstInstance) {
1922 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1923 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1924}
1925
Camden5b184be2019-08-13 07:50:19 -06001926bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001927 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001928 bool skip = false;
1929
1930 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001931 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1932 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001933 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001934 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1935
Attilio Provenzano02859b22020-02-27 14:17:28 +00001936 // Check if we reached the limit for small indexed draw calls.
1937 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1938 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1939 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001940 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1941 VendorCheckEnabled(kBPVendorArm)) {
1942 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001943 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001944 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1945 "You can try batching drawcalls or instancing when applicable.",
1946 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1947 }
1948
Sam Walls8e77e4f2020-03-16 20:47:40 +00001949 if (VendorCheckEnabled(kBPVendorArm)) {
1950 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1951 }
1952
1953 return skip;
1954}
1955
1956bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1957 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1958 bool skip = false;
1959
1960 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1961 const auto* cmd_state = GetCBState(commandBuffer);
1962 if (cmd_state == nullptr) return skip;
1963
locke-lunarg1ae57d62020-11-18 10:49:19 -07001964 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001965 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001966
1967 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06001968 const auto& ib_mem_state = *ib_state->MemState();
Sam Walls8e77e4f2020-03-16 20:47:40 +00001969 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1970 const void* ib_mem = ib_mem_state.p_driver_data;
1971 bool primitive_restart_enable = false;
1972
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001973 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1974 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1975 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001976
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001977 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001978 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001979 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001980
1981 // 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 -06001982 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001983 uint32_t scan_stride;
1984 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1985 scan_stride = sizeof(uint8_t);
1986 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1987 scan_stride = sizeof(uint16_t);
1988 } else {
1989 scan_stride = sizeof(uint32_t);
1990 }
1991
1992 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1993 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1994
1995 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1996 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1997 // irrespective of whether or not they're part of the draw call.
1998
1999 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
2000 uint32_t min_index = ~0u;
2001 // start with maximum as 0 and adjust to indices in the buffer
2002 uint32_t max_index = 0u;
2003
2004 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
2005 // for the given index buffer
2006 uint32_t vertex_shade_count = 0;
2007
2008 PostTransformLRUCacheModel post_transform_cache;
2009
2010 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
2011 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
2012 // target architecture.
2013 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
2014 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
2015 post_transform_cache.resize(32);
2016
2017 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2018 uint32_t scan_index;
2019 uint32_t primitive_restart_value;
2020 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2021 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2022 primitive_restart_value = 0xFF;
2023 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2024 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2025 primitive_restart_value = 0xFFFF;
2026 } else {
2027 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2028 primitive_restart_value = 0xFFFFFFFF;
2029 }
2030
2031 max_index = std::max(max_index, scan_index);
2032 min_index = std::min(min_index, scan_index);
2033
2034 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
2035 bool in_cache = post_transform_cache.query_cache(scan_index);
2036 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
2037 if (!in_cache) vertex_shade_count++;
2038 }
2039 }
2040
2041 // 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 +01002042 // 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
2043 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00002044
2045 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07002046 skip |=
2047 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2048 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
2049 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
2050 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
2051 "maximum would be loaded, and possibly shaded, whether or not they are used.",
2052 VendorSpecificTag(kBPVendorArm),
2053 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002054 return skip;
2055 }
2056
2057 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
2058 // 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 +01002059 const size_t refs_per_bucket = 64;
2060 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
2061
2062 const uint32_t n_indices = max_index - min_index + 1;
2063 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
2064 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
2065
2066 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
2067 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00002068
2069 // To avoid using too much memory, we run over the indices again.
2070 // Knowing the size from the last scan allows us to record index usage with bitsets
2071 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
2072 uint32_t scan_index;
2073 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
2074 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
2075 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
2076 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
2077 } else {
2078 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
2079 }
2080 // keep track of the set of all indices used to reference vertices in the draw call
2081 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01002082 size_t bitset_bucket_index = index_offset / refs_per_bucket;
2083 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002084 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
2085 }
2086
2087 uint32_t vertex_reference_count = 0;
2088 for (const auto& bitset : vertex_reference_buckets) {
2089 vertex_reference_count += static_cast<uint32_t>(bitset.count());
2090 }
2091
2092 // 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 -07002093 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002094 // 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 -07002095 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00002096
2097 if (utilization < 0.5f) {
2098 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
2099 "%s The indices which were specified for the draw call only utilise approximately "
2100 "%.02f%% of the bound vertex buffer.",
2101 VendorSpecificTag(kBPVendorArm), utilization);
2102 }
2103
2104 if (cache_hit_rate <= 0.5f) {
2105 skip |=
2106 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
2107 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
2108 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
2109 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
2110 "recently shaded vertices.",
2111 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
2112 }
2113 }
2114
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002115 return skip;
2116}
2117
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002118bool BestPractices::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2119 const VkCommandBuffer* pCommandBuffers) const {
2120 bool skip = false;
2121 const CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2122 for (uint32_t i = 0; i < commandBufferCount; i++) {
2123 auto secondary_itr = cbRenderPassState.find(pCommandBuffers[i]);
2124 if (secondary_itr == cbRenderPassState.end()) {
2125 continue;
2126 }
2127 auto& secondary = secondary_itr->second;
2128 for (auto& clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002129 if (ClearAttachmentsIsFullClear(primary, uint32_t(clear.rects.size()), clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002130 skip |= ValidateClearAttachment(commandBuffer, primary,
2131 clear.framebufferAttachment, clear.colorAttachment,
2132 clear.aspects, true);
2133 }
2134 }
2135 }
2136 return skip;
2137}
2138
2139void BestPractices::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
2140 const VkCommandBuffer* pCommandBuffers) {
2141 CMD_BUFFER_STATE* primary = GetCBState(commandBuffer);
2142 auto& primary_state = cbRenderPassState[commandBuffer];
2143
2144 for (uint32_t i = 0; i < commandBufferCount; i++) {
2145 auto& secondary = cbRenderPassState[pCommandBuffers[i]];
2146
2147 for (auto& early_clear : secondary.earlyClearAttachments) {
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002148 if (ClearAttachmentsIsFullClear(primary, uint32_t(early_clear.rects.size()), early_clear.rects.data())) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002149 RecordAttachmentClearAttachments(primary, primary_state, early_clear.framebufferAttachment,
2150 early_clear.colorAttachment, early_clear.aspects,
Hans-Kristian Arntzenfa8ef9f2021-06-29 12:07:59 +02002151 uint32_t(early_clear.rects.size()), early_clear.rects.data());
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002152 } else {
2153 RecordAttachmentAccess(primary_state, early_clear.framebufferAttachment,
2154 early_clear.aspects);
2155 }
2156 }
2157
2158 for (auto& touch : secondary.touchesAttachments) {
2159 RecordAttachmentAccess(primary_state, touch.framebufferAttachment,
2160 touch.aspects);
2161 }
Hans-Kristian Arntzenc7eb82a2021-06-16 13:57:18 +02002162
2163 primary_state.numDrawCallsDepthEqualCompare += secondary.numDrawCallsDepthEqualCompare;
2164 primary_state.numDrawCallsDepthOnly += secondary.numDrawCallsDepthOnly;
Hans-Kristian Arntzenaf81dca2021-06-18 11:14:28 +02002165
2166 CMD_BUFFER_STATE* second_state = GetCBState(pCommandBuffers[i]);
2167 if (second_state->hasDrawCmd) {
2168 primary->hasDrawCmd = true;
2169 }
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002170 }
2171
2172 ValidationStateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2173}
2174
2175void BestPractices::RecordAttachmentAccess(RenderPassState& state, uint32_t fb_attachment, VkImageAspectFlags aspects) {
2176 // Called when we have a partial clear attachment, or a normal draw call which accesses an attachment.
2177 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002178 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002179 return info.framebufferAttachment == fb_attachment;
2180 });
2181
2182 if (itr != state.touchesAttachments.end()) {
2183 itr->aspects |= aspects;
2184 } else {
2185 state.touchesAttachments.push_back({ fb_attachment, aspects });
2186 }
2187}
2188
2189void BestPractices::RecordAttachmentClearAttachments(CMD_BUFFER_STATE* cmd_state, RenderPassState& state,
2190 uint32_t fb_attachment, uint32_t color_attachment,
2191 VkImageAspectFlags aspects, uint32_t rectCount,
2192 const VkClearRect *pRects) {
2193 // If we observe a full clear before any other access to a frame buffer attachment,
2194 // we have candidate for redundant clear attachments.
2195 auto itr = std::find_if(state.touchesAttachments.begin(), state.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002196 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002197 return info.framebufferAttachment == fb_attachment;
2198 });
2199
2200 uint32_t new_aspects = aspects;
2201 if (itr != state.touchesAttachments.end()) {
2202 new_aspects = aspects & ~itr->aspects;
2203 itr->aspects |= aspects;
2204 } else {
2205 state.touchesAttachments.push_back({ fb_attachment, aspects });
2206 }
2207
2208 if (new_aspects == 0) {
2209 return;
2210 }
2211
2212 if (cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2213 // The first command might be a clear, but might not be the first in the render pass, defer any checks until
2214 // CmdExecuteCommands.
2215 state.earlyClearAttachments.push_back({ fb_attachment, color_attachment, new_aspects,
2216 std::vector<VkClearRect>{pRects, pRects + rectCount} });
2217 }
2218}
2219
2220void BestPractices::PreCallRecordCmdClearAttachments(VkCommandBuffer commandBuffer,
2221 uint32_t attachmentCount, const VkClearAttachment* pClearAttachments,
2222 uint32_t rectCount, const VkClearRect* pRects) {
2223 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2224 RENDER_PASS_STATE* rp_state = cmd_state->activeRenderPass.get();
2225 FRAMEBUFFER_STATE* fb_state = cmd_state->activeFramebuffer.get();
2226 RenderPassState& tracking_state = cbRenderPassState[commandBuffer];
2227 bool is_secondary = cmd_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY;
2228
2229 if (rectCount == 0 || !rp_state) {
2230 return;
2231 }
2232
2233 if (!is_secondary && !fb_state) {
2234 return;
2235 }
2236
2237 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2238 bool full_clear = ClearAttachmentsIsFullClear(cmd_state, rectCount, pRects);
2239
2240 auto& subpass = rp_state->createInfo.pSubpasses[cmd_state->activeSubpass];
2241 for (uint32_t i = 0; i < attachmentCount; i++) {
2242 auto& attachment = pClearAttachments[i];
2243 uint32_t fb_attachment = VK_ATTACHMENT_UNUSED;
2244 VkImageAspectFlags aspects = attachment.aspectMask;
2245
2246 if (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
2247 if (subpass.pDepthStencilAttachment) {
2248 fb_attachment = subpass.pDepthStencilAttachment->attachment;
2249 }
2250 } else if (aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
2251 fb_attachment = subpass.pColorAttachments[attachment.colorAttachment].attachment;
2252 }
2253
2254 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2255 if (full_clear) {
2256 RecordAttachmentClearAttachments(cmd_state, tracking_state,
2257 fb_attachment, attachment.colorAttachment, aspects,
2258 rectCount, pRects);
2259 } else {
2260 RecordAttachmentAccess(tracking_state, fb_attachment, aspects);
2261 }
2262 }
2263 }
2264
2265 ValidationStateTracker::PreCallRecordCmdClearAttachments(commandBuffer, attachmentCount, pClearAttachments,
2266 rectCount, pRects);
2267}
2268
Attilio Provenzano02859b22020-02-27 14:17:28 +00002269void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2270 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2271 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
2272 firstInstance);
2273
2274 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
2275 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
2276 cmd_state->small_indexed_draw_call_count++;
2277 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002278
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002279 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00002280}
2281
Sam Walls0961ec02020-03-31 16:39:15 +01002282void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
2283 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
2284 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
2285 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
2286}
2287
sfricke-samsung681ab7b2020-10-29 01:53:35 -07002288bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2289 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
2290 uint32_t maxDrawCount, uint32_t stride) const {
2291 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
2292
2293 return skip;
2294}
2295
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002296bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
2297 VkDeviceSize offset, VkBuffer countBuffer,
2298 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
2299 uint32_t stride) const {
2300 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06002301
2302 return skip;
2303}
2304
2305bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002306 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002307 bool skip = false;
2308
2309 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002310 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2311 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002312 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002313 }
2314
2315 return skip;
2316}
2317
Sam Walls0961ec02020-03-31 16:39:15 +01002318void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2319 uint32_t count, uint32_t stride) {
2320 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2321 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2322}
2323
Camden5b184be2019-08-13 07:50:19 -06002324bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002325 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002326 bool skip = false;
2327
2328 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002329 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2330 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002331 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002332 }
2333
2334 return skip;
2335}
2336
Sam Walls0961ec02020-03-31 16:39:15 +01002337void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2338 uint32_t count, uint32_t stride) {
2339 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2340 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2341}
2342
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002343void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002344 CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002345
2346 if (cb_state) {
2347 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002348 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002349
2350 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2351 // For bindless scenarios, we should not attempt to track descriptor set state.
2352 // It is highly uncertain which resources are actually bound.
2353 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2354 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2355 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2356 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2357 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2358 continue;
2359 }
2360
2361 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002362 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002363 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002364
2365 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2366 switch (descriptor->GetClass()) {
2367 case cvdescriptorset::DescriptorClass::Image: {
2368 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2369 image_view = image_descriptor->GetImageView();
2370 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002371 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002372 }
2373 case cvdescriptorset::DescriptorClass::ImageSampler: {
2374 if (const auto image_sampler_descriptor =
2375 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2376 image_view = image_sampler_descriptor->GetImageView();
2377 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002378 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002379 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002380 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002381 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002382 }
2383
2384 if (image_view) {
2385 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002386 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2387 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002388 }
2389 }
2390 }
2391 }
2392 }
2393}
2394
2395void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2396 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002397 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002398}
2399
2400void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2401 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002402 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002403}
2404
2405void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2406 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002407 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002408}
2409
Camden5b184be2019-08-13 07:50:19 -06002410bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002411 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002412 bool skip = false;
2413
2414 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002415 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2416 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2417 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2418 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002419 }
2420
2421 return skip;
2422}
Camden83a9c372019-08-14 11:41:38 -06002423
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002424bool BestPractices::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2425 bool skip = false;
2426 skip |= StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
2427 skip |= ValidateCmdEndRenderPass(commandBuffer);
2428 return skip;
2429}
2430
2431bool BestPractices::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo* pSubpassEndInfo) const {
2432 bool skip = false;
2433 skip |= StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
2434 skip |= ValidateCmdEndRenderPass(commandBuffer);
2435 return skip;
2436}
2437
Sam Walls0961ec02020-03-31 16:39:15 +01002438bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2439 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002440 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzend9941a92021-06-18 12:31:30 +02002441 skip |= ValidateCmdEndRenderPass(commandBuffer);
2442 return skip;
2443}
2444
2445bool BestPractices::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2446 bool skip = false;
Sam Walls0961ec02020-03-31 16:39:15 +01002447
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002448 auto render_pass_state = cbRenderPassState.find(commandBuffer);
Sam Walls0961ec02020-03-31 16:39:15 +01002449
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002450 if (render_pass_state == cbRenderPassState.end()) return skip;
Sam Walls0961ec02020-03-31 16:39:15 +01002451
Hans-Kristian Arntzen09aff9d2021-06-14 15:17:02 +02002452 bool uses_depth = (render_pass_state->second.depthAttachment || render_pass_state->second.colorAttachment) &&
2453 render_pass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2454 render_pass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
Sam Walls0961ec02020-03-31 16:39:15 +01002455 if (uses_depth) {
2456 skip |= LogPerformanceWarning(
2457 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2458 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2459 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2460 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2461 VendorSpecificTag(kBPVendorArm));
2462 }
2463
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002464 const CMD_BUFFER_STATE* cmd = GetCBState(commandBuffer);
2465 RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2466
2467 if (VendorCheckEnabled(kBPVendorArm) && rp) {
2468
2469 // If we use an attachment on-tile, we should access it in some way. Otherwise,
2470 // it is redundant to have it be part of the render pass.
2471 // Only consider it redundant if it will actually consume bandwidth, i.e.
2472 // LOAD_OP_LOAD is used or STORE_OP_STORE. CLEAR -> DONT_CARE is benign,
2473 // as is using pure input attachments.
2474 // CLEAR -> STORE might be considered a "useful" thing to do, but
2475 // the optimal thing to do is to defer the clear until you're actually
2476 // going to render to the image.
2477
2478 uint32_t num_attachments = rp->createInfo.attachmentCount;
2479 for (uint32_t i = 0; i < num_attachments; i++) {
Hans-Kristian Arntzen237663c2021-07-01 14:36:40 +02002480 if (!RenderPassUsesAttachmentOnTile(rp->createInfo, i) ||
2481 RenderPassUsesAttachmentAsResolve(rp->createInfo, i)) {
Hans-Kristian Arntzen808bfa12021-06-18 13:52:45 +02002482 continue;
2483 }
2484
2485 auto& attachment = rp->createInfo.pAttachments[i];
2486
2487 VkImageAspectFlags bandwidth_aspects = 0;
2488
2489 if (!FormatIsStencilOnly(attachment.format) &&
2490 (attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2491 attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2492 if (FormatHasDepth(attachment.format)) {
2493 bandwidth_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
2494 } else {
2495 bandwidth_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
2496 }
2497 }
2498
2499 if (FormatHasStencil(attachment.format) &&
2500 (attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
2501 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
2502 bandwidth_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
2503 }
2504
2505 if (!bandwidth_aspects) {
2506 continue;
2507 }
2508
2509 auto itr = std::find_if(render_pass_state->second.touchesAttachments.begin(),
2510 render_pass_state->second.touchesAttachments.end(),
2511 [&](const AttachmentInfo& info) {
2512 return info.framebufferAttachment == i;
2513 });
2514 uint32_t untouched_aspects = bandwidth_aspects;
2515 if (itr != render_pass_state->second.touchesAttachments.end()) {
2516 untouched_aspects &= ~itr->aspects;
2517 }
2518
2519 if (untouched_aspects) {
2520 skip |= LogPerformanceWarning(
2521 device, kVUID_BestPractices_EndRenderPass_RedundantAttachmentOnTile,
2522 "%s Render pass was ended, but attachment #%u (format: %u, untouched aspects 0x%x) "
2523 "was never accessed by a pipeline or clear command. "
2524 "On tile-based architectures, LOAD_OP_LOAD and STORE_OP_STORE consume bandwidth and should not be part of the render pass "
2525 "if the attachments are not intended to be accessed.",
2526 VendorSpecificTag(kBPVendorArm), i, attachment.format, untouched_aspects);
2527 }
2528 }
2529 }
2530
Sam Walls0961ec02020-03-31 16:39:15 +01002531 return skip;
2532}
2533
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002534void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002535 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002536}
2537
2538void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002539 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002540}
2541
Camden Stocker9c051442019-11-06 14:28:43 -08002542bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2543 const char* api_name) const {
2544 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002545 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002546
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002547 if (bp_pd_state) {
2548 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2549 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2550 "Potential problem with calling %s() without first retrieving properties from "
2551 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2552 api_name);
2553 }
Camden Stocker9c051442019-11-06 14:28:43 -08002554 }
2555
2556 return skip;
2557}
2558
Camden83a9c372019-08-14 11:41:38 -06002559bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002560 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002561 bool skip = false;
2562
Camden Stocker9c051442019-11-06 14:28:43 -08002563 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002564
Camden Stocker9c051442019-11-06 14:28:43 -08002565 return skip;
2566}
2567
2568bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2569 uint32_t planeIndex,
2570 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2571 bool skip = false;
2572
2573 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2574
2575 return skip;
2576}
2577
2578bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2579 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2580 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2581 bool skip = false;
2582
2583 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002584
2585 return skip;
2586}
Camden05de2d42019-08-19 10:23:56 -06002587
2588bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002589 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002590 bool skip = false;
2591
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002592 const auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
Camden05de2d42019-08-19 10:23:56 -06002593
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002594 if (swapchain_state && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002595 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario39152e62021-07-02 13:04:16 -06002596 if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002597 skip |=
2598 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2599 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2600 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002601 }
Camden05de2d42019-08-19 10:23:56 -06002602
Nathaniel Cesario4ce98382021-05-28 11:33:20 -06002603 if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) {
2604 skip |= LogWarning(
2605 device, kVUID_BestPractices_Swapchain_InvalidCount,
2606 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImages, and with pSwapchainImageCount set to a "
2607 "value (%d) that is greater than the value (%d) that was returned when pSwapchainImages was NULL.",
2608 *pSwapchainImageCount, swapchain_state->get_swapchain_image_count);
2609 }
2610 }
2611
Camden05de2d42019-08-19 10:23:56 -06002612 return skip;
2613}
2614
2615// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002616bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2617 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002618 const CALL_STATE call_state,
2619 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002620 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002621 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2622 if (UNCALLED == call_state) {
2623 skip |= LogWarning(
2624 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2625 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2626 "recommended "
2627 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2628 caller_name, caller_name);
2629 // Then verify that pCount that is passed in on second call matches what was returned
2630 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2631 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2632 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2633 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2634 ". It is recommended to instead receive all the properties by calling %s with "
2635 "pQueueFamilyPropertyCount that was "
2636 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2637 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2638 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002639 }
2640
2641 return skip;
2642}
2643
Jeff Bolz5c801d12019-10-09 10:38:45 -05002644bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2645 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002646 bool skip = false;
2647
2648 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002649 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002650 if (!as_state->memory_requirements_checked) {
2651 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2652 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2653 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002654 skip |= LogWarning(
2655 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002656 "vkBindAccelerationStructureMemoryNV(): "
2657 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2658 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2659 }
2660 }
2661
2662 return skip;
2663}
2664
Camden05de2d42019-08-19 10:23:56 -06002665bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2666 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002667 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002668 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2669 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002670 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2671 if (pQueueFamilyProperties && bp_pd_state) {
2672 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2673 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2674 "vkGetPhysicalDeviceQueueFamilyProperties()");
2675 }
2676 return false;
Camden05de2d42019-08-19 10:23:56 -06002677}
2678
Mike Schuchardt2df08912020-12-15 16:28:09 -08002679bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2680 uint32_t* pQueueFamilyPropertyCount,
2681 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002682 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2683 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002684 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2685 if (pQueueFamilyProperties && bp_pd_state) {
2686 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2687 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2688 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2689 }
2690 return false;
Camden05de2d42019-08-19 10:23:56 -06002691}
2692
Jeff Bolz5c801d12019-10-09 10:38:45 -05002693bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002694 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002695 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2696 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002697 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2698 if (pQueueFamilyProperties && bp_pd_state) {
2699 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2700 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2701 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2702 }
2703 return false;
Camden05de2d42019-08-19 10:23:56 -06002704}
2705
2706bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2707 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002708 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002709 if (!pSurfaceFormats) return false;
2710 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002711 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2712 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002713 bool skip = false;
2714 if (call_state == UNCALLED) {
2715 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2716 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002717 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2718 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2719 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002720 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002721 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002722 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002723 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2724 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2725 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2726 "when pSurfaceFormatCount was NULL.",
2727 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002728 }
2729 }
2730 return skip;
2731}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002732
2733bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002734 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002735 bool skip = false;
2736
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002737 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2738 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002739 // 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 -07002740 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002741 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2742 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002743 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002744 // 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 -07002745 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2746 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002747 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002748 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002749 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002750 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002751 sparse_images.insert(image_state);
2752 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2753 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2754 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002755 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002756 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2757 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002758 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002759 }
2760 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002761 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002762 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002763 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002764 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2765 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002766 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002767 }
2768 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002769 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2770 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2771 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2772 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002773 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002774 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002775 sparse_images.insert(image_state);
2776 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2777 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2778 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002779 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002780 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2781 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002782 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002783 }
2784 }
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06002785 if (!image_state->memory_requirements_checked[0]) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002786 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002787 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002788 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2789 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002790 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002791 }
2792 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2793 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002794 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002795 }
2796 }
2797 }
2798 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002799 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2800 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002801 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002802 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002803 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2804 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002805 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002806 }
2807 }
2808 }
2809
2810 return skip;
2811}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002812
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002813void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2814 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002815 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002816 return;
2817 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002818
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002819 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2820 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2821 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2822 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2823 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2824 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002825 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002826 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002827 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2828 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2829 image_state->sparse_metadata_bound = true;
2830 }
2831 }
2832 }
2833 }
2834}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002835
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002836bool BestPractices::ClearAttachmentsIsFullClear(const CMD_BUFFER_STATE* cmd,
2837 uint32_t rectCount, const VkClearRect* pRects) const {
2838 if (cmd->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2839 // We don't know the accurate render area in a secondary,
2840 // so assume we clear the entire frame buffer.
2841 // This is resolved in CmdExecuteCommands where we can check if the clear is a full clear.
2842 return true;
2843 }
2844
2845 // If we have a rect which covers the entire frame buffer, we have a LOAD_OP_CLEAR-like command.
2846 for (uint32_t i = 0; i < rectCount; i++) {
2847 auto& rect = pRects[i];
2848 auto& render_area = cmd->activeRenderPassBeginInfo.renderArea;
2849 if (rect.rect.extent.width == render_area.extent.width && rect.rect.extent.height == render_area.extent.height) {
2850 return true;
2851 }
2852 }
2853
2854 return false;
2855}
2856
2857bool BestPractices::ValidateClearAttachment(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE* cmd,
2858 uint32_t fb_attachment, uint32_t color_attachment,
2859 VkImageAspectFlags aspects, bool secondary) const {
2860 const RENDER_PASS_STATE* rp = cmd->activeRenderPass.get();
2861 bool skip = false;
2862
2863 if (!rp || fb_attachment == VK_ATTACHMENT_UNUSED) {
2864 return skip;
2865 }
2866
2867 auto rp_itr = cbRenderPassState.find(commandBuffer);
2868 if (rp_itr == cbRenderPassState.end()) {
2869 return skip;
2870 }
2871
2872 auto attachment_itr = std::find_if(rp_itr->second.touchesAttachments.begin(), rp_itr->second.touchesAttachments.end(),
Hans-Kristian Arntzen8abca1e2021-06-16 13:57:45 +02002873 [&](const AttachmentInfo& info) {
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002874 return info.framebufferAttachment == fb_attachment;
2875 });
2876
2877 // Only report aspects which haven't been touched yet.
2878 VkImageAspectFlags new_aspects = aspects;
2879 if (attachment_itr != rp_itr->second.touchesAttachments.end()) {
2880 new_aspects &= ~attachment_itr->aspects;
2881 }
2882
2883 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
2884 if (!cmd->hasDrawCmd) {
2885 skip |= LogPerformanceWarning(
2886 commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
Hans-Kristian Arntzen4ddd6182021-06-18 12:16:33 +02002887 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds in current render pass. It is recommended you "
2888 "use RenderPass LOAD_OP_CLEAR on attachments instead.",
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002889 report_data->FormatHandle(commandBuffer).c_str());
2890 }
2891
2892 if ((new_aspects & VK_IMAGE_ASPECT_COLOR_BIT) &&
2893 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2894 skip |= LogPerformanceWarning(
2895 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2896 "%svkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2897 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2898 "it is more efficient.",
2899 secondary ? "vkCmdExecuteCommands(): " : "",
2900 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2901 }
2902
2903 if ((new_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
2904 rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2905 skip |= LogPerformanceWarning(
2906 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2907 "%svkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2908 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2909 "it is more efficient.",
2910 secondary ? "vkCmdExecuteCommands(): " : "",
2911 report_data->FormatHandle(commandBuffer).c_str());
2912 }
2913
2914 if ((new_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
2915 rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2916 skip |= LogPerformanceWarning(
2917 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2918 "%svkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2919 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2920 "it is more efficient.",
2921 secondary ? "vkCmdExecuteCommands(): " : "",
2922 report_data->FormatHandle(commandBuffer).c_str());
2923 }
2924
2925 return skip;
2926}
2927
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002928bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002929 const VkClearAttachment* pAttachments, uint32_t rectCount,
2930 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002931 bool skip = false;
2932 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2933 if (!cb_node) return skip;
2934
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002935 if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2936 // Defer checks to ExecuteCommands.
2937 return skip;
2938 }
2939
2940 // Only care about full clears, partial clears might have legitimate uses.
2941 if (!ClearAttachmentsIsFullClear(cb_node, rectCount, pRects)) {
2942 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002943 }
2944
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002945 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2946 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002947 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002948 if (rp) {
2949 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2950
2951 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002952 const auto& attachment = pAttachments[i];
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002953
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002954 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2955 uint32_t color_attachment = attachment.colorAttachment;
2956 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002957 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2958 fb_attachment, color_attachment,
2959 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002960 }
2961
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002962 if (subpass.pDepthStencilAttachment &&
2963 (attachment.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) {
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002964 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
Hans-Kristian Arntzenb6586312021-07-05 11:43:39 +02002965 skip |= ValidateClearAttachment(commandBuffer, cb_node,
2966 fb_attachment, VK_ATTACHMENT_UNUSED,
2967 attachment.aspectMask, false);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002968 }
2969 }
2970 }
2971
Camden Stockerf55721f2019-09-09 11:04:49 -06002972 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002973}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002974
2975bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2976 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2977 const VkImageResolve* pRegions) const {
2978 bool skip = false;
2979
2980 skip |= VendorCheckEnabled(kBPVendorArm) &&
2981 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2982 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2983 "This is a very slow and extremely bandwidth intensive path. "
2984 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2985 VendorSpecificTag(kBPVendorArm));
2986
2987 return skip;
2988}
2989
Jeff Leger178b1e52020-10-05 12:22:23 -04002990bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2991 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2992 bool skip = false;
2993
2994 skip |= VendorCheckEnabled(kBPVendorArm) &&
2995 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2996 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2997 "This is a very slow and extremely bandwidth intensive path. "
2998 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2999 VendorSpecificTag(kBPVendorArm));
3000
3001 return skip;
3002}
3003
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003004void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3005 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3006 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003007 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003008 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003009 auto* src = GetImageUsageState(srcImage);
3010 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003011
3012 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003013 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
3014 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003015 }
3016}
3017
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003018void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
3019 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003020 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003021 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003022 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
3023 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003024 uint32_t regionCount = pResolveImageInfo->regionCount;
3025
3026 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003027 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
3028 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01003029 }
3030}
3031
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003032void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3033 const VkClearColorValue* pColor, uint32_t rangeCount,
3034 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003035 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003036 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003037 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003038
3039 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003040 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003041 }
3042}
3043
3044void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
3045 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
3046 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003047 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003048 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003049 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003050
3051 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003052 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003053 }
3054}
3055
3056void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3057 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3058 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003059 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003060 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003061 auto* src = GetImageUsageState(srcImage);
3062 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003063
3064 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003065 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
3066 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003067 }
3068}
3069
3070void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
3071 VkImageLayout dstImageLayout, uint32_t regionCount,
3072 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003073 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003074 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003075 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003076
3077 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003078 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003079 }
3080}
3081
3082void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3083 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003084 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003085 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003086 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003087
3088 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003089 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003090 }
3091}
3092
3093void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3094 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3095 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003096 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01003097 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01003098 auto* src = GetImageUsageState(srcImage);
3099 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003100
3101 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02003102 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
3103 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01003104 }
3105}
3106
Attilio Provenzano02859b22020-02-27 14:17:28 +00003107bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
3108 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
3109 bool skip = false;
3110
3111 if (VendorCheckEnabled(kBPVendorArm)) {
3112 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
3113 skip |= LogPerformanceWarning(
3114 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
3115 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
3116 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
3117 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06003118 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00003119 }
3120
3121 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
3122 skip |= LogPerformanceWarning(
3123 device, kVUID_BestPractices_CreateSampler_LodClamping,
3124 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
3125 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
3126 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
3127 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
3128 }
3129
3130 if (pCreateInfo->mipLodBias != 0.0f) {
3131 skip |=
3132 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
3133 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
3134 "descriptors being created and may cause reduced performance.",
3135 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
3136 }
3137
3138 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3139 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
3140 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
3141 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
3142 skip |= LogPerformanceWarning(
3143 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
3144 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
3145 "This will lead to less efficient descriptors being created and may cause reduced performance. "
3146 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
3147 VendorSpecificTag(kBPVendorArm));
3148 }
3149
3150 if (pCreateInfo->unnormalizedCoordinates) {
3151 skip |= LogPerformanceWarning(
3152 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
3153 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
3154 "descriptors being created and may cause reduced performance.",
3155 VendorSpecificTag(kBPVendorArm));
3156 }
3157
3158 if (pCreateInfo->anisotropyEnable) {
3159 skip |= LogPerformanceWarning(
3160 device, kVUID_BestPractices_CreateSampler_Anisotropy,
3161 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
3162 "and may cause reduced performance.",
3163 VendorSpecificTag(kBPVendorArm));
3164 }
3165 }
3166
3167 return skip;
3168}
Sam Walls8e77e4f2020-03-16 20:47:40 +00003169
3170void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
3171
3172bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
3173 // look for a cache hit
3174 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
3175 if (hit != _entries.end()) {
3176 // mark the cache hit as being most recently used
3177 hit->age = iteration++;
3178 return true;
3179 }
3180
3181 // if there's no cache hit, we need to model the entry being inserted into the cache
3182 CacheEntry new_entry = {value, iteration};
3183 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
3184 // if there is still space left in the cache, use the next available slot
3185 *(_entries.begin() + iteration) = new_entry;
3186 } else {
3187 // otherwise replace the least recently used cache entry
3188 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
3189 *lru = new_entry;
3190 }
3191 iteration++;
3192 return false;
3193}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003194
3195bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
3196 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
3197 const auto swapchain_data = GetSwapchainState(swapchain);
3198 bool skip = false;
3199 if (swapchain_data && swapchain_data->images.size() == 0) {
3200 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
3201 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
3202 "vkGetSwapchainImagesKHR after swapchain creation.");
3203 }
3204 return skip;
3205}
3206
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003207void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
3208 if (no_pointer) {
3209 if (UNCALLED == call_state) {
3210 call_state = QUERY_COUNT;
3211 }
3212 } else { // Save queue family properties
3213 call_state = QUERY_DETAILS;
3214 }
3215}
3216
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003217void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
3218 uint32_t* pQueueFamilyPropertyCount,
3219 VkQueueFamilyProperties* pQueueFamilyProperties) {
3220 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
3221 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003222 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003223 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07003224 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
3225 nullptr == pQueueFamilyProperties);
3226 }
3227}
3228
3229void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
3230 uint32_t* pQueueFamilyPropertyCount,
3231 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3232 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
3233 pQueueFamilyProperties);
3234 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3235 if (bp_pd_state) {
3236 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
3237 nullptr == pQueueFamilyProperties);
3238 }
3239}
3240
3241void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
3242 uint32_t* pQueueFamilyPropertyCount,
3243 VkQueueFamilyProperties2* pQueueFamilyProperties) {
3244 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
3245 pQueueFamilyProperties);
3246 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3247 if (bp_pd_state) {
3248 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
3249 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003250 }
3251}
3252
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003253void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
3254 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003255 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3256 if (bp_pd_state) {
3257 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3258 }
3259}
3260
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003261void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
3262 VkPhysicalDeviceFeatures2* pFeatures) {
3263 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003264 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3265 if (bp_pd_state) {
3266 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3267 }
3268}
3269
Nathaniel Cesariof121d122020-10-08 13:09:46 -06003270void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
3271 VkPhysicalDeviceFeatures2* pFeatures) {
3272 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003273 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3274 if (bp_pd_state) {
3275 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
3276 }
3277}
3278
3279void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
3280 VkSurfaceKHR surface,
3281 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
3282 VkResult result) {
3283 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3284 if (bp_pd_state) {
3285 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3286 }
3287}
3288
3289void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
3290 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3291 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
3292 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3293 if (bp_pd_state) {
3294 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3295 }
3296}
3297
3298void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
3299 VkSurfaceKHR surface,
3300 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
3301 VkResult result) {
3302 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
3303 if (bp_pd_state) {
3304 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
3305 }
3306}
3307
3308void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
3309 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
3310 VkPresentModeKHR* pPresentModes, VkResult result) {
3311 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3312 if (bp_pd_data) {
3313 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
3314
3315 if (*pPresentModeCount) {
3316 if (call_state < QUERY_COUNT) {
3317 call_state = QUERY_COUNT;
3318 }
3319 }
3320 if (pPresentModes) {
3321 if (call_state < QUERY_DETAILS) {
3322 call_state = QUERY_DETAILS;
3323 }
3324 }
3325 }
3326}
3327
3328void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
3329 uint32_t* pSurfaceFormatCount,
3330 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
3331 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3332 if (bp_pd_data) {
3333 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
3334
3335 if (*pSurfaceFormatCount) {
3336 if (call_state < QUERY_COUNT) {
3337 call_state = QUERY_COUNT;
3338 }
3339 }
3340 if (pSurfaceFormats) {
3341 if (call_state < QUERY_DETAILS) {
3342 call_state = QUERY_DETAILS;
3343 }
3344 }
3345 }
3346}
3347
3348void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
3349 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
3350 uint32_t* pSurfaceFormatCount,
3351 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
3352 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3353 if (bp_pd_data) {
3354 if (*pSurfaceFormatCount) {
3355 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
3356 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
3357 }
3358 }
3359 if (pSurfaceFormats) {
3360 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
3361 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
3362 }
3363 }
3364 }
3365}
3366
3367void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
3368 uint32_t* pPropertyCount,
3369 VkDisplayPlanePropertiesKHR* pProperties,
3370 VkResult result) {
3371 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
3372 if (bp_pd_data) {
3373 if (*pPropertyCount) {
3374 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
3375 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
3376 }
3377 }
3378 if (pProperties) {
3379 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
3380 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
3381 }
3382 }
3383 }
3384}
3385
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003386void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
3387 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
3388 VkResult result) {
Nathaniel Cesario39152e62021-07-02 13:04:16 -06003389 auto* swapchain_state = static_cast<SWAPCHAIN_STATE_BP*>(Get<SWAPCHAIN_NODE>(swapchain));
3390 if (swapchain_state && (pSwapchainImages || *pSwapchainImageCount)) {
3391 if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
3392 swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06003393 }
3394 }
3395}
3396
3397void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
3398 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
3399 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
3400 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
3401 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
3402 }
3403 }
3404}
3405
3406void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
3407 VkDevice*, VkResult result) {
3408 if (VK_SUCCESS == result) {
3409 instance_device_bp_state = &phys_device_bp_state_map[gpu];
3410 }
3411}
3412
3413PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
3414 if (phys_device_bp_state_map.count(phys_device) > 0) {
3415 return &phys_device_bp_state_map.at(phys_device);
3416 } else {
3417 return nullptr;
3418 }
3419}
3420
3421const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
3422 if (phys_device_bp_state_map.count(phys_device) > 0) {
3423 return &phys_device_bp_state_map.at(phys_device);
3424 } else {
3425 return nullptr;
3426 }
3427}
3428
3429PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
3430 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3431 if (bp_state) {
3432 return bp_state;
3433 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3434 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3435 } else {
3436 return nullptr;
3437 }
3438}
3439
3440const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
3441 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
3442 if (bp_state) {
3443 return bp_state;
3444 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3445 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3446 } else {
3447 return nullptr;
3448 }
3449}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003450
3451void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3452 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3453
3454 QUEUE_STATE* queue_state = GetQueueState(queue);
3455 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003456 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003457 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
3458 CMD_BUFFER_STATE* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
3459 for (auto &func : cb->queue_submit_functions) {
3460 func(this, queue_state);
3461 }
3462 }
3463 }
3464}