blob: abee95b8112ac6b9321f6aa80ed2bf3e435b214f [file] [log] [blame]
Nathaniel Cesario56a96652020-12-30 13:23:42 -07001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * 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"
Camden5b184be2019-08-13 07:50:19 -060025
26#include <string>
Sam Walls8e77e4f2020-03-16 20:47:40 +000027#include <bitset>
Sam Wallsd7ab6db2020-06-19 20:41:54 +010028#include <memory>
Camden5b184be2019-08-13 07:50:19 -060029
Attilio Provenzano19d6a982020-02-27 12:41:41 +000030struct VendorSpecificInfo {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060031 EnableFlags vendor_id;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000032 std::string name;
33};
34
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070035const std::map<BPVendorFlagBits, VendorSpecificInfo> kVendorInfo = {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060036 {kBPVendorArm, {vendor_specific_arm, "Arm"}},
Attilio Provenzano19d6a982020-02-27 12:41:41 +000037};
38
39bool BestPractices::VendorCheckEnabled(BPVendorFlags vendors) const {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070040 for (const auto& vendor : kVendorInfo) {
Mark Lobodzinski90eea5b2020-05-15 12:54:00 -060041 if (vendors & vendor.first && enabled[vendor.second.vendor_id]) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000042 return true;
43 }
44 }
45 return false;
46}
47
48const char* VendorSpecificTag(BPVendorFlags vendors) {
49 // Cache built vendor tags in a map
Jeremy Gebbencbf22862021-03-03 12:01:22 -070050 static layer_data::unordered_map<BPVendorFlags, std::string> tag_map;
Attilio Provenzano19d6a982020-02-27 12:41:41 +000051
52 auto res = tag_map.find(vendors);
53 if (res == tag_map.end()) {
54 // Build the vendor tag string
55 std::stringstream vendor_tag;
56
57 vendor_tag << "[";
58 bool first_vendor = true;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -070059 for (const auto& vendor : kVendorInfo) {
Attilio Provenzano19d6a982020-02-27 12:41:41 +000060 if (vendors & vendor.first) {
61 if (!first_vendor) {
62 vendor_tag << ", ";
63 }
64 vendor_tag << vendor.second.name;
65 first_vendor = false;
66 }
67 }
68 vendor_tag << "]";
69
70 tag_map[vendors] = vendor_tag.str();
71 res = tag_map.find(vendors);
72 }
73
74 return res->second.c_str();
75}
76
Mark Lobodzinski6167e102020-02-24 17:03:55 -070077const char* DepReasonToString(ExtDeprecationReason reason) {
78 switch (reason) {
79 case kExtPromoted:
80 return "promoted to";
81 break;
82 case kExtObsoleted:
83 return "obsoleted by";
84 break;
85 case kExtDeprecated:
86 return "deprecated by";
87 break;
88 default:
89 return "";
90 break;
91 }
92}
93
94bool BestPractices::ValidateDeprecatedExtensions(const char* api_name, const char* extension_name, uint32_t version,
95 const char* vuid) const {
96 bool skip = false;
97 auto dep_info_it = deprecated_extensions.find(extension_name);
98 if (dep_info_it != deprecated_extensions.end()) {
99 auto dep_info = dep_info_it->second;
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600100 if (((dep_info.target.compare("VK_VERSION_1_1") == 0) && (version >= VK_API_VERSION_1_1)) ||
101 ((dep_info.target.compare("VK_VERSION_1_2") == 0) && (version >= VK_API_VERSION_1_2))) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700102 skip |=
103 LogWarning(instance, vuid, "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
104 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
Mark Lobodzinski6a149702020-05-14 12:21:34 -0600105 } else if (dep_info.target.find("VK_VERSION") == std::string::npos) {
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700106 if (dep_info.target.length() == 0) {
107 skip |= LogWarning(instance, vuid,
108 "%s(): Attempting to enable deprecated extension %s, but this extension has been deprecated "
109 "without replacement.",
110 api_name, extension_name);
111 } else {
112 skip |= LogWarning(instance, vuid,
113 "%s(): Attempting to enable deprecated extension %s, but this extension has been %s %s.",
114 api_name, extension_name, DepReasonToString(dep_info.reason), (dep_info.target).c_str());
115 }
116 }
117 }
118 return skip;
119}
120
Mark Lobodzinski057724a2020-11-09 17:13:18 -0700121bool BestPractices::ValidateSpecialUseExtensions(const char* api_name, const char* extension_name, const char* vuid) const {
122 bool skip = false;
123 auto dep_info_it = special_use_extensions.find(extension_name);
124
125 if (dep_info_it != special_use_extensions.end()) {
126 auto special_uses = dep_info_it->second;
127 std::string message("is intended to support the following uses: ");
128 if (special_uses.find("cadsupport") != std::string::npos) {
129 message.append("specialized functionality used by CAD/CAM applications, ");
130 }
131 if (special_uses.find("d3demulation") != std::string::npos) {
132 message.append("D3D emulation layers, and applications ported from D3D, by adding functionality specific to D3D, ");
133 }
134 if (special_uses.find("devtools") != std::string::npos) {
135 message.append(" developer tools such as capture-replay libraries, ");
136 }
137 if (special_uses.find("debugging") != std::string::npos) {
138 message.append("use by applications when debugging, ");
139 }
140 if (special_uses.find("glemulation") != std::string::npos) {
141 message.append(
142 "OpenGL and/or OpenGL ES emulation layers, and applications ported from those APIs, by adding functionality "
143 "specific to those APIs, ");
144 }
145 message.append("and it is strongly recommended that they be otherwise avoided");
146
147 skip |= LogWarning(instance, vuid, "%s(): Attempting to enable extension %s, but this extension %s.", api_name,
148 extension_name, message.c_str());
149 }
150 return skip;
151}
152
Camden5b184be2019-08-13 07:50:19 -0600153bool BestPractices::PreCallValidateCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500154 VkInstance* pInstance) const {
Camden5b184be2019-08-13 07:50:19 -0600155 bool skip = false;
156
157 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
158 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kDeviceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800159 skip |= LogWarning(instance, kVUID_BestPractices_CreateInstance_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700160 "vkCreateInstance(): Attempting to enable Device Extension %s at CreateInstance time.",
161 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600162 }
Mark Lobodzinski17d8dc62020-06-03 08:48:58 -0600163 uint32_t specified_version =
164 (pCreateInfo->pApplicationInfo ? pCreateInfo->pApplicationInfo->apiVersion : VK_API_VERSION_1_0);
165 skip |= ValidateDeprecatedExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i], specified_version,
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700166 kVUID_BestPractices_CreateInstance_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700167 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
168 kVUID_BestPractices_CreateInstance_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600169 }
170
171 return skip;
172}
173
174void BestPractices::PreCallRecordCreateInstance(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator,
175 VkInstance* pInstance) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700176 ValidationStateTracker::PreCallRecordCreateInstance(pCreateInfo, pAllocator, pInstance);
Sam Walls53bf7652020-04-21 17:35:15 +0100177
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700178 if (pCreateInfo != nullptr && pCreateInfo->pApplicationInfo != nullptr) {
Sam Walls53bf7652020-04-21 17:35:15 +0100179 instance_api_version = pCreateInfo->pApplicationInfo->apiVersion;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700180 } else {
Sam Walls53bf7652020-04-21 17:35:15 +0100181 instance_api_version = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700182 }
Camden5b184be2019-08-13 07:50:19 -0600183}
184
185bool BestPractices::PreCallValidateCreateDevice(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500186 const VkAllocationCallbacks* pAllocator, VkDevice* pDevice) const {
Camden5b184be2019-08-13 07:50:19 -0600187 bool skip = false;
188
189 // get API version of physical device passed when creating device.
190 VkPhysicalDeviceProperties physical_device_properties{};
191 DispatchGetPhysicalDeviceProperties(physicalDevice, &physical_device_properties);
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500192 auto device_api_version = physical_device_properties.apiVersion;
Camden5b184be2019-08-13 07:50:19 -0600193
194 // check api versions and warn if instance api Version is higher than version on device.
195 if (instance_api_version > device_api_version) {
Mark Lobodzinski60880782020-08-11 08:02:07 -0600196 std::string inst_api_name = StringAPIVersion(instance_api_version);
197 std::string dev_api_name = StringAPIVersion(device_api_version);
Camden5b184be2019-08-13 07:50:19 -0600198
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700199 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_API_Mismatch,
200 "vkCreateDevice(): API Version of current instance, %s is higher than API Version on device, %s",
201 inst_api_name.c_str(), dev_api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -0600202 }
203
204 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
205 if (white_list(pCreateInfo->ppEnabledExtensionNames[i], kInstanceExtensionNames)) {
Camden Stocker11ecf512020-01-21 16:06:49 -0800206 skip |= LogWarning(instance, kVUID_BestPractices_CreateDevice_ExtensionMismatch,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700207 "vkCreateDevice(): Attempting to enable Instance Extension %s at CreateDevice time.",
208 pCreateInfo->ppEnabledExtensionNames[i]);
Camden5b184be2019-08-13 07:50:19 -0600209 }
Mark Lobodzinski6167e102020-02-24 17:03:55 -0700210 skip |= ValidateDeprecatedExtensions("CreateDevice", pCreateInfo->ppEnabledExtensionNames[i], instance_api_version,
211 kVUID_BestPractices_CreateDevice_DeprecatedExtension);
Mark Lobodzinskia431b772020-11-10 08:12:13 -0700212 skip |= ValidateSpecialUseExtensions("CreateInstance", pCreateInfo->ppEnabledExtensionNames[i],
213 kVUID_BestPractices_CreateDevice_SpecialUseExtension);
Camden5b184be2019-08-13 07:50:19 -0600214 }
215
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600216 const auto bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
217 if ((bp_pd_state->vkGetPhysicalDeviceFeaturesState == UNCALLED) && (pCreateInfo->pEnabledFeatures != NULL)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700218 skip |= LogWarning(device, kVUID_BestPractices_CreateDevice_PDFeaturesNotCalled,
219 "vkCreateDevice() called before getting physical device features from vkGetPhysicalDeviceFeatures().");
Camden83a9c372019-08-14 11:41:38 -0600220 }
221
Szilard Papp7d2c7952020-06-22 14:38:13 +0100222 if ((VendorCheckEnabled(kBPVendorArm)) && (pCreateInfo->pEnabledFeatures != nullptr) &&
223 (pCreateInfo->pEnabledFeatures->robustBufferAccess == VK_TRUE)) {
224 skip |= LogPerformanceWarning(
225 device, kVUID_BestPractices_CreateDevice_RobustBufferAccess,
226 "%s vkCreateDevice() called with enabled robustBufferAccess. Use robustBufferAccess as a debugging tool during "
227 "development. Enabling it causes loss in performance for accesses to uniform buffers and shader storage "
228 "buffers. Disable robustBufferAccess in release builds. Only leave it enabled if the application use-case "
229 "requires the additional level of reliability due to the use of unverified user-supplied draw parameters.",
230 VendorSpecificTag(kBPVendorArm));
231 }
232
Camden5b184be2019-08-13 07:50:19 -0600233 return skip;
234}
235
236bool BestPractices::PreCallValidateCreateBuffer(VkDevice device, const VkBufferCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500237 const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer) const {
Camden5b184be2019-08-13 07:50:19 -0600238 bool skip = false;
239
240 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700241 std::stringstream buffer_hex;
242 buffer_hex << "0x" << std::hex << HandleToUint64(pBuffer);
Camden5b184be2019-08-13 07:50:19 -0600243
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700244 skip |= LogWarning(
245 device, kVUID_BestPractices_SharingModeExclusive,
246 "Warning: Buffer (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
247 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700248 buffer_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600249 }
250
251 return skip;
252}
253
254bool BestPractices::PreCallValidateCreateImage(VkDevice device, const VkImageCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500255 const VkAllocationCallbacks* pAllocator, VkImage* pImage) const {
Camden5b184be2019-08-13 07:50:19 -0600256 bool skip = false;
257
258 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->sharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700259 std::stringstream image_hex;
260 image_hex << "0x" << std::hex << HandleToUint64(pImage);
Camden5b184be2019-08-13 07:50:19 -0600261
262 skip |=
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700263 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
264 "Warning: Image (%s) specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple queues "
265 "(queueFamilyIndexCount of %" PRIu32 ").",
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700266 image_hex.str().c_str(), pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600267 }
268
Attilio Provenzano02859b22020-02-27 14:17:28 +0000269 if (VendorCheckEnabled(kBPVendorArm)) {
270 if (pCreateInfo->samples > kMaxEfficientSamplesArm) {
271 skip |= LogPerformanceWarning(
272 device, kVUID_BestPractices_CreateImage_TooLargeSampleCount,
273 "%s vkCreateImage(): Trying to create an image with %u samples. "
274 "The hardware revision may not have full throughput for framebuffers with more than %u samples.",
275 VendorSpecificTag(kBPVendorArm), static_cast<uint32_t>(pCreateInfo->samples), kMaxEfficientSamplesArm);
276 }
277
278 if (pCreateInfo->samples > VK_SAMPLE_COUNT_1_BIT && !(pCreateInfo->usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT)) {
279 skip |= LogPerformanceWarning(
280 device, kVUID_BestPractices_CreateImage_NonTransientMSImage,
281 "%s vkCreateImage(): Trying to create a multisampled image, but createInfo.usage did not have "
282 "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. Multisampled images may be resolved on-chip, "
283 "and do not need to be backed by physical storage. "
284 "TRANSIENT_ATTACHMENT allows tiled GPUs to not back the multisampled image with physical memory.",
285 VendorSpecificTag(kBPVendorArm));
286 }
287 }
288
Camden5b184be2019-08-13 07:50:19 -0600289 return skip;
290}
291
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100292void BestPractices::PreCallRecordDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
293 ValidationStateTracker::PreCallRecordDestroyImage(device, image, pAllocator);
294 ReleaseImageUsageState(image);
295}
296
Hans-Kristian Arntzen92664eb2021-03-29 12:19:48 +0200297void BestPractices::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator) {
298 SWAPCHAIN_NODE* chain = GetSwapchainState(swapchain);
299 for (auto& image : chain->images) {
300 ReleaseImageUsageState(image.image_state->image());
301 }
302 ValidationStateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
303}
304
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +0100305IMAGE_STATE_BP* BestPractices::GetImageUsageState(VkImage vk_image) {
306 auto itr = imageUsageMap.find(vk_image);
307 if (itr != imageUsageMap.end()) {
308 return &itr->second;
309 } else {
310 auto& state = imageUsageMap[vk_image];
311 IMAGE_STATE* image = GetImageState(vk_image);
312 state.image = image;
313 state.usages.resize(image->createInfo.arrayLayers);
314 for (auto& mips : state.usages) {
315 mips.resize(image->createInfo.mipLevels, IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED);
316 }
317 return &state;
318 }
319}
320
321void BestPractices::ReleaseImageUsageState(VkImage image) {
322 auto itr = imageUsageMap.find(image);
323 if (itr != imageUsageMap.end()) {
324 imageUsageMap.erase(itr);
325 }
326}
327
Camden5b184be2019-08-13 07:50:19 -0600328bool BestPractices::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500329 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain) const {
Camden5b184be2019-08-13 07:50:19 -0600330 bool skip = false;
331
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600332 const auto* bp_pd_state = GetPhysicalDeviceStateBP();
333 if (bp_pd_state) {
334 if (bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) {
335 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
336 "vkCreateSwapchainKHR() called before getting surface capabilities from "
337 "vkGetPhysicalDeviceSurfaceCapabilitiesKHR().");
338 }
Camden83a9c372019-08-14 11:41:38 -0600339
Shannon McPherson73e58c82021-03-05 17:14:26 -0700340 if ((pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) &&
341 (bp_pd_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS)) {
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600342 skip |= LogWarning(device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
343 "vkCreateSwapchainKHR() called before getting surface present mode(s) from "
344 "vkGetPhysicalDeviceSurfacePresentModesKHR().");
345 }
Camden83a9c372019-08-14 11:41:38 -0600346
Nathaniel Cesario24184fe2020-10-06 12:46:12 -0600347 if (bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) {
348 skip |= LogWarning(
349 device, kVUID_BestPractices_Swapchain_GetSurfaceNotCalled,
350 "vkCreateSwapchainKHR() called before getting surface format(s) from vkGetPhysicalDeviceSurfaceFormatsKHR().");
351 }
Camden83a9c372019-08-14 11:41:38 -0600352 }
353
Camden5b184be2019-08-13 07:50:19 -0600354 if ((pCreateInfo->queueFamilyIndexCount > 1) && (pCreateInfo->imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700355 skip |=
356 LogWarning(device, kVUID_BestPractices_SharingModeExclusive,
Mark Lobodzinski019f4e32020-04-13 11:01:35 -0600357 "Warning: A Swapchain is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while "
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700358 "specifying multiple queues (queueFamilyIndexCount of %" PRIu32 ").",
359 pCreateInfo->queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600360 }
361
Szilard Papp48a6da32020-06-10 14:41:59 +0100362 if (pCreateInfo->minImageCount == 2) {
363 skip |= LogPerformanceWarning(
364 device, kVUID_BestPractices_SuboptimalSwapchainImageCount,
365 "Warning: A Swapchain is being created with minImageCount set to %" PRIu32
366 ", which means double buffering is going "
367 "to be used. Using double buffering and vsync locks rendering to an integer fraction of the vsync rate. In turn, "
368 "reducing the performance of the application if rendering is slower than vsync. Consider setting minImageCount to "
369 "3 to use triple buffering to maximize performance in such cases.",
370 pCreateInfo->minImageCount);
371 }
372
Szilard Pappd5f0f812020-06-22 09:01:29 +0100373 if (VendorCheckEnabled(kBPVendorArm) && (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR)) {
374 skip |= LogWarning(device, kVUID_BestPractices_CreateSwapchain_PresentMode,
375 "%s Warning: Swapchain is not being created with presentation mode \"VK_PRESENT_MODE_FIFO_KHR\". "
376 "Prefer using \"VK_PRESENT_MODE_FIFO_KHR\" to avoid unnecessary CPU and GPU load and save power. "
377 "Presentation modes which are not FIFO will present the latest available frame and discard other "
378 "frame(s) if any.",
379 VendorSpecificTag(kBPVendorArm));
380 }
381
Camden5b184be2019-08-13 07:50:19 -0600382 return skip;
383}
384
385bool BestPractices::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount,
386 const VkSwapchainCreateInfoKHR* pCreateInfos,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500387 const VkAllocationCallbacks* pAllocator,
388 VkSwapchainKHR* pSwapchains) const {
Camden5b184be2019-08-13 07:50:19 -0600389 bool skip = false;
390
391 for (uint32_t i = 0; i < swapchainCount; i++) {
392 if ((pCreateInfos[i].queueFamilyIndexCount > 1) && (pCreateInfos[i].imageSharingMode == VK_SHARING_MODE_EXCLUSIVE)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700393 skip |= LogWarning(
394 device, kVUID_BestPractices_SharingModeExclusive,
395 "Warning: A shared swapchain (index %" PRIu32
396 ") is being created which specifies a sharing mode of VK_SHARING_MODE_EXCLUSIVE while specifying multiple "
397 "queues (queueFamilyIndexCount of %" PRIu32 ").",
398 i, pCreateInfos[i].queueFamilyIndexCount);
Camden5b184be2019-08-13 07:50:19 -0600399 }
400 }
401
402 return skip;
403}
404
405bool BestPractices::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500406 const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass) const {
Camden5b184be2019-08-13 07:50:19 -0600407 bool skip = false;
408
409 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) {
410 VkFormat format = pCreateInfo->pAttachments[i].format;
411 if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) {
412 if ((FormatIsColor(format) || FormatHasDepth(format)) &&
413 pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700414 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
415 "Render pass has an attachment with loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and "
416 "initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
417 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
418 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600419 }
420 if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700421 skip |= LogWarning(device, kVUID_BestPractices_RenderPass_Attatchment,
422 "Render pass has an attachment with stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD "
423 "and initialLayout == VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you "
424 "intended. Consider using VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the "
425 "image truely is undefined at the start of the render pass.");
Camden5b184be2019-08-13 07:50:19 -0600426 }
427 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000428
429 const auto& attachment = pCreateInfo->pAttachments[i];
430 if (attachment.samples > VK_SAMPLE_COUNT_1_BIT) {
431 bool access_requires_memory =
432 attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE;
433
434 if (FormatHasStencil(format)) {
435 access_requires_memory |= attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ||
436 attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE;
437 }
438
439 if (access_requires_memory) {
440 skip |= LogPerformanceWarning(
441 device, kVUID_BestPractices_CreateRenderPass_ImageRequiresMemory,
442 "Attachment %u in the VkRenderPass is a multisampled image with %u samples, but it uses loadOp/storeOp "
443 "which requires accessing data from memory. Multisampled images should always be loadOp = CLEAR or DONT_CARE, "
444 "storeOp = DONT_CARE. This allows the implementation to use lazily allocated memory effectively.",
445 i, static_cast<uint32_t>(attachment.samples));
446 }
447 }
Camden5b184be2019-08-13 07:50:19 -0600448 }
449
450 for (uint32_t dependency = 0; dependency < pCreateInfo->dependencyCount; dependency++) {
451 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].srcStageMask);
452 skip |= CheckPipelineStageFlags("vkCreateRenderPass", pCreateInfo->pDependencies[dependency].dstStageMask);
453 }
454
455 return skip;
456}
457
Tony-LunarG767180f2020-04-23 14:03:59 -0600458bool BestPractices::ValidateAttachments(const VkRenderPassCreateInfo2* rpci, uint32_t attachmentCount,
459 const VkImageView* image_views) const {
460 bool skip = false;
461
462 // Check for non-transient attachments that should be transient and vice versa
463 for (uint32_t i = 0; i < attachmentCount; ++i) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200464 const auto& attachment = rpci->pAttachments[i];
Tony-LunarG767180f2020-04-23 14:03:59 -0600465 bool attachment_should_be_transient =
466 (attachment.loadOp != VK_ATTACHMENT_LOAD_OP_LOAD && attachment.storeOp != VK_ATTACHMENT_STORE_OP_STORE);
467
468 if (FormatHasStencil(attachment.format)) {
469 attachment_should_be_transient &= (attachment.stencilLoadOp != VK_ATTACHMENT_LOAD_OP_LOAD &&
470 attachment.stencilStoreOp != VK_ATTACHMENT_STORE_OP_STORE);
471 }
472
473 auto view_state = GetImageViewState(image_views[i]);
474 if (view_state) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200475 const auto& ivci = view_state->create_info;
476 const auto& ici = GetImageState(ivci.image)->createInfo;
Tony-LunarG767180f2020-04-23 14:03:59 -0600477
478 bool image_is_transient = (ici.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) != 0;
479
480 // The check for an image that should not be transient applies to all GPUs
481 if (!attachment_should_be_transient && image_is_transient) {
482 skip |= LogPerformanceWarning(
483 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldNotBeTransient,
484 "Attachment %u in VkFramebuffer uses loadOp/storeOps which need to access physical memory, "
485 "but the image backing the image view has VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
486 "Physical memory will need to be backed lazily to this image, potentially causing stalls.",
487 i);
488 }
489
490 bool supports_lazy = false;
491 for (uint32_t j = 0; j < phys_dev_mem_props.memoryTypeCount; j++) {
492 if (phys_dev_mem_props.memoryTypes[j].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
493 supports_lazy = true;
494 }
495 }
496
497 // The check for an image that should be transient only applies to GPUs supporting
498 // lazily allocated memory
499 if (supports_lazy && attachment_should_be_transient && !image_is_transient) {
500 skip |= LogPerformanceWarning(
501 device, kVUID_BestPractices_CreateFramebuffer_AttachmentShouldBeTransient,
502 "Attachment %u in VkFramebuffer uses loadOp/storeOps which never have to be backed by physical memory, "
503 "but the image backing the image view does not have VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT set. "
504 "You can save physical memory by using transient attachment backed by lazily allocated memory here.",
505 i);
506 }
507 }
508 }
509 return skip;
510}
511
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000512bool BestPractices::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo,
513 const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer) const {
514 bool skip = false;
515
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000516 auto rp_state = GetRenderPassState(pCreateInfo->renderPass);
Mike Schuchardt2df08912020-12-15 16:28:09 -0800517 if (rp_state && !(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) {
Tony-LunarG767180f2020-04-23 14:03:59 -0600518 skip = ValidateAttachments(rp_state->createInfo.ptr(), pCreateInfo->attachmentCount, pCreateInfo->pAttachments);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000519 }
520
521 return skip;
522}
523
Sam Wallse746d522020-03-16 21:20:23 +0000524bool BestPractices::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
525 VkDescriptorSet* pDescriptorSets, void* ads_state_data) const {
526 bool skip = false;
527 skip |= ValidationStateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data);
528
529 if (!skip) {
530 const auto& pool_handle = pAllocateInfo->descriptorPool;
531 auto iter = descriptor_pool_freed_count.find(pool_handle);
532 // if the number of freed sets > 0, it implies they could be recycled instead if desirable
533 // this warning is specific to Arm
534 if (VendorCheckEnabled(kBPVendorArm) && iter != descriptor_pool_freed_count.end() && iter->second > 0) {
535 skip |= LogPerformanceWarning(
536 device, kVUID_BestPractices_AllocateDescriptorSets_SuboptimalReuse,
537 "%s Descriptor set memory was allocated via vkAllocateDescriptorSets() for sets which were previously freed in the "
538 "same logical device. On some drivers or architectures it may be most optimal to re-use existing descriptor sets.",
539 VendorSpecificTag(kBPVendorArm));
540 }
541 }
542
543 return skip;
544}
545
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600546void BestPractices::ManualPostCallRecordAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo,
547 VkDescriptorSet* pDescriptorSets, VkResult result, void* ads_state) {
Sam Wallse746d522020-03-16 21:20:23 +0000548 if (result == VK_SUCCESS) {
549 // find the free count for the pool we allocated into
550 auto iter = descriptor_pool_freed_count.find(pAllocateInfo->descriptorPool);
551 if (iter != descriptor_pool_freed_count.end()) {
552 // we record successful allocations by subtracting the allocation count from the last recorded free count
553 const auto alloc_count = pAllocateInfo->descriptorSetCount;
554 // clamp the unsigned subtraction to the range [0, last_free_count]
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700555 if (iter->second > alloc_count) {
Sam Wallse746d522020-03-16 21:20:23 +0000556 iter->second -= alloc_count;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700557 } else {
Sam Wallse746d522020-03-16 21:20:23 +0000558 iter->second = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700559 }
Sam Wallse746d522020-03-16 21:20:23 +0000560 }
561 }
562}
563
564void BestPractices::PostCallRecordFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount,
565 const VkDescriptorSet* pDescriptorSets, VkResult result) {
566 ValidationStateTracker::PostCallRecordFreeDescriptorSets(device, descriptorPool, descriptorSetCount, pDescriptorSets, result);
567 if (result == VK_SUCCESS) {
568 // we want to track frees because we're interested in suggesting re-use
569 auto iter = descriptor_pool_freed_count.find(descriptorPool);
570 if (iter == descriptor_pool_freed_count.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700571 descriptor_pool_freed_count.emplace(descriptorPool, descriptorSetCount);
Sam Wallse746d522020-03-16 21:20:23 +0000572 } else {
573 iter->second += descriptorSetCount;
574 }
575 }
576}
577
Camden5b184be2019-08-13 07:50:19 -0600578bool BestPractices::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500579 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory) const {
Camden5b184be2019-08-13 07:50:19 -0600580 bool skip = false;
581
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500582 if (num_mem_objects + 1 > kMemoryObjectWarningLimit) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700583 skip |= LogPerformanceWarning(device, kVUID_BestPractices_AllocateMemory_TooManyObjects,
584 "Performance Warning: This app has > %" PRIu32 " memory objects.", kMemoryObjectWarningLimit);
Camden5b184be2019-08-13 07:50:19 -0600585 }
586
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000587 if (pAllocateInfo->allocationSize < kMinDeviceAllocationSize) {
588 skip |= LogPerformanceWarning(
589 device, kVUID_BestPractices_AllocateMemory_SmallAllocation,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600590 "vkAllocateMemory(): Allocating a VkDeviceMemory of size %" PRIu64 ". This is a very small allocation (current "
591 "threshold is %" PRIu64 " bytes). "
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000592 "You should make large allocations and sub-allocate from one large VkDeviceMemory.",
593 pAllocateInfo->allocationSize, kMinDeviceAllocationSize);
594 }
595
Camden83a9c372019-08-14 11:41:38 -0600596 // TODO: Insert get check for GetPhysicalDeviceMemoryProperties once the state is tracked in the StateTracker
597
598 return skip;
599}
600
Mark Lobodzinski84101d72020-04-24 09:43:48 -0600601void BestPractices::ManualPostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo,
602 const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory,
603 VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700604 if (result != VK_SUCCESS) {
605 static std::vector<VkResult> error_codes = {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
606 VK_ERROR_TOO_MANY_OBJECTS, VK_ERROR_INVALID_EXTERNAL_HANDLE,
Mike Schuchardt2df08912020-12-15 16:28:09 -0800607 VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS};
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700608 static std::vector<VkResult> success_codes = {};
Nathaniel Cesariodb3f43f2021-05-12 09:08:23 -0600609 ValidateReturnCodes("vkAllocateMemory", result, error_codes, success_codes);
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700610 return;
611 }
612 num_mem_objects++;
613}
Camden Stocker9738af92019-10-16 13:54:03 -0700614
Mark Lobodzinskide15e582020-04-29 08:06:00 -0600615void BestPractices::ValidateReturnCodes(const char* api_name, VkResult result, const std::vector<VkResult>& error_codes,
616 const std::vector<VkResult>& success_codes) const {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700617 auto error = std::find(error_codes.begin(), error_codes.end(), result);
618 if (error != error_codes.end()) {
Gareth Webb586c46b2021-01-13 11:17:22 +0000619 static const std::vector<VkResult> common_failure_codes = {VK_ERROR_OUT_OF_DATE_KHR,
620 VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT};
621
622 auto common_failure = std::find(common_failure_codes.begin(), common_failure_codes.end(), result);
623 if (common_failure != common_failure_codes.end()) {
624 LogInfo(instance, kVUID_BestPractices_Failure_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
625 } else {
626 LogWarning(instance, kVUID_BestPractices_Error_Result, "%s(): Returned error %s.", api_name, string_VkResult(result));
627 }
Mark Lobodzinski205b7a02020-02-21 13:23:17 -0700628 return;
629 }
630 auto success = std::find(success_codes.begin(), success_codes.end(), result);
631 if (success != success_codes.end()) {
Mark Lobodzinskie7215152020-05-11 08:21:23 -0600632 LogInfo(instance, kVUID_BestPractices_NonSuccess_Result, "%s(): Returned non-success return code %s.", api_name,
633 string_VkResult(result));
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500634 }
635}
636
Jeff Bolz5c801d12019-10-09 10:38:45 -0500637bool BestPractices::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory memory,
638 const VkAllocationCallbacks* pAllocator) const {
Mark Lobodzinski91e50bf2020-01-14 09:55:11 -0700639 if (memory == VK_NULL_HANDLE) return false;
Camden83a9c372019-08-14 11:41:38 -0600640 bool skip = false;
641
Camden Stocker9738af92019-10-16 13:54:03 -0700642 const DEVICE_MEMORY_STATE* mem_info = ValidationStateTracker::GetDevMemState(memory);
Camden83a9c372019-08-14 11:41:38 -0600643
Jeremy Gebben5570abe2021-05-16 18:35:13 -0600644 for (const auto& node: mem_info->ObjectBindings()) {
645 const auto& obj = node->Handle();
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600646 LogObjectList objlist(device);
647 objlist.add(obj);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -0600648 objlist.add(mem_info->mem());
Mark Lobodzinski818425a2020-03-16 18:19:03 -0600649 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 -0600650 report_data->FormatHandle(obj).c_str(), report_data->FormatHandle(mem_info->mem()).c_str());
Camden83a9c372019-08-14 11:41:38 -0600651 }
652
Camden5b184be2019-08-13 07:50:19 -0600653 return skip;
654}
655
656void BestPractices::PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator) {
Mark Lobodzinski97484d62020-03-03 11:57:41 -0700657 ValidationStateTracker::PreCallRecordFreeMemory(device, memory, pAllocator);
Camden5b184be2019-08-13 07:50:19 -0600658 if (memory != VK_NULL_HANDLE) {
659 num_mem_objects--;
660 }
661}
662
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000663bool BestPractices::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory memory, const char* api_name) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600664 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500665 const BUFFER_STATE* buffer_state = GetBufferState(buffer);
Camden Stockerb603cc82019-09-03 10:09:02 -0600666
sfricke-samsunge2441192019-11-06 14:07:57 -0800667 if (!buffer_state->memory_requirements_checked && !buffer_state->external_memory_handle) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -0700668 skip |= LogWarning(device, kVUID_BestPractices_BufferMemReqNotCalled,
669 "%s: Binding memory to %s but vkGetBufferMemoryRequirements() has not been called on that buffer.",
670 api_name, report_data->FormatHandle(buffer).c_str());
Camden Stockerb603cc82019-09-03 10:09:02 -0600671 }
672
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000673 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
674
675 if (mem_state->alloc_info.allocationSize == buffer_state->createInfo.size &&
676 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
677 skip |= LogPerformanceWarning(
678 device, kVUID_BestPractices_SmallDedicatedAllocation,
679 "%s: Trying to bind %s to a memory block which is fully consumed by the buffer. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600680 "The required size of the allocation is %" PRIu64 ", but smaller buffers like this should be sub-allocated from "
681 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000682 api_name, report_data->FormatHandle(buffer).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
683 }
684
Camden Stockerb603cc82019-09-03 10:09:02 -0600685 return skip;
686}
687
688bool BestPractices::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500689 VkDeviceSize memoryOffset) const {
Camden Stockerb603cc82019-09-03 10:09:02 -0600690 bool skip = false;
691 const char* api_name = "BindBufferMemory()";
692
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000693 skip |= ValidateBindBufferMemory(buffer, memory, api_name);
Camden Stockerb603cc82019-09-03 10:09:02 -0600694
695 return skip;
696}
697
698bool BestPractices::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500699 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600700 char api_name[64];
701 bool skip = false;
702
703 for (uint32_t i = 0; i < bindInfoCount; i++) {
704 sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000705 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600706 }
707
708 return skip;
709}
Camden Stockerb603cc82019-09-03 10:09:02 -0600710
711bool BestPractices::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500712 const VkBindBufferMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600713 char api_name[64];
714 bool skip = false;
Camden Stockerb603cc82019-09-03 10:09:02 -0600715
Camden Stocker8b798ab2019-09-03 10:33:28 -0600716 for (uint32_t i = 0; i < bindInfoCount; i++) {
717 sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000718 skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600719 }
720
721 return skip;
722}
723
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000724bool BestPractices::ValidateBindImageMemory(VkImage image, VkDeviceMemory memory, const char* api_name) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600725 bool skip = false;
Jeff Bolz46c0ea02019-10-09 13:06:29 -0500726 const IMAGE_STATE* image_state = GetImageState(image);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600727
sfricke-samsung71bc6572020-04-29 15:49:43 -0700728 if (image_state->disjoint == false) {
sfricke-samsungd7ea5de2020-04-08 09:19:18 -0700729 if (!image_state->memory_requirements_checked && !image_state->external_memory_handle) {
730 skip |= LogWarning(device, kVUID_BestPractices_ImageMemReqNotCalled,
731 "%s: Binding memory to %s but vkGetImageMemoryRequirements() has not been called on that image.",
732 api_name, report_data->FormatHandle(image).c_str());
733 }
734 } else {
735 // TODO If binding disjoint image then this needs to check that VkImagePlaneMemoryRequirementsInfo was called for each
736 // plane.
Camden Stocker8b798ab2019-09-03 10:33:28 -0600737 }
738
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000739 const DEVICE_MEMORY_STATE* mem_state = GetDevMemState(memory);
740
741 if (mem_state->alloc_info.allocationSize == image_state->requirements.size &&
742 mem_state->alloc_info.allocationSize < kMinDedicatedAllocationSize) {
743 skip |= LogPerformanceWarning(
744 device, kVUID_BestPractices_SmallDedicatedAllocation,
745 "%s: Trying to bind %s to a memory block which is fully consumed by the image. "
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600746 "The required size of the allocation is %" PRIu64 ", but smaller images like this should be sub-allocated from "
747 "larger memory blocks. (Current threshold is %" PRIu64 " bytes.)",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000748 api_name, report_data->FormatHandle(image).c_str(), mem_state->alloc_info.allocationSize, kMinDedicatedAllocationSize);
749 }
750
751 // If we're binding memory to a image which was created as TRANSIENT and the image supports LAZY allocation,
752 // make sure this type is actually used.
753 // This warning will only trigger if this layer is run on a platform that supports LAZILY_ALLOCATED_BIT
754 // (i.e.most tile - based renderers)
755 if (image_state->createInfo.usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) {
756 bool supports_lazy = false;
757 uint32_t suggested_type = 0;
758
759 for (uint32_t i = 0; i < phys_dev_mem_props.memoryTypeCount; i++) {
760 if ((1u << i) & image_state->requirements.memoryTypeBits) {
761 if (phys_dev_mem_props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
762 supports_lazy = true;
763 suggested_type = i;
764 break;
765 }
766 }
767 }
768
769 uint32_t allocated_properties = phys_dev_mem_props.memoryTypes[mem_state->alloc_info.memoryTypeIndex].propertyFlags;
770
771 if (supports_lazy && (allocated_properties & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) {
772 skip |= LogPerformanceWarning(
773 device, kVUID_BestPractices_NonLazyTransientImage,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -0600774 "%s: Attempting to bind memory type %u to VkImage which was created with TRANSIENT_ATTACHMENT_BIT,"
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000775 "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 -0600776 "%" PRIu64 " bytes of physical memory.",
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000777 api_name, mem_state->alloc_info.memoryTypeIndex, suggested_type, image_state->requirements.size);
778 }
779 }
780
Camden Stocker8b798ab2019-09-03 10:33:28 -0600781 return skip;
782}
783
784bool BestPractices::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500785 VkDeviceSize memoryOffset) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600786 bool skip = false;
787 const char* api_name = "vkBindImageMemory()";
788
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000789 skip |= ValidateBindImageMemory(image, memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600790
791 return skip;
792}
793
794bool BestPractices::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500795 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600796 char api_name[64];
797 bool skip = false;
798
799 for (uint32_t i = 0; i < bindInfoCount; i++) {
800 sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i);
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700801 if (!LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(pBindInfos[i].pNext)) {
Tony-LunarG5e60b852020-04-27 11:27:54 -0600802 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
803 }
Camden Stocker8b798ab2019-09-03 10:33:28 -0600804 }
805
806 return skip;
807}
808
809bool BestPractices::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500810 const VkBindImageMemoryInfo* pBindInfos) const {
Camden Stocker8b798ab2019-09-03 10:33:28 -0600811 char api_name[64];
812 bool skip = false;
813
814 for (uint32_t i = 0; i < bindInfoCount; i++) {
815 sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i);
Attilio Provenzanof31788e2020-02-27 12:00:36 +0000816 skip |= ValidateBindImageMemory(pBindInfos[i].image, pBindInfos[i].memory, api_name);
Camden Stocker8b798ab2019-09-03 10:33:28 -0600817 }
818
819 return skip;
820}
Camden83a9c372019-08-14 11:41:38 -0600821
Attilio Provenzano02859b22020-02-27 14:17:28 +0000822static inline bool FormatHasFullThroughputBlendingArm(VkFormat format) {
823 switch (format) {
824 case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
825 case VK_FORMAT_R16_SFLOAT:
826 case VK_FORMAT_R16G16_SFLOAT:
827 case VK_FORMAT_R16G16B16_SFLOAT:
828 case VK_FORMAT_R16G16B16A16_SFLOAT:
829 case VK_FORMAT_R32_SFLOAT:
830 case VK_FORMAT_R32G32_SFLOAT:
831 case VK_FORMAT_R32G32B32_SFLOAT:
832 case VK_FORMAT_R32G32B32A32_SFLOAT:
833 return false;
834
835 default:
836 return true;
837 }
838}
839
840bool BestPractices::ValidateMultisampledBlendingArm(uint32_t createInfoCount,
841 const VkGraphicsPipelineCreateInfo* pCreateInfos) const {
842 bool skip = false;
843
844 for (uint32_t i = 0; i < createInfoCount; i++) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700845 auto create_info = &pCreateInfos[i];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000846
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700847 if (!create_info->pColorBlendState || !create_info->pMultisampleState ||
848 create_info->pMultisampleState->rasterizationSamples == VK_SAMPLE_COUNT_1_BIT ||
849 create_info->pMultisampleState->sampleShadingEnable) {
Attilio Provenzano02859b22020-02-27 14:17:28 +0000850 return skip;
851 }
852
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700853 auto rp_state = GetRenderPassState(create_info->renderPass);
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200854 const auto& subpass = rp_state->createInfo.pSubpasses[create_info->subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000855
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700856 for (uint32_t j = 0; j < create_info->pColorBlendState->attachmentCount; j++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200857 const auto& blend_att = create_info->pColorBlendState->pAttachments[j];
Attilio Provenzano02859b22020-02-27 14:17:28 +0000858 uint32_t att = subpass.pColorAttachments[j].attachment;
859
860 if (att != VK_ATTACHMENT_UNUSED && blend_att.blendEnable && blend_att.colorWriteMask) {
861 if (!FormatHasFullThroughputBlendingArm(rp_state->createInfo.pAttachments[att].format)) {
862 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreatePipelines_MultisampledBlending,
863 "%s vkCreateGraphicsPipelines() - createInfo #%u: Pipeline is multisampled and "
864 "color attachment #%u makes use "
865 "of a format which cannot be blended at full throughput when using MSAA.",
866 VendorSpecificTag(kBPVendorArm), i, j);
867 }
868 }
869 }
870 }
871
872 return skip;
873}
874
Camden5b184be2019-08-13 07:50:19 -0600875bool BestPractices::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
876 const VkGraphicsPipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600877 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500878 void* cgpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600879 bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, createInfoCount, pCreateInfos,
880 pAllocator, pPipelines, cgpl_state_data);
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600881 create_graphics_pipeline_api_state* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600882
883 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700884 skip |= LogPerformanceWarning(
885 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
886 "Performance Warning: This vkCreateGraphicsPipelines call is creating multiple pipelines but is not using a "
887 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600888 }
889
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000890 for (uint32_t i = 0; i < createInfoCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200891 const auto& create_info = pCreateInfos[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000892
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600893 if (!(cgpl_state->pipe_state[i]->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +0200894 const auto& vertex_input = *create_info.pVertexInputState;
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600895 uint32_t count = 0;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700896 for (uint32_t j = 0; j < vertex_input.vertexBindingDescriptionCount; j++) {
897 if (vertex_input.pVertexBindingDescriptions[j].inputRate == VK_VERTEX_INPUT_RATE_INSTANCE) {
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600898 count++;
899 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000900 }
Mark Lobodzinski8dd14d82020-04-10 14:16:33 -0600901 if (count > kMaxInstancedVertexBuffers) {
902 skip |= LogPerformanceWarning(
903 device, kVUID_BestPractices_CreatePipelines_TooManyInstancedVertexBuffers,
904 "The pipeline is using %u instanced vertex buffers (current limit: %u), but this can be inefficient on the "
905 "GPU. If using instanced vertex attributes prefer interleaving them in a single buffer.",
906 count, kMaxInstancedVertexBuffers);
907 }
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000908 }
Attilio Provenzano02859b22020-02-27 14:17:28 +0000909
Szilard Pappaaf2da32020-06-22 10:37:35 +0100910 if ((pCreateInfos[i].pRasterizationState->depthBiasEnable) &&
911 (pCreateInfos[i].pRasterizationState->depthBiasConstantFactor == 0.0f) &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +0200912 (pCreateInfos[i].pRasterizationState->depthBiasSlopeFactor == 0.0f) &&
913 VendorCheckEnabled(kBPVendorArm)) {
914 skip |= LogPerformanceWarning(
915 device, kVUID_BestPractices_CreatePipelines_DepthBias_Zero,
916 "%s Performance Warning: This vkCreateGraphicsPipelines call is created with depthBiasEnable set to true "
917 "and both depthBiasConstantFactor and depthBiasSlopeFactor are set to 0. This can cause reduced "
918 "efficiency during rasterization. Consider disabling depthBias or increasing either "
919 "depthBiasConstantFactor or depthBiasSlopeFactor.",
920 VendorSpecificTag(kBPVendorArm));
Szilard Pappaaf2da32020-06-22 10:37:35 +0100921 }
922
Attilio Provenzano02859b22020-02-27 14:17:28 +0000923 skip |= VendorCheckEnabled(kBPVendorArm) && ValidateMultisampledBlendingArm(createInfoCount, pCreateInfos);
Attilio Provenzano1d9a8362020-02-27 12:23:51 +0000924 }
925
Camden5b184be2019-08-13 07:50:19 -0600926 return skip;
927}
928
Sam Walls0961ec02020-03-31 16:39:15 +0100929void BestPractices::ManualPostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count,
930 const VkGraphicsPipelineCreateInfo* pCreateInfos,
931 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
932 VkResult result, void* cgpl_state_data) {
933 for (size_t i = 0; i < count; i++) {
934 const auto* cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state*>(cgpl_state_data);
935 const VkPipeline pipeline_handle = pPipelines[i];
936
937 // record depth stencil state and color blend states for depth pre-pass tracking purposes
938 auto gp_cis = graphicsPipelineCIs.find(pipeline_handle);
939
940 // add the tracking state if it doesn't exist
941 if (gp_cis == graphicsPipelineCIs.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -0700942 auto result = graphicsPipelineCIs.emplace(pipeline_handle, GraphicsPipelineCIs{});
Sam Walls0961ec02020-03-31 16:39:15 +0100943
944 if (!result.second) continue;
945
946 gp_cis = result.first;
947 }
948
Tony-LunarG412b1b72020-07-15 10:30:13 -0600949 gp_cis->second.colorBlendStateCI =
950 cgpl_state->pCreateInfos[i].pColorBlendState
951 ? new safe_VkPipelineColorBlendStateCreateInfo(cgpl_state->pCreateInfos[i].pColorBlendState)
952 : nullptr;
953 gp_cis->second.depthStencilStateCI =
954 cgpl_state->pCreateInfos[i].pDepthStencilState
955 ? new safe_VkPipelineDepthStencilStateCreateInfo(cgpl_state->pCreateInfos[i].pDepthStencilState)
956 : nullptr;
Sam Walls0961ec02020-03-31 16:39:15 +0100957 }
958}
959
Camden5b184be2019-08-13 07:50:19 -0600960bool BestPractices::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount,
961 const VkComputePipelineCreateInfo* pCreateInfos,
Mark Lobodzinski2a162a02019-09-06 11:02:12 -0600962 const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines,
Jeff Bolz5c801d12019-10-09 10:38:45 -0500963 void* ccpl_state_data) const {
Mark Lobodzinski8317a3e2019-09-20 10:07:08 -0600964 bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, createInfoCount, pCreateInfos,
965 pAllocator, pPipelines, ccpl_state_data);
Camden5b184be2019-08-13 07:50:19 -0600966
967 if ((createInfoCount > 1) && (!pipelineCache)) {
Mark Lobodzinskif95a2662020-01-29 15:43:32 -0700968 skip |= LogPerformanceWarning(
969 device, kVUID_BestPractices_CreatePipelines_MultiplePipelines,
970 "Performance Warning: This vkCreateComputePipelines call is creating multiple pipelines but is not using a "
971 "pipeline cache, which may help with performance");
Camden5b184be2019-08-13 07:50:19 -0600972 }
973
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100974 if (VendorCheckEnabled(kBPVendorArm)) {
975 for (size_t i = 0; i < createInfoCount; i++) {
976 skip |= ValidateCreateComputePipelineArm(pCreateInfos[i]);
977 }
978 }
979
980 return skip;
981}
982
983bool BestPractices::ValidateCreateComputePipelineArm(const VkComputePipelineCreateInfo& createInfo) const {
984 bool skip = false;
985 auto* module = GetShaderModuleState(createInfo.stage.module);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800986 // Generate warnings about work group sizes based on active resources.
sfricke-samsung962cad92021-04-13 00:46:29 -0700987 auto entrypoint = module->FindEntrypoint(createInfo.stage.pName, createInfo.stage.stage);
sfricke-samsung8a7341a2021-02-28 07:30:21 -0800988 if (entrypoint == module->end()) return false;
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100989
990 uint32_t x = 1, y = 1, z = 1;
sfricke-samsung962cad92021-04-13 00:46:29 -0700991 module->FindLocalSize(entrypoint, x, y, z);
Sam Wallsd7ab6db2020-06-19 20:41:54 +0100992
993 uint32_t thread_count = x * y * z;
994
995 // Generate a priori warnings about work group sizes.
996 if (thread_count > kMaxEfficientWorkGroupThreadCountArm) {
997 skip |= LogPerformanceWarning(
998 device, kVUID_BestPractices_CreateComputePipelines_ComputeWorkGroupSize,
999 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, %u, "
1000 "%u) (%u threads total), has more threads than advised in a single work group. It is advised to use work "
1001 "groups with less than %u threads, especially when using barrier() or shared memory.",
1002 VendorSpecificTag(kBPVendorArm), x, y, z, thread_count, kMaxEfficientWorkGroupThreadCountArm);
1003 }
1004
1005 if (thread_count == 1 || ((x > 1) && (x & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1006 ((y > 1) && (y & (kThreadGroupDispatchCountAlignmentArm - 1))) ||
1007 ((z > 1) && (z & (kThreadGroupDispatchCountAlignmentArm - 1)))) {
1008 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeThreadGroupAlignment,
1009 "%s vkCreateComputePipelines(): compute shader with work group dimensions (%u, "
1010 "%u, %u) is not aligned to %u "
1011 "threads. On Arm Mali architectures, not aligning work group sizes to %u may "
1012 "leave threads idle on the shader "
1013 "core.",
1014 VendorSpecificTag(kBPVendorArm), x, y, z, kThreadGroupDispatchCountAlignmentArm,
1015 kThreadGroupDispatchCountAlignmentArm);
1016 }
1017
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001018 bool has_writeable_descriptors = false;
locke-lunarg63e4daf2020-08-17 17:53:25 -06001019 bool has_atomic_descriptors = false;
sfricke-samsung962cad92021-04-13 00:46:29 -07001020 auto accessible_ids = module->MarkAccessibleIds(entrypoint);
locke-lunarg63e4daf2020-08-17 17:53:25 -06001021 auto descriptor_uses =
sfricke-samsung962cad92021-04-13 00:46:29 -07001022 module->CollectInterfaceByDescriptorSlot(accessible_ids, &has_writeable_descriptors, &has_atomic_descriptors);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001023
1024 unsigned dimensions = 0;
1025 if (x > 1) dimensions++;
1026 if (y > 1) dimensions++;
1027 if (z > 1) dimensions++;
1028 // Here the dimension will really depend on the dispatch grid, but assume it's 1D.
1029 dimensions = std::max(dimensions, 1u);
1030
1031 // If we're accessing images, we almost certainly want to have a 2D workgroup for cache reasons.
1032 // There are some false positives here. We could simply have a shader that does this within a 1D grid,
1033 // or we may have a linearly tiled image, but these cases are quite unlikely in practice.
1034 bool accesses_2d = false;
1035 for (const auto& usage : descriptor_uses) {
sfricke-samsung962cad92021-04-13 00:46:29 -07001036 auto dim = module->GetShaderResourceDimensionality(usage.second);
Sam Wallsd7ab6db2020-06-19 20:41:54 +01001037 if (dim < 0) continue;
1038 auto spvdim = spv::Dim(dim);
1039 if (spvdim != spv::Dim1D && spvdim != spv::DimBuffer) accesses_2d = true;
1040 }
1041
1042 if (accesses_2d && dimensions < 2) {
1043 LogPerformanceWarning(device, kVUID_BestPractices_CreateComputePipelines_ComputeSpatialLocality,
1044 "%s vkCreateComputePipelines(): compute shader has work group dimensions (%u, %u, %u), which "
1045 "suggests a 1D dispatch, but the shader is accessing 2D or 3D images. The shader may be "
1046 "exhibiting poor spatial locality with respect to one or more shader resources.",
1047 VendorSpecificTag(kBPVendorArm), x, y, z);
1048 }
1049
Camden5b184be2019-08-13 07:50:19 -06001050 return skip;
1051}
1052
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001053bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags flags) const {
Camden5b184be2019-08-13 07:50:19 -06001054 bool skip = false;
1055
1056 if (flags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001057 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1058 "You are using VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001059 } else if (flags & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001060 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1061 "You are using VK_PIPELINE_STAGE_ALL_COMMANDS_BIT when %s is called\n", api_name.c_str());
Camden5b184be2019-08-13 07:50:19 -06001062 }
1063
1064 return skip;
1065}
1066
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001067bool BestPractices::CheckPipelineStageFlags(const std::string& api_name, VkPipelineStageFlags2KHR flags) const {
1068 bool skip = false;
1069
1070 if (flags & VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR) {
1071 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1072 "You are using VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR when %s is called\n", api_name.c_str());
1073 } else if (flags & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) {
1074 skip |= LogWarning(device, kVUID_BestPractices_PipelineStageFlags,
1075 "You are using VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR when %s is called\n", api_name.c_str());
1076 }
1077
1078 return skip;
1079}
1080
1081bool BestPractices::CheckDependencyInfo(const std::string& api_name, const VkDependencyInfoKHR& dep_info) const {
1082 bool skip = false;
1083 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
1084
1085 skip |= CheckPipelineStageFlags(api_name, stage_masks.src);
1086 skip |= CheckPipelineStageFlags(api_name, stage_masks.dst);
1087
1088 return skip;
1089}
1090
Mark Lobodzinski84101d72020-04-24 09:43:48 -06001091void BestPractices::ManualPostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* pPresentInfo, VkResult result) {
Mark Lobodzinski9b133c12020-03-10 10:42:56 -06001092 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) {
1093 auto swapchains_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result;
1094 if (swapchains_result == VK_SUBOPTIMAL_KHR) {
1095 LogPerformanceWarning(
1096 pPresentInfo->pSwapchains[i], kVUID_BestPractices_SuboptimalSwapchain,
1097 "vkQueuePresentKHR: %s :VK_SUBOPTIMAL_KHR was returned. VK_SUBOPTIMAL_KHR - Presentation will still succeed, "
1098 "subject to the window resize behavior, but the swapchain is no longer configured optimally for the surface it "
1099 "targets. Applications should query updated surface information and recreate their swapchain at the next "
1100 "convenient opportunity.",
1101 report_data->FormatHandle(pPresentInfo->pSwapchains[i]).c_str());
1102 }
1103 }
1104}
1105
Jeff Bolz5c801d12019-10-09 10:38:45 -05001106bool BestPractices::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits,
1107 VkFence fence) const {
Camden5b184be2019-08-13 07:50:19 -06001108 bool skip = false;
1109
1110 for (uint32_t submit = 0; submit < submitCount; submit++) {
1111 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreCount; semaphore++) {
1112 skip |= CheckPipelineStageFlags("vkQueueSubmit", pSubmits[submit].pWaitDstStageMask[semaphore]);
1113 }
1114 }
1115
1116 return skip;
1117}
1118
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001119bool BestPractices::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR* pSubmits,
1120 VkFence fence) const {
1121 bool skip = false;
1122
1123 for (uint32_t submit = 0; submit < submitCount; submit++) {
1124 for (uint32_t semaphore = 0; semaphore < pSubmits[submit].waitSemaphoreInfoCount; semaphore++) {
1125 skip |= CheckPipelineStageFlags("vkQueueSubmit2KHR", pSubmits[submit].pWaitSemaphoreInfos[semaphore].stageMask);
1126 }
1127 }
1128
1129 return skip;
1130}
1131
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001132bool BestPractices::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo,
1133 const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool) const {
1134 bool skip = false;
1135
1136 if (pCreateInfo->flags & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) {
1137 skip |= LogPerformanceWarning(
1138 device, kVUID_BestPractices_CreateCommandPool_CommandBufferReset,
1139 "vkCreateCommandPool(): VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT is set. Consider resetting entire "
1140 "pool instead.");
1141 }
1142
1143 return skip;
1144}
1145
1146bool BestPractices::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer,
1147 const VkCommandBufferBeginInfo* pBeginInfo) const {
1148 bool skip = false;
1149
1150 if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) {
1151 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_SimultaneousUse,
1152 "vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT is set.");
1153 }
1154
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001155 if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && VendorCheckEnabled(kBPVendorArm)) {
1156 skip |= LogPerformanceWarning(device, kVUID_BestPractices_BeginCommandBuffer_OneTimeSubmit,
Attilio Provenzano02859b22020-02-27 14:17:28 +00001157 "%s vkBeginCommandBuffer(): VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT is not set. "
1158 "For best performance on Mali GPUs, consider setting ONE_TIME_SUBMIT by default.",
1159 VendorSpecificTag(kBPVendorArm));
1160 }
1161
Attilio Provenzano746e43e2020-02-27 11:23:50 +00001162 return skip;
1163}
1164
Jeff Bolz5c801d12019-10-09 10:38:45 -05001165bool BestPractices::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001166 bool skip = false;
1167
1168 skip |= CheckPipelineStageFlags("vkCmdSetEvent", stageMask);
1169
1170 return skip;
1171}
1172
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001173bool BestPractices::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1174 const VkDependencyInfoKHR* pDependencyInfo) const {
1175 return CheckDependencyInfo("vkCmdSetEvent2KHR", *pDependencyInfo);
1176}
1177
Jeff Bolz5c801d12019-10-09 10:38:45 -05001178bool BestPractices::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
1179 VkPipelineStageFlags stageMask) const {
Camden5b184be2019-08-13 07:50:19 -06001180 bool skip = false;
1181
1182 skip |= CheckPipelineStageFlags("vkCmdResetEvent", stageMask);
1183
1184 return skip;
1185}
1186
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001187bool BestPractices::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
1188 VkPipelineStageFlags2KHR stageMask) const {
1189 bool skip = false;
1190
1191 skip |= CheckPipelineStageFlags("vkCmdResetEvent2KHR", stageMask);
1192
1193 return skip;
1194}
1195
Camden5b184be2019-08-13 07:50:19 -06001196bool BestPractices::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1197 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
1198 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1199 uint32_t bufferMemoryBarrierCount,
1200 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1201 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001202 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001203 bool skip = false;
1204
1205 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", srcStageMask);
1206 skip |= CheckPipelineStageFlags("vkCmdWaitEvents", dstStageMask);
1207
1208 return skip;
1209}
1210
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001211bool BestPractices::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents,
1212 const VkDependencyInfoKHR* pDependencyInfos) const {
1213 bool skip = false;
1214 for (uint32_t i = 0; i < eventCount; i++) {
1215 skip = CheckDependencyInfo("vkCmdWaitEvents2KHR", pDependencyInfos[i]);
1216 }
1217
1218 return skip;
1219}
1220
Camden5b184be2019-08-13 07:50:19 -06001221bool BestPractices::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
1222 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
1223 uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers,
1224 uint32_t bufferMemoryBarrierCount,
1225 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1226 uint32_t imageMemoryBarrierCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001227 const VkImageMemoryBarrier* pImageMemoryBarriers) const {
Camden5b184be2019-08-13 07:50:19 -06001228 bool skip = false;
1229
1230 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", srcStageMask);
1231 skip |= CheckPipelineStageFlags("vkCmdPipelineBarrier", dstStageMask);
1232
1233 return skip;
1234}
1235
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001236bool BestPractices::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
1237 const VkDependencyInfoKHR* pDependencyInfo) const {
1238 return CheckDependencyInfo("vkCmdPipelineBarrier2KHR", *pDependencyInfo);
1239}
1240
Camden5b184be2019-08-13 07:50:19 -06001241bool BestPractices::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001242 VkQueryPool queryPool, uint32_t query) const {
Camden5b184be2019-08-13 07:50:19 -06001243 bool skip = false;
1244
Jeremy Gebbena3705f42021-01-19 16:47:43 -07001245 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp", static_cast<VkPipelineStageFlags>(pipelineStage));
1246
1247 return skip;
1248}
1249
1250bool BestPractices::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
1251 VkQueryPool queryPool, uint32_t query) const {
1252 bool skip = false;
1253
1254 skip |= CheckPipelineStageFlags("vkCmdWriteTimestamp2KHR", pipelineStage);
Camden5b184be2019-08-13 07:50:19 -06001255
1256 return skip;
1257}
1258
Sam Walls0961ec02020-03-31 16:39:15 +01001259void BestPractices::PostCallRecordCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint,
1260 VkPipeline pipeline) {
1261 StateTracker::PostCallRecordCmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1262
1263 if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) {
1264 // check for depth/blend state tracking
1265 auto gp_cis = graphicsPipelineCIs.find(pipeline);
1266 if (gp_cis != graphicsPipelineCIs.end()) {
1267 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1268 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001269 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001270
1271 if (!result.second) return;
1272
1273 prepass_state = result.first;
1274 }
1275
1276 const auto* blend_state = gp_cis->second.colorBlendStateCI;
1277 const auto* stencil_state = gp_cis->second.depthStencilStateCI;
1278
1279 if (blend_state) {
1280 // assume the pipeline is depth-only unless any of the attachments have color writes enabled
1281 prepass_state->second.depthOnly = true;
1282 for (size_t i = 0; i < blend_state->attachmentCount; i++) {
1283 if (blend_state->pAttachments[i].colorWriteMask != 0) {
1284 prepass_state->second.depthOnly = false;
1285 }
1286 }
1287 }
1288
1289 // check for depth value usage
1290 prepass_state->second.depthEqualComparison = false;
1291
1292 if (stencil_state && stencil_state->depthTestEnable) {
1293 switch (stencil_state->depthCompareOp) {
1294 case VK_COMPARE_OP_EQUAL:
1295 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1296 case VK_COMPARE_OP_LESS_OR_EQUAL:
1297 prepass_state->second.depthEqualComparison = true;
1298 break;
1299 default:
1300 break;
1301 }
1302 }
1303 } else {
1304 // reset depth pre-pass tracking
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001305 cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001306 }
1307 }
1308}
1309
Attilio Provenzano02859b22020-02-27 14:17:28 +00001310static inline bool RenderPassUsesAttachmentOnTile(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1311 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001312 const auto& subpass_info = createInfo.pSubpasses[subpass];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001313
1314 // If an attachment is ever used as a color attachment,
1315 // resolve attachment or depth stencil attachment,
1316 // it needs to exist on tile at some point.
1317
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001318 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1319 if (subpass_info.pColorAttachments[i].attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001320 }
1321
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001322 if (subpass_info.pResolveAttachments) {
1323 for (uint32_t i = 0; i < subpass_info.colorAttachmentCount; i++) {
1324 if (subpass_info.pResolveAttachments[i].attachment == attachment) return true;
1325 }
1326 }
1327
1328 if (subpass_info.pDepthStencilAttachment && subpass_info.pDepthStencilAttachment->attachment == attachment) return true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001329 }
1330
1331 return false;
1332}
1333
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001334static inline bool RenderPassUsesAttachmentAsImageOnly(const safe_VkRenderPassCreateInfo2& createInfo, uint32_t attachment) {
1335 if (RenderPassUsesAttachmentOnTile(createInfo, attachment)) {
1336 return false;
1337 }
1338
1339 for (uint32_t subpass = 0; subpass < createInfo.subpassCount; subpass++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001340 const auto& subpassInfo = createInfo.pSubpasses[subpass];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001341
1342 for (uint32_t i = 0; i < subpassInfo.inputAttachmentCount; i++) {
1343 if (subpassInfo.pInputAttachments[i].attachment == attachment) {
1344 return true;
1345 }
1346 }
1347 }
1348
1349 return false;
1350}
1351
Attilio Provenzano02859b22020-02-27 14:17:28 +00001352bool BestPractices::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1353 const VkRenderPassBeginInfo* pRenderPassBegin) const {
1354 bool skip = false;
1355
1356 if (!pRenderPassBegin) {
1357 return skip;
1358 }
1359
1360 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1361 if (rp_state) {
Mike Schuchardt2df08912020-12-15 16:28:09 -08001362 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
Mark Lobodzinski1f887d32020-12-30 15:31:33 -07001363 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
Tony-LunarG767180f2020-04-23 14:03:59 -06001364 if (rpabi) {
1365 skip = ValidateAttachments(rp_state->createInfo.ptr(), rpabi->attachmentCount, rpabi->pAttachments);
1366 }
1367 }
Attilio Provenzano02859b22020-02-27 14:17:28 +00001368 // Check if any attachments have LOAD operation on them
1369 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001370 const auto& attachment = rp_state->createInfo.pAttachments[att];
Attilio Provenzano02859b22020-02-27 14:17:28 +00001371
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001372 bool attachment_has_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001373 if (!FormatHasStencil(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001374 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001375 }
1376
1377 if (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001378 attachment_has_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001379 }
1380
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001381 bool attachment_needs_readback = false;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001382
1383 // Check if the attachment is actually used in any subpass on-tile
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001384 if (attachment_has_readback && RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1385 attachment_needs_readback = true;
Attilio Provenzano02859b22020-02-27 14:17:28 +00001386 }
1387
1388 // Using LOAD_OP_LOAD is expensive on tiled GPUs, so flag it as a potential improvement
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001389 if (attachment_needs_readback && VendorCheckEnabled(kBPVendorArm)) {
1390 skip |= LogPerformanceWarning(
1391 device, kVUID_BestPractices_BeginRenderPass_AttachmentNeedsReadback,
1392 "%s Attachment #%u in render pass has begun with VK_ATTACHMENT_LOAD_OP_LOAD.\n"
1393 "Submitting this renderpass will cause the driver to inject a readback of the attachment "
1394 "which will copy in total %u pixels (renderArea = { %d, %d, %u, %u }) to the tile buffer.",
1395 VendorSpecificTag(kBPVendorArm), att,
1396 pRenderPassBegin->renderArea.extent.width * pRenderPassBegin->renderArea.extent.height,
1397 pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y,
1398 pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001399 }
1400 }
1401 }
1402
1403 return skip;
1404}
1405
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001406void BestPractices::QueueValidateImageView(QueueCallbacks &funcs, const char* function_name,
1407 IMAGE_VIEW_STATE* view, IMAGE_SUBRESOURCE_USAGE_BP usage) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001408 if (view) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001409 QueueValidateImage(funcs, function_name, GetImageUsageState(view->create_info.image), usage, view->create_info.subresourceRange);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001410 }
1411}
1412
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001413void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1414 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001415 const VkImageSubresourceRange& subresource_range) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001416 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001417
1418 // If we're viewing a 3D slice, ignore base array layer.
1419 // The entire 3D subresource is accessed as one atomic unit.
1420 const uint32_t base_array_layer = image->createInfo.imageType == VK_IMAGE_TYPE_3D ? 0 : subresource_range.baseArrayLayer;
1421
1422 const uint32_t max_layers = image->createInfo.arrayLayers - base_array_layer;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001423 const uint32_t array_layers = std::min(subresource_range.layerCount, max_layers);
1424 const uint32_t max_levels = image->createInfo.mipLevels - subresource_range.baseMipLevel;
1425 const uint32_t mip_levels = std::min(image->createInfo.mipLevels, max_levels);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001426
1427 for (uint32_t layer = 0; layer < array_layers; layer++) {
1428 for (uint32_t level = 0; level < mip_levels; level++) {
Hans-Kristian Arntzen93264202021-05-21 17:07:46 +02001429 QueueValidateImage(funcs, function_name, state, usage, layer + base_array_layer,
1430 level + subresource_range.baseMipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001431 }
1432 }
1433}
1434
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001435void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1436 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001437 const VkImageSubresourceLayers& subresource_layers) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001438 IMAGE_STATE* image = state->image;
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001439 const uint32_t max_layers = image->createInfo.arrayLayers - subresource_layers.baseArrayLayer;
1440 const uint32_t array_layers = std::min(subresource_layers.layerCount, max_layers);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001441
1442 for (uint32_t layer = 0; layer < array_layers; layer++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001443 QueueValidateImage(funcs, function_name, state, usage, layer + subresource_layers.baseArrayLayer, subresource_layers.mipLevel);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001444 }
1445}
1446
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001447void BestPractices::QueueValidateImage(QueueCallbacks &funcs, const char* function_name,
1448 IMAGE_STATE_BP* state, IMAGE_SUBRESOURCE_USAGE_BP usage,
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001449 uint32_t array_layer, uint32_t mip_level) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001450 funcs.push_back([this, function_name, state, usage, array_layer, mip_level](const ValidationStateTracker*, const QUEUE_STATE*) -> bool {
1451 ValidateImageInQueue(function_name, state, usage, array_layer, mip_level);
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001452 return false;
1453 });
1454}
1455
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001456void BestPractices::ValidateImageInQueueArm(const char* function_name, IMAGE_STATE* image,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001457 IMAGE_SUBRESOURCE_USAGE_BP last_usage,
1458 IMAGE_SUBRESOURCE_USAGE_BP usage,
1459 uint32_t array_layer, uint32_t mip_level) {
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001460 // Swapchain images are implicitly read so clear after store is expected.
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001461 if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED && last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED &&
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001462 !image->is_swapchain_image) {
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001463 LogPerformanceWarning(
1464 device, kVUID_BestPractices_RenderPass_RedundantStore,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001465 "%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 +02001466 "image was used, it was written to with STORE_OP_STORE. "
1467 "Storing to the image is probably redundant in this case, and wastes bandwidth on tile-based "
1468 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001469 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001470 } 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 +02001471 LogPerformanceWarning(
1472 device, kVUID_BestPractices_RenderPass_RedundantClear,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001473 "%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 +02001474 "image was used, it was written to with vkCmdClear*Image(). "
1475 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1476 "tile-based architectures."
1477 "architectures.",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001478 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level);
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001479 } else if (usage == IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE &&
1480 (last_usage == IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE ||
1481 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::CLEARED ||
1482 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE ||
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001483 last_usage == IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE)) {
Hans-Kristian Arntzen44f9d862021-03-22 13:56:39 +01001484 const char *last_cmd = nullptr;
1485 const char *vuid = nullptr;
1486 const char *suggestion = nullptr;
1487
1488 switch (last_usage) {
1489 case IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE:
1490 vuid = kVUID_BestPractices_RenderPass_BlitImage_LoadOpLoad;
1491 last_cmd = "vkCmdBlitImage";
1492 suggestion =
1493 "The blit is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1494 "Rather than blitting, just render the source image in a fragment shader in this render pass, "
1495 "which avoids the memory roundtrip.";
1496 break;
1497 case IMAGE_SUBRESOURCE_USAGE_BP::CLEARED:
1498 vuid = kVUID_BestPractices_RenderPass_InefficientClear;
1499 last_cmd = "vkCmdClear*Image";
1500 suggestion =
1501 "Clearing the image with vkCmdClear*Image() is probably redundant in this case, and wastes bandwidth on "
1502 "tile-based architectures. "
1503 "Use LOAD_OP_CLEAR instead to clear the image for free.";
1504 break;
1505 case IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE:
1506 vuid = kVUID_BestPractices_RenderPass_CopyImage_LoadOpLoad;
1507 last_cmd = "vkCmdCopy*Image";
1508 suggestion =
1509 "The copy is probably redundant in this case, and wastes bandwidth on tile-based architectures. "
1510 "Rather than copying, just render the source image in a fragment shader in this render pass, "
1511 "which avoids the memory roundtrip.";
1512 break;
1513 case IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE:
1514 vuid = kVUID_BestPractices_RenderPass_ResolveImage_LoadOpLoad;
1515 last_cmd = "vkCmdResolveImage";
1516 suggestion =
1517 "The resolve is probably redundant in this case, and wastes a lot of bandwidth on tile-based architectures. "
1518 "Rather than resolving, and then loading, try to keep rendering in the same render pass, "
1519 "which avoids the memory roundtrip.";
1520 break;
1521 default:
1522 break;
1523 }
1524
1525 LogPerformanceWarning(
1526 device, vuid,
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001527 "%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 +01001528 "time image was used, it was written to with %s. %s",
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001529 function_name, VendorSpecificTag(kBPVendorArm), array_layer, mip_level, last_cmd, suggestion);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001530 }
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001531}
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001532
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001533void BestPractices::ValidateImageInQueue(const char* function_name, IMAGE_STATE_BP* state,
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001534 IMAGE_SUBRESOURCE_USAGE_BP usage, uint32_t array_layer,
1535 uint32_t mip_level) {
1536 IMAGE_STATE* image = state->image;
1537 IMAGE_SUBRESOURCE_USAGE_BP last_usage = state->usages[array_layer][mip_level];
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001538 state->usages[array_layer][mip_level] = usage;
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001539 if (VendorCheckEnabled(kBPVendorArm)) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001540 ValidateImageInQueueArm(function_name, image, last_usage, usage, array_layer, mip_level);
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001541 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001542}
1543
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001544void BestPractices::AddDeferredQueueOperations(CMD_BUFFER_STATE* cb) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001545 cb->queue_submit_functions.insert(cb->queue_submit_functions.end(),
1546 queue_submit_functions_after_render_pass.begin(),
1547 queue_submit_functions_after_render_pass.end());
1548 queue_submit_functions_after_render_pass.clear();
1549}
1550
1551void BestPractices::PreCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
1552 ValidationStateTracker::PreCallRecordCmdEndRenderPass(commandBuffer);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001553 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001554}
1555
1556void BestPractices::PreCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassInfo) {
1557 ValidationStateTracker::PreCallRecordCmdEndRenderPass2(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001558 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001559}
1560
1561void BestPractices::PreCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassInfo) {
1562 ValidationStateTracker::PreCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassInfo);
Hans-Kristian Arntzenb8336ad2021-04-28 14:54:09 +02001563 AddDeferredQueueOperations(GetCBState(commandBuffer));
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001564}
1565
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001566void BestPractices::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1567 VkSubpassContents contents) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001568 ValidationStateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1569
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001570 if (!pRenderPassBegin) {
1571 return;
1572 }
1573
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01001574 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
1575
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001576 auto rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
1577 if (rp_state) {
1578 // Check load ops
1579 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001580 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001581
1582 if (!RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att) &&
1583 !RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1584 continue;
1585 }
1586
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001587 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::UNDEFINED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001588
1589 if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) ||
1590 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001591 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_READ_TO_TILE;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001592 } else if ((!FormatIsStencilOnly(attachment.format) && attachment.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) ||
1593 (FormatHasStencil(attachment.format) && attachment.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001594 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_CLEARED;
Hans-Kristian Arntzen5e56e552021-03-29 11:45:20 +02001595 } else if (RenderPassUsesAttachmentAsImageOnly(rp_state->createInfo, att)) {
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01001596 usage = IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001597 }
1598
1599 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001600 IMAGE_VIEW_STATE* image_view = nullptr;
1601
1602 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1603 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1604 if (rpabi) {
1605 image_view = GetImageViewState(rpabi->pAttachments[att]);
1606 }
1607 } else {
1608 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1609 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001610
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001611 QueueValidateImageView(cb->queue_submit_functions, "vkCmdBeginRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001612 }
1613
1614 // Check store ops
1615 for (uint32_t att = 0; att < rp_state->createInfo.attachmentCount; att++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02001616 const auto& attachment = rp_state->createInfo.pAttachments[att];
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001617
1618 if (!RenderPassUsesAttachmentOnTile(rp_state->createInfo, att)) {
1619 continue;
1620 }
1621
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001622 IMAGE_SUBRESOURCE_USAGE_BP usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_DISCARDED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001623
1624 if ((!FormatIsStencilOnly(attachment.format) && attachment.storeOp == VK_ATTACHMENT_STORE_OP_STORE) ||
1625 (FormatHasStencil(attachment.format) && attachment.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE)) {
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01001626 usage = IMAGE_SUBRESOURCE_USAGE_BP::RENDER_PASS_STORED;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001627 }
1628
1629 auto framebuffer = GetFramebufferState(pRenderPassBegin->framebuffer);
Hans-Kristian Arntzen9710e142021-03-18 12:19:02 +01001630
1631 IMAGE_VIEW_STATE* image_view = nullptr;
1632 if (rp_state->createInfo.flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) {
1633 const VkRenderPassAttachmentBeginInfo* rpabi = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBegin->pNext);
1634 if (rpabi) {
1635 image_view = GetImageViewState(rpabi->pAttachments[att]);
1636 }
1637 } else {
1638 image_view = GetImageViewState(framebuffer->createInfo.pAttachments[att]);
1639 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001640
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001641 QueueValidateImageView(queue_submit_functions_after_render_pass, "vkCmdEndRenderPass()", image_view, usage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001642 }
1643 }
1644}
1645
Attilio Provenzano02859b22020-02-27 14:17:28 +00001646bool BestPractices::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1647 VkSubpassContents contents) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001648 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1649 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001650 return skip;
1651}
1652
1653bool BestPractices::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1654 const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001655 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001656 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1657 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001658 return skip;
1659}
1660
1661bool BestPractices::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08001662 const VkSubpassBeginInfo* pSubpassBeginInfo) const {
Sam Walls0961ec02020-03-31 16:39:15 +01001663 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1664 skip |= ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
Attilio Provenzano02859b22020-02-27 14:17:28 +00001665 return skip;
1666}
1667
Sam Walls0961ec02020-03-31 16:39:15 +01001668void BestPractices::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version,
1669 const VkRenderPassBeginInfo* pRenderPassBegin) {
1670 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
1671
1672 // add the tracking state if it doesn't exist
1673 if (prepass_state == cbDepthPrePassStates.end()) {
Jeremy Gebbencbf22862021-03-03 12:01:22 -07001674 auto result = cbDepthPrePassStates.emplace(commandBuffer, DepthPrePassState{});
Sam Walls0961ec02020-03-31 16:39:15 +01001675
1676 if (!result.second) return;
1677
1678 prepass_state = result.first;
1679 }
1680
1681 // reset the renderpass state
1682 prepass_state->second = {};
1683
Hans-Kristian Arntzena1a92cc2021-03-17 13:09:33 +01001684 const auto* rp_state = GetRenderPassState(pRenderPassBegin->renderPass);
Sam Walls0961ec02020-03-31 16:39:15 +01001685
1686 // track depth / color attachment usage within the renderpass
1687 for (size_t i = 0; i < rp_state->createInfo.subpassCount; i++) {
1688 // record if depth/color attachments are in use for this renderpass
1689 if (rp_state->createInfo.pSubpasses[i].pDepthStencilAttachment != nullptr) prepass_state->second.depthAttachment = true;
1690
1691 if (rp_state->createInfo.pSubpasses[i].colorAttachmentCount > 0) prepass_state->second.colorAttachment = true;
1692 }
1693}
1694
1695void BestPractices::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1696 VkSubpassContents contents) {
1697 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
1698 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin);
1699}
1700
1701void BestPractices::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin,
1702 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1703 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1704 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1705}
1706
1707void BestPractices::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
1708 const VkRenderPassBeginInfo* pRenderPassBegin,
1709 const VkSubpassBeginInfo* pSubpassBeginInfo) {
1710 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
1711 RecordCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin);
1712}
1713
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001714// Generic function to handle validation for all CmdDraw* type functions
1715bool BestPractices::ValidateCmdDrawType(VkCommandBuffer cmd_buffer, const char* caller) const {
1716 bool skip = false;
1717 const CMD_BUFFER_STATE* cb_state = GetCBState(cmd_buffer);
1718 if (cb_state) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001719 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1720 const auto* pipeline_state = cb_state->lastBound[lv_bind_point].pipeline_state;
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001721 const auto& current_vtx_bfr_binding_info = cb_state->current_vertex_buffer_binding_info.vertex_buffer_bindings;
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001722
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001723 // Verify vertex binding
1724 if (pipeline_state->vertex_binding_descriptions_.size() <= 0) {
1725 if ((!current_vtx_bfr_binding_info.empty()) && (!cb_state->vertex_buffer_used)) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001726 skip |= LogPerformanceWarning(cb_state->commandBuffer(), kVUID_BestPractices_DrawState_VtxIndexOutOfBounds,
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07001727 "Vertex buffers are bound to %s but no vertex buffers are attached to %s.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001728 report_data->FormatHandle(cb_state->commandBuffer()).c_str(),
1729 report_data->FormatHandle(pipeline_state->pipeline()).c_str());
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001730 }
1731 }
1732 }
1733 return skip;
1734}
1735
Sam Walls0961ec02020-03-31 16:39:15 +01001736void BestPractices::RecordCmdDrawType(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1737 if (VendorCheckEnabled(kBPVendorArm)) {
1738 RecordCmdDrawTypeArm(cmd_buffer, draw_count, caller);
1739 }
1740}
1741
1742void BestPractices::RecordCmdDrawTypeArm(VkCommandBuffer cmd_buffer, uint32_t draw_count, const char* caller) {
1743 auto prepass_state = cbDepthPrePassStates.find(cmd_buffer);
1744 if (prepass_state != cbDepthPrePassStates.end() && draw_count >= kDepthPrePassMinDrawCountArm) {
1745 if (prepass_state->second.depthOnly) prepass_state->second.numDrawCallsDepthOnly++;
1746
1747 if (prepass_state->second.depthEqualComparison) prepass_state->second.numDrawCallsDepthEqualCompare++;
1748 }
1749}
1750
Camden5b184be2019-08-13 07:50:19 -06001751bool BestPractices::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001752 uint32_t firstVertex, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001753 bool skip = false;
1754
1755 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001756 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1757 "Warning: You are calling vkCmdDraw() with an instanceCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001758 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDraw()");
Camden5b184be2019-08-13 07:50:19 -06001759 }
1760
1761 return skip;
1762}
1763
Sam Walls0961ec02020-03-31 16:39:15 +01001764void BestPractices::PostCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
1765 uint32_t firstVertex, uint32_t firstInstance) {
1766 StateTracker::PostCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
1767 RecordCmdDrawType(commandBuffer, vertexCount * instanceCount, "vkCmdDraw()");
1768}
1769
Camden5b184be2019-08-13 07:50:19 -06001770bool BestPractices::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001771 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
Camden5b184be2019-08-13 07:50:19 -06001772 bool skip = false;
1773
1774 if (instanceCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07001775 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_InstanceCountZero,
1776 "Warning: You are calling vkCmdDrawIndexed() with an instanceCount of Zero.");
Camden5b184be2019-08-13 07:50:19 -06001777 }
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001778 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexed()");
1779
Attilio Provenzano02859b22020-02-27 14:17:28 +00001780 // Check if we reached the limit for small indexed draw calls.
1781 // Note that we cannot update the draw call count here, so we do it in PreCallRecordCmdDrawIndexed.
1782 const CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1783 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices &&
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02001784 (cmd_state->small_indexed_draw_call_count == kMaxSmallIndexedDrawcalls - 1) &&
1785 VendorCheckEnabled(kBPVendorArm)) {
1786 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_ManySmallIndexedDrawcalls,
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06001787 "%s: The command buffer contains many small indexed drawcalls "
Attilio Provenzano02859b22020-02-27 14:17:28 +00001788 "(at least %u drawcalls with less than %u indices each). This may cause pipeline bubbles. "
1789 "You can try batching drawcalls or instancing when applicable.",
1790 VendorSpecificTag(kBPVendorArm), kMaxSmallIndexedDrawcalls, kSmallIndexedDrawcallIndices);
1791 }
1792
Sam Walls8e77e4f2020-03-16 20:47:40 +00001793 if (VendorCheckEnabled(kBPVendorArm)) {
1794 ValidateIndexBufferArm(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1795 }
1796
1797 return skip;
1798}
1799
1800bool BestPractices::ValidateIndexBufferArm(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1801 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
1802 bool skip = false;
1803
1804 // check for sparse/underutilised index buffer, and post-transform cache thrashing
1805 const auto* cmd_state = GetCBState(commandBuffer);
1806 if (cmd_state == nullptr) return skip;
1807
locke-lunarg1ae57d62020-11-18 10:49:19 -07001808 const auto* ib_state = cmd_state->index_buffer_binding.buffer_state.get();
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06001809 if (ib_state == nullptr || cmd_state->index_buffer_binding.buffer_state->Destroyed()) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001810
1811 const VkIndexType ib_type = cmd_state->index_buffer_binding.index_type;
1812 const auto& ib_mem_state = *ib_state->binding.mem_state;
1813 const VkDeviceSize ib_mem_offset = ib_mem_state.mapped_range.offset;
1814 const void* ib_mem = ib_mem_state.p_driver_data;
1815 bool primitive_restart_enable = false;
1816
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001817 const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS);
1818 const auto& pipeline_binding_iter = cmd_state->lastBound[lv_bind_point];
1819 const auto* pipeline_state = pipeline_binding_iter.pipeline_state;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001820
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001821 if (pipeline_state != nullptr && pipeline_state->graphicsPipelineCI.pInputAssemblyState != nullptr) {
locke-lunargb8d7a7a2020-10-25 16:01:52 -06001822 primitive_restart_enable = pipeline_state->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001823 }
Sam Walls8e77e4f2020-03-16 20:47:40 +00001824
1825 // 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 -06001826 if (ib_mem && pipeline_binding_iter.IsUsing()) {
Sam Walls8e77e4f2020-03-16 20:47:40 +00001827 uint32_t scan_stride;
1828 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1829 scan_stride = sizeof(uint8_t);
1830 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1831 scan_stride = sizeof(uint16_t);
1832 } else {
1833 scan_stride = sizeof(uint32_t);
1834 }
1835
1836 const uint8_t* scan_begin = static_cast<const uint8_t*>(ib_mem) + ib_mem_offset + firstIndex * scan_stride;
1837 const uint8_t* scan_end = scan_begin + indexCount * scan_stride;
1838
1839 // Min and max are important to track for some Mali architectures. In older Mali devices without IDVS, all
1840 // vertices corresponding to indices between the minimum and maximum may be loaded, and possibly shaded,
1841 // irrespective of whether or not they're part of the draw call.
1842
1843 // start with minimum as 0xFFFFFFFF and adjust to indices in the buffer
1844 uint32_t min_index = ~0u;
1845 // start with maximum as 0 and adjust to indices in the buffer
1846 uint32_t max_index = 0u;
1847
1848 // first scan-through, we're looking to simulate a model LRU post-transform cache, estimating the number of vertices shaded
1849 // for the given index buffer
1850 uint32_t vertex_shade_count = 0;
1851
1852 PostTransformLRUCacheModel post_transform_cache;
1853
1854 // The size of the cache being modelled positively correlates with how much behaviour it can capture about
1855 // arbitrary ground-truth hardware/architecture cache behaviour. I.e. it's a good solution when we don't know the
1856 // target architecture.
1857 // However, modelling a post-transform cache with more than 32 elements gives diminishing returns in practice.
1858 // http://eelpi.gotdns.org/papers/fast_vert_cache_opt.html
1859 post_transform_cache.resize(32);
1860
1861 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1862 uint32_t scan_index;
1863 uint32_t primitive_restart_value;
1864 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1865 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1866 primitive_restart_value = 0xFF;
1867 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1868 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1869 primitive_restart_value = 0xFFFF;
1870 } else {
1871 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1872 primitive_restart_value = 0xFFFFFFFF;
1873 }
1874
1875 max_index = std::max(max_index, scan_index);
1876 min_index = std::min(min_index, scan_index);
1877
1878 if (!primitive_restart_enable || scan_index != primitive_restart_value) {
1879 bool in_cache = post_transform_cache.query_cache(scan_index);
1880 // if the shaded vertex corresponding to the index is not in the PT-cache, we need to shade again
1881 if (!in_cache) vertex_shade_count++;
1882 }
1883 }
1884
1885 // 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 +01001886 // 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
1887 if (max_index < min_index || max_index == min_index) return skip;
Sam Walls8e77e4f2020-03-16 20:47:40 +00001888
1889 if (max_index - min_index >= indexCount) {
Mark Young0ec6b062020-11-19 15:32:17 -07001890 skip |=
1891 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1892 "%s The indices which were specified for the draw call only utilise approximately %.02f%% of "
1893 "index buffer value range. Arm Mali architectures before G71 do not have IDVS (Index-Driven "
1894 "Vertex Shading), meaning all vertices corresponding to indices between the minimum and "
1895 "maximum would be loaded, and possibly shaded, whether or not they are used.",
1896 VendorSpecificTag(kBPVendorArm),
1897 (static_cast<float>(indexCount) / static_cast<float>(max_index - min_index)) * 100.0f);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001898 return skip;
1899 }
1900
1901 // use a dynamic vector of bitsets as a memory-compact representation of which indices are included in the draw call
1902 // 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 +01001903 const size_t refs_per_bucket = 64;
1904 std::vector<std::bitset<refs_per_bucket>> vertex_reference_buckets;
1905
1906 const uint32_t n_indices = max_index - min_index + 1;
1907 const uint32_t n_buckets = (n_indices / static_cast<uint32_t>(refs_per_bucket)) +
1908 ((n_indices % static_cast<uint32_t>(refs_per_bucket)) != 0 ? 1 : 0);
1909
1910 // there needs to be at least one bitset to store a set of indices smaller than n_buckets
1911 vertex_reference_buckets.resize(std::max(1u, n_buckets));
Sam Walls8e77e4f2020-03-16 20:47:40 +00001912
1913 // To avoid using too much memory, we run over the indices again.
1914 // Knowing the size from the last scan allows us to record index usage with bitsets
1915 for (const uint8_t* scan_ptr = scan_begin; scan_ptr < scan_end; scan_ptr += scan_stride) {
1916 uint32_t scan_index;
1917 if (ib_type == VK_INDEX_TYPE_UINT8_EXT) {
1918 scan_index = *reinterpret_cast<const uint8_t*>(scan_ptr);
1919 } else if (ib_type == VK_INDEX_TYPE_UINT16) {
1920 scan_index = *reinterpret_cast<const uint16_t*>(scan_ptr);
1921 } else {
1922 scan_index = *reinterpret_cast<const uint32_t*>(scan_ptr);
1923 }
1924 // keep track of the set of all indices used to reference vertices in the draw call
1925 size_t index_offset = scan_index - min_index;
Sam Walls61b06892020-07-23 16:20:50 +01001926 size_t bitset_bucket_index = index_offset / refs_per_bucket;
1927 uint64_t used_indices = 1ull << ((index_offset % refs_per_bucket) & 0xFFFFFFFFu);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001928 vertex_reference_buckets[bitset_bucket_index] |= used_indices;
1929 }
1930
1931 uint32_t vertex_reference_count = 0;
1932 for (const auto& bitset : vertex_reference_buckets) {
1933 vertex_reference_count += static_cast<uint32_t>(bitset.count());
1934 }
1935
1936 // 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 -07001937 float utilization = static_cast<float>(vertex_reference_count) / static_cast<float>(max_index - min_index + 1);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001938 // 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 -07001939 float cache_hit_rate = static_cast<float>(vertex_reference_count) / static_cast<float>(vertex_shade_count);
Sam Walls8e77e4f2020-03-16 20:47:40 +00001940
1941 if (utilization < 0.5f) {
1942 skip |= LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_SparseIndexBuffer,
1943 "%s The indices which were specified for the draw call only utilise approximately "
1944 "%.02f%% of the bound vertex buffer.",
1945 VendorSpecificTag(kBPVendorArm), utilization);
1946 }
1947
1948 if (cache_hit_rate <= 0.5f) {
1949 skip |=
1950 LogPerformanceWarning(device, kVUID_BestPractices_CmdDrawIndexed_PostTransformCacheThrashing,
1951 "%s The indices which were specified for the draw call are estimated to cause thrashing of "
1952 "the post-transform vertex cache, with a hit-rate of %.02f%%. "
1953 "I.e. the ordering of the index buffer may not make optimal use of indices associated with "
1954 "recently shaded vertices.",
1955 VendorSpecificTag(kBPVendorArm), cache_hit_rate * 100.0f);
1956 }
1957 }
1958
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001959 return skip;
1960}
1961
Attilio Provenzano02859b22020-02-27 14:17:28 +00001962void BestPractices::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1963 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1964 ValidationStateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset,
1965 firstInstance);
1966
1967 CMD_BUFFER_STATE* cmd_state = GetCBState(commandBuffer);
1968 if ((indexCount * instanceCount) <= kSmallIndexedDrawcallIndices) {
1969 cmd_state->small_indexed_draw_call_count++;
1970 }
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01001971
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02001972 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexed()");
Attilio Provenzano02859b22020-02-27 14:17:28 +00001973}
1974
Sam Walls0961ec02020-03-31 16:39:15 +01001975void BestPractices::PostCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
1976 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
1977 StateTracker::PostCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
1978 RecordCmdDrawType(commandBuffer, indexCount * instanceCount, "vkCmdDrawIndexed()");
1979}
1980
sfricke-samsung681ab7b2020-10-29 01:53:35 -07001981bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
1982 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
1983 uint32_t maxDrawCount, uint32_t stride) const {
1984 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCount()");
1985
1986 return skip;
1987}
1988
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07001989bool BestPractices::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
1990 VkDeviceSize offset, VkBuffer countBuffer,
1991 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
1992 uint32_t stride) const {
1993 bool skip = ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirectCountKHR()");
Camden5b184be2019-08-13 07:50:19 -06001994
1995 return skip;
1996}
1997
1998bool BestPractices::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05001999 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002000 bool skip = false;
2001
2002 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002003 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2004 "Warning: You are calling vkCmdDrawIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002005 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002006 }
2007
2008 return skip;
2009}
2010
Sam Walls0961ec02020-03-31 16:39:15 +01002011void BestPractices::PostCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2012 uint32_t count, uint32_t stride) {
2013 StateTracker::PostCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, count, stride);
2014 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndirect()");
2015}
2016
Camden5b184be2019-08-13 07:50:19 -06002017bool BestPractices::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002018 uint32_t drawCount, uint32_t stride) const {
Camden5b184be2019-08-13 07:50:19 -06002019 bool skip = false;
2020
2021 if (drawCount == 0) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002022 skip |= LogWarning(device, kVUID_BestPractices_CmdDraw_DrawCountZero,
2023 "Warning: You are calling vkCmdDrawIndexedIndirect() with a drawCount of Zero.");
Mark Lobodzinski4c4cf942019-12-20 11:09:51 -07002024 skip |= ValidateCmdDrawType(commandBuffer, "vkCmdDrawIndexedIndirect()");
Camden5b184be2019-08-13 07:50:19 -06002025 }
2026
2027 return skip;
2028}
2029
Sam Walls0961ec02020-03-31 16:39:15 +01002030void BestPractices::PostCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2031 uint32_t count, uint32_t stride) {
2032 StateTracker::PostCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, count, stride);
2033 RecordCmdDrawType(commandBuffer, count, "vkCmdDrawIndexedIndirect()");
2034}
2035
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002036void BestPractices::ValidateBoundDescriptorSets(VkCommandBuffer commandBuffer, const char* function_name) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002037 CMD_BUFFER_STATE* cb_state = GetCBState(commandBuffer);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002038
2039 if (cb_state) {
2040 for (auto descriptor_set : cb_state->validated_descriptor_sets) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002041 const auto& layout = *descriptor_set->GetLayout();
Hans-Kristian Arntzena8199012021-03-22 12:10:07 +01002042
2043 for (uint32_t index = 0; index < descriptor_set->GetBindingCount(); ++index) {
2044 // For bindless scenarios, we should not attempt to track descriptor set state.
2045 // It is highly uncertain which resources are actually bound.
2046 // Resources which are written to such a descriptor should be marked as indeterminate w.r.t. state.
2047 VkDescriptorBindingFlags flags = layout.GetDescriptorBindingFlagsFromIndex(index);
2048 if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
2049 VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
2050 VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT)) {
2051 continue;
2052 }
2053
2054 auto index_range = layout.GetGlobalIndexRangeFromIndex(index);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002055 for (uint32_t i = index_range.start; i < index_range.end; ++i) {
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002056 VkImageView image_view{VK_NULL_HANDLE};
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002057
2058 auto descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2059 switch (descriptor->GetClass()) {
2060 case cvdescriptorset::DescriptorClass::Image: {
2061 if (const auto image_descriptor = static_cast<const cvdescriptorset::ImageDescriptor*>(descriptor)) {
2062 image_view = image_descriptor->GetImageView();
2063 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002064 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002065 }
2066 case cvdescriptorset::DescriptorClass::ImageSampler: {
2067 if (const auto image_sampler_descriptor =
2068 static_cast<const cvdescriptorset::ImageSamplerDescriptor*>(descriptor)) {
2069 image_view = image_sampler_descriptor->GetImageView();
2070 }
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002071 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002072 }
ZandroFargnoliacf12f02020-06-18 16:50:00 +01002073 default:
Hans-Kristian Arntzenbc3a6152021-03-22 13:05:43 +01002074 break;
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002075 }
2076
2077 if (image_view) {
2078 IMAGE_VIEW_STATE* image_view_state = GetImageViewState(image_view);
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002079 QueueValidateImageView(cb_state->queue_submit_functions, function_name,
2080 image_view_state, IMAGE_SUBRESOURCE_USAGE_BP::DESCRIPTOR_ACCESS);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002081 }
2082 }
2083 }
2084 }
2085 }
2086}
2087
2088void BestPractices::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
2089 uint32_t firstVertex, uint32_t firstInstance) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002090 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDraw()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002091}
2092
2093void BestPractices::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2094 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002095 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002096}
2097
2098void BestPractices::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
2099 uint32_t drawCount, uint32_t stride) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002100 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDrawIndexedIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002101}
2102
Camden5b184be2019-08-13 07:50:19 -06002103bool BestPractices::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002104 uint32_t groupCountZ) const {
Camden5b184be2019-08-13 07:50:19 -06002105 bool skip = false;
2106
2107 if ((groupCountX == 0) || (groupCountY == 0) || (groupCountZ == 0)) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002108 skip |= LogWarning(device, kVUID_BestPractices_CmdDispatch_GroupCountZero,
2109 "Warning: You are calling vkCmdDispatch() while one or more groupCounts are zero (groupCountX = %" PRIu32
2110 ", groupCountY = %" PRIu32 ", groupCountZ = %" PRIu32 ").",
2111 groupCountX, groupCountY, groupCountZ);
Camden5b184be2019-08-13 07:50:19 -06002112 }
2113
2114 return skip;
2115}
Camden83a9c372019-08-14 11:41:38 -06002116
Sam Walls0961ec02020-03-31 16:39:15 +01002117bool BestPractices::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
2118 bool skip = false;
2119
2120 skip |= StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
2121
2122 auto prepass_state = cbDepthPrePassStates.find(commandBuffer);
2123
2124 if (prepass_state == cbDepthPrePassStates.end()) return skip;
2125
2126 bool uses_depth = (prepass_state->second.depthAttachment || prepass_state->second.colorAttachment) &&
2127 prepass_state->second.numDrawCallsDepthEqualCompare >= kDepthPrePassNumDrawCallsArm &&
2128 prepass_state->second.numDrawCallsDepthOnly >= kDepthPrePassNumDrawCallsArm;
2129 if (uses_depth) {
2130 skip |= LogPerformanceWarning(
2131 device, kVUID_BestPractices_EndRenderPass_DepthPrePassUsage,
2132 "%s Depth pre-passes may be in use. In general, this is not recommended, as in Arm Mali GPUs since "
2133 "Mali-T620, Forward Pixel Killing (FPK) can already perform automatic hidden surface removal; in which "
2134 "case, using depth pre-passes for hidden surface removal may worsen performance.",
2135 VendorSpecificTag(kBPVendorArm));
2136 }
2137
2138 return skip;
2139}
2140
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002141void BestPractices::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002142 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatch()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002143}
2144
2145void BestPractices::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002146 ValidateBoundDescriptorSets(commandBuffer, "vkCmdDispatchIndirect()");
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002147}
2148
Camden Stocker9c051442019-11-06 14:28:43 -08002149bool BestPractices::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice,
2150 const char* api_name) const {
2151 bool skip = false;
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002152 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Camden Stocker9c051442019-11-06 14:28:43 -08002153
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002154 if (bp_pd_state) {
2155 if (bp_pd_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) {
2156 skip |= LogWarning(physicalDevice, kVUID_BestPractices_DisplayPlane_PropertiesNotCalled,
2157 "Potential problem with calling %s() without first retrieving properties from "
2158 "vkGetPhysicalDeviceDisplayPlanePropertiesKHR or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.",
2159 api_name);
2160 }
Camden Stocker9c051442019-11-06 14:28:43 -08002161 }
2162
2163 return skip;
2164}
2165
Camden83a9c372019-08-14 11:41:38 -06002166bool BestPractices::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002167 uint32_t* pDisplayCount, VkDisplayKHR* pDisplays) const {
Camden83a9c372019-08-14 11:41:38 -06002168 bool skip = false;
2169
Camden Stocker9c051442019-11-06 14:28:43 -08002170 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneSupportedDisplaysKHR");
Camden83a9c372019-08-14 11:41:38 -06002171
Camden Stocker9c051442019-11-06 14:28:43 -08002172 return skip;
2173}
2174
2175bool BestPractices::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode,
2176 uint32_t planeIndex,
2177 VkDisplayPlaneCapabilitiesKHR* pCapabilities) const {
2178 bool skip = false;
2179
2180 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilitiesKHR");
2181
2182 return skip;
2183}
2184
2185bool BestPractices::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice,
2186 const VkDisplayPlaneInfo2KHR* pDisplayPlaneInfo,
2187 VkDisplayPlaneCapabilities2KHR* pCapabilities) const {
2188 bool skip = false;
2189
2190 skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, "vkGetDisplayPlaneCapabilities2KHR");
Camden83a9c372019-08-14 11:41:38 -06002191
2192 return skip;
2193}
Camden05de2d42019-08-19 10:23:56 -06002194
2195bool BestPractices::PreCallValidateGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002196 VkImage* pSwapchainImages) const {
Camden05de2d42019-08-19 10:23:56 -06002197 bool skip = false;
2198
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002199 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
Camden05de2d42019-08-19 10:23:56 -06002200
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002201 if ((swapchain_state_itr != swapchain_bp_state_map.cend()) && pSwapchainImages) {
Camden05de2d42019-08-19 10:23:56 -06002202 // Compare the preliminary value of *pSwapchainImageCount with the value this time:
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002203 if (swapchain_state_itr->second.vkGetSwapchainImagesKHRState == UNCALLED) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002204 skip |=
2205 LogWarning(device, kVUID_Core_Swapchain_PriorCount,
2206 "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has "
2207 "been seen for pSwapchainImages.");
Camden05de2d42019-08-19 10:23:56 -06002208 }
2209 }
2210
2211 return skip;
2212}
2213
2214// Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002215bool BestPractices::ValidateCommonGetPhysicalDeviceQueueFamilyProperties(const PHYSICAL_DEVICE_STATE* pd_state,
2216 uint32_t requested_queue_family_property_count,
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002217 const CALL_STATE call_state,
2218 const char* caller_name) const {
Camden05de2d42019-08-19 10:23:56 -06002219 bool skip = false;
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002220 // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count
2221 if (UNCALLED == call_state) {
2222 skip |= LogWarning(
2223 pd_state->phys_device, kVUID_Core_DevLimit_MissingQueryCount,
2224 "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is "
2225 "recommended "
2226 "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.",
2227 caller_name, caller_name);
2228 // Then verify that pCount that is passed in on second call matches what was returned
2229 } else if (pd_state->queue_family_known_count != requested_queue_family_property_count) {
2230 skip |= LogWarning(pd_state->phys_device, kVUID_Core_DevLimit_CountMismatch,
2231 "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32
2232 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32
2233 ". It is recommended to instead receive all the properties by calling %s with "
2234 "pQueueFamilyPropertyCount that was "
2235 "previously obtained by calling %s with NULL pQueueFamilyProperties.",
2236 caller_name, requested_queue_family_property_count, pd_state->queue_family_known_count, caller_name,
2237 caller_name);
Camden05de2d42019-08-19 10:23:56 -06002238 }
2239
2240 return skip;
2241}
2242
Jeff Bolz5c801d12019-10-09 10:38:45 -05002243bool BestPractices::PreCallValidateBindAccelerationStructureMemoryNV(
2244 VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) const {
Camden Stocker82510582019-09-03 14:00:16 -06002245 bool skip = false;
2246
2247 for (uint32_t i = 0; i < bindInfoCount; i++) {
sourav parmarcd5fb182020-07-17 12:58:44 -07002248 const ACCELERATION_STRUCTURE_STATE* as_state = GetAccelerationStructureStateNV(pBindInfos[i].accelerationStructure);
Camden Stocker82510582019-09-03 14:00:16 -06002249 if (!as_state->memory_requirements_checked) {
2250 // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling
2251 // BindAccelerationStructureMemoryNV but it's implied in that memory being bound must conform with
2252 // VkAccelerationStructureMemoryRequirementsInfoNV from vkGetAccelerationStructureMemoryRequirementsNV
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002253 skip |= LogWarning(
2254 device, kVUID_BestPractices_BindAccelNV_NoMemReqQuery,
Camden Stocker82510582019-09-03 14:00:16 -06002255 "vkBindAccelerationStructureMemoryNV(): "
2256 "Binding memory to %s but vkGetAccelerationStructureMemoryRequirementsNV() has not been called on that structure.",
2257 report_data->FormatHandle(pBindInfos[i].accelerationStructure).c_str());
2258 }
2259 }
2260
2261 return skip;
2262}
2263
Camden05de2d42019-08-19 10:23:56 -06002264bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2265 uint32_t* pQueueFamilyPropertyCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002266 VkQueueFamilyProperties* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002267 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2268 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002269 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2270 if (pQueueFamilyProperties && bp_pd_state) {
2271 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2272 bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2273 "vkGetPhysicalDeviceQueueFamilyProperties()");
2274 }
2275 return false;
Camden05de2d42019-08-19 10:23:56 -06002276}
2277
Mike Schuchardt2df08912020-12-15 16:28:09 -08002278bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2279 uint32_t* pQueueFamilyPropertyCount,
2280 VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002281 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2282 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002283 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2284 if (pQueueFamilyProperties && bp_pd_state) {
2285 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2286 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2287 "vkGetPhysicalDeviceQueueFamilyProperties2()");
2288 }
2289 return false;
Camden05de2d42019-08-19 10:23:56 -06002290}
2291
Jeff Bolz5c801d12019-10-09 10:38:45 -05002292bool BestPractices::PreCallValidateGetPhysicalDeviceQueueFamilyProperties2KHR(
Mike Schuchardt2df08912020-12-15 16:28:09 -08002293 VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties) const {
Camden05de2d42019-08-19 10:23:56 -06002294 auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
2295 assert(physical_device_state);
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002296 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physical_device_state->phys_device);
2297 if (pQueueFamilyProperties && bp_pd_state) {
2298 return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(physical_device_state, *pQueueFamilyPropertyCount,
2299 bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2300 "vkGetPhysicalDeviceQueueFamilyProperties2KHR()");
2301 }
2302 return false;
Camden05de2d42019-08-19 10:23:56 -06002303}
2304
2305bool BestPractices::PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2306 uint32_t* pSurfaceFormatCount,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002307 VkSurfaceFormatKHR* pSurfaceFormats) const {
Camden05de2d42019-08-19 10:23:56 -06002308 if (!pSurfaceFormats) return false;
2309 const auto physical_device_state = GetPhysicalDeviceState(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002310 const auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2311 const auto& call_state = bp_pd_state->vkGetPhysicalDeviceSurfaceFormatsKHRState;
Camden05de2d42019-08-19 10:23:56 -06002312 bool skip = false;
2313 if (call_state == UNCALLED) {
2314 // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application didn't
2315 // previously call this function with a NULL value of pSurfaceFormats:
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002316 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_MustQueryCount,
2317 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior "
2318 "positive value has been seen for pSurfaceFormats.");
Camden05de2d42019-08-19 10:23:56 -06002319 } else {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002320 auto prev_format_count = static_cast<uint32_t>(physical_device_state->surface_formats.size());
Peter Chene191bd72019-09-16 13:04:37 -04002321 if (*pSurfaceFormatCount > prev_format_count) {
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002322 skip |= LogWarning(physicalDevice, kVUID_Core_DevLimit_CountMismatch,
2323 "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with "
2324 "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned "
2325 "when pSurfaceFormatCount was NULL.",
2326 *pSurfaceFormatCount, prev_format_count);
Camden05de2d42019-08-19 10:23:56 -06002327 }
2328 }
2329 return skip;
2330}
Camden Stocker23cc47d2019-09-03 14:53:57 -06002331
2332bool BestPractices::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
Jeff Bolz5c801d12019-10-09 10:38:45 -05002333 VkFence fence) const {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002334 bool skip = false;
2335
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002336 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2337 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002338 // 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 -07002339 layer_data::unordered_set<const IMAGE_STATE*> sparse_images;
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002340 // Track images getting metadata bound by this call in a set, it'll be recorded into the image_state
2341 // in RecordQueueBindSparse.
Jeremy Gebbencbf22862021-03-03 12:01:22 -07002342 layer_data::unordered_set<const IMAGE_STATE*> sparse_images_with_metadata;
Camden Stocker23cc47d2019-09-03 14:53:57 -06002343 // 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 -07002344 for (uint32_t i = 0; i < bind_info.imageBindCount; ++i) {
2345 const auto& image_bind = bind_info.pImageBinds[i];
Camden Stocker23cc47d2019-09-03 14:53:57 -06002346 auto image_state = GetImageState(image_bind.image);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002347 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002348 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002349 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002350 sparse_images.insert(image_state);
2351 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2352 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2353 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002354 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002355 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2356 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002357 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002358 }
2359 }
2360 if (!image_state->memory_requirements_checked) {
2361 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002362 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002363 "vkQueueBindSparse(): Binding sparse memory to %s without first calling "
2364 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002365 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002366 }
2367 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002368 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2369 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2370 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2371 if (!image_state) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002372 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002373 }
Camden Stocker23cc47d2019-09-03 14:53:57 -06002374 sparse_images.insert(image_state);
2375 if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) {
2376 if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) {
2377 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002378 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002379 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2380 "vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002381 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002382 }
2383 }
2384 if (!image_state->memory_requirements_checked) {
2385 // For now just warning if sparse image binding occurs without calling to get reqs first
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002386 skip |= LogWarning(image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002387 "vkQueueBindSparse(): Binding opaque sparse memory to %s without first calling "
2388 "vkGetImageMemoryRequirements() to retrieve requirements.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002389 report_data->FormatHandle(image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002390 }
2391 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2392 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002393 sparse_images_with_metadata.insert(image_state);
Camden Stocker23cc47d2019-09-03 14:53:57 -06002394 }
2395 }
2396 }
2397 for (const auto& sparse_image_state : sparse_images) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002398 if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound &&
2399 sparse_images_with_metadata.find(sparse_image_state) == sparse_images_with_metadata.end()) {
Camden Stocker23cc47d2019-09-03 14:53:57 -06002400 // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002401 skip |= LogWarning(sparse_image_state->image(), kVUID_Core_MemTrack_InvalidState,
Mark Lobodzinskib6e2a282020-01-29 16:03:26 -07002402 "vkQueueBindSparse(): Binding sparse memory to %s which requires a metadata aspect but no "
2403 "binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.",
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002404 report_data->FormatHandle(sparse_image_state->image()).c_str());
Camden Stocker23cc47d2019-09-03 14:53:57 -06002405 }
2406 }
2407 }
2408
2409 return skip;
2410}
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002411
Mark Lobodzinski84101d72020-04-24 09:43:48 -06002412void BestPractices::ManualPostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo,
2413 VkFence fence, VkResult result) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002414 if (result != VK_SUCCESS) {
Mark Lobodzinski205b7a02020-02-21 13:23:17 -07002415 return;
2416 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002417
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002418 for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; bind_idx++) {
2419 const VkBindSparseInfo& bind_info = pBindInfo[bind_idx];
2420 for (uint32_t i = 0; i < bind_info.imageOpaqueBindCount; ++i) {
2421 const auto& image_opaque_bind = bind_info.pImageOpaqueBinds[i];
2422 auto image_state = GetImageState(bind_info.pImageOpaqueBinds[i].image);
2423 if (!image_state) {
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002424 continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here.
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002425 }
Jeff Bolz46c0ea02019-10-09 13:06:29 -05002426 for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) {
2427 if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) {
2428 image_state->sparse_metadata_bound = true;
2429 }
2430 }
2431 }
2432 }
2433}
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002434
2435bool BestPractices::PreCallValidateCmdClearAttachments(VkCommandBuffer commandBuffer, uint32_t attachmentCount,
Camden Stockerf55721f2019-09-09 11:04:49 -06002436 const VkClearAttachment* pAttachments, uint32_t rectCount,
2437 const VkClearRect* pRects) const {
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002438 bool skip = false;
2439 const CMD_BUFFER_STATE* cb_node = GetCBState(commandBuffer);
2440 if (!cb_node) return skip;
2441
Camden Stockerf55721f2019-09-09 11:04:49 -06002442 // Warn if this is issued prior to Draw Cmd and clearing the entire attachment
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002443 if (!cb_node->hasDrawCmd && (cb_node->activeRenderPassBeginInfo.renderArea.extent.width == pRects[0].rect.extent.width) &&
2444 (cb_node->activeRenderPassBeginInfo.renderArea.extent.height == pRects[0].rect.extent.height)) {
2445 // There are times where app needs to use ClearAttachments (generally when reusing a buffer inside of a render pass)
2446 // This warning should be made more specific. It'd be best to avoid triggering this test if it's a use that must call
2447 // CmdClearAttachments.
Mark Lobodzinskif95a2662020-01-29 15:43:32 -07002448 skip |= LogPerformanceWarning(commandBuffer, kVUID_BestPractices_DrawState_ClearCmdBeforeDraw,
2449 "vkCmdClearAttachments() issued on %s prior to any Draw Cmds. It is recommended you "
2450 "use RenderPass LOAD_OP_CLEAR on Attachments prior to any Draw.",
2451 report_data->FormatHandle(commandBuffer).c_str());
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002452 }
2453
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002454 // Check for uses of ClearAttachments along with LOAD_OP_LOAD,
2455 // as it can be more efficient to just use LOAD_OP_CLEAR
locke-lunargaecf2152020-05-12 17:15:41 -06002456 const RENDER_PASS_STATE* rp = cb_node->activeRenderPass.get();
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002457 if (rp) {
2458 const auto& subpass = rp->createInfo.pSubpasses[cb_node->activeSubpass];
2459
2460 for (uint32_t i = 0; i < attachmentCount; i++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02002461 const auto& attachment = pAttachments[i];
Attilio Provenzano1d9a8362020-02-27 12:23:51 +00002462 if (attachment.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
2463 uint32_t color_attachment = attachment.colorAttachment;
2464 uint32_t fb_attachment = subpass.pColorAttachments[color_attachment].attachment;
2465
2466 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2467 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2468 skip |= LogPerformanceWarning(
2469 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2470 "vkCmdClearAttachments() issued on %s for color attachment #%u in this subpass, "
2471 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2472 "it is more efficient.",
2473 report_data->FormatHandle(commandBuffer).c_str(), color_attachment);
2474 }
2475 }
2476 }
2477
2478 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2479 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2480
2481 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2482 if (rp->createInfo.pAttachments[fb_attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2483 skip |= LogPerformanceWarning(
2484 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2485 "vkCmdClearAttachments() issued on %s for the depth attachment in this subpass, "
2486 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2487 "it is more efficient.",
2488 report_data->FormatHandle(commandBuffer).c_str());
2489 }
2490 }
2491 }
2492
2493 if (subpass.pDepthStencilAttachment && attachment.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2494 uint32_t fb_attachment = subpass.pDepthStencilAttachment->attachment;
2495
2496 if (fb_attachment != VK_ATTACHMENT_UNUSED) {
2497 if (rp->createInfo.pAttachments[fb_attachment].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) {
2498 skip |= LogPerformanceWarning(
2499 device, kVUID_BestPractices_ClearAttachments_ClearAfterLoad,
2500 "vkCmdClearAttachments() issued on %s for the stencil attachment in this subpass, "
2501 "but LOAD_OP_LOAD was used. If you need to clear the framebuffer, always use LOAD_OP_CLEAR as "
2502 "it is more efficient.",
2503 report_data->FormatHandle(commandBuffer).c_str());
2504 }
2505 }
2506 }
2507 }
2508 }
2509
Camden Stockerf55721f2019-09-09 11:04:49 -06002510 return skip;
Camden Stocker0e0f89b2019-10-16 12:24:31 -07002511}
Attilio Provenzano02859b22020-02-27 14:17:28 +00002512
2513bool BestPractices::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2514 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2515 const VkImageResolve* pRegions) const {
2516 bool skip = false;
2517
2518 skip |= VendorCheckEnabled(kBPVendorArm) &&
2519 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage_ResolvingImage,
2520 "%s Attempting to use vkCmdResolveImage to resolve a multisampled image. "
2521 "This is a very slow and extremely bandwidth intensive path. "
2522 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2523 VendorSpecificTag(kBPVendorArm));
2524
2525 return skip;
2526}
2527
Jeff Leger178b1e52020-10-05 12:22:23 -04002528bool BestPractices::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2529 const VkResolveImageInfo2KHR* pResolveImageInfo) const {
2530 bool skip = false;
2531
2532 skip |= VendorCheckEnabled(kBPVendorArm) &&
2533 LogPerformanceWarning(device, kVUID_BestPractices_CmdResolveImage2KHR_ResolvingImage,
2534 "%s Attempting to use vkCmdResolveImage2KHR to resolve a multisampled image. "
2535 "This is a very slow and extremely bandwidth intensive path. "
2536 "You should always resolve multisampled images on-tile with pResolveAttachments in VkRenderPass.",
2537 VendorSpecificTag(kBPVendorArm));
2538
2539 return skip;
2540}
2541
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002542void BestPractices::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2543 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2544 const VkImageResolve* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002545 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002546 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002547 auto* src = GetImageUsageState(srcImage);
2548 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002549
2550 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002551 QueueValidateImage(funcs, "vkCmdResolveImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pRegions[i].srcSubresource);
2552 QueueValidateImage(funcs, "vkCmdResolveImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002553 }
2554}
2555
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002556void BestPractices::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
2557 const VkResolveImageInfo2KHR* pResolveImageInfo) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002558 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002559 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002560 auto* src = GetImageUsageState(pResolveImageInfo->srcImage);
2561 auto* dst = GetImageUsageState(pResolveImageInfo->dstImage);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002562 uint32_t regionCount = pResolveImageInfo->regionCount;
2563
2564 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002565 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", src, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_READ, pResolveImageInfo->pRegions[i].srcSubresource);
2566 QueueValidateImage(funcs, "vkCmdResolveImage2KHR()", dst, IMAGE_SUBRESOURCE_USAGE_BP::RESOLVE_WRITE, pResolveImageInfo->pRegions[i].dstSubresource);
Hans-Kristian Arntzen9e030f12021-03-17 13:09:30 +01002567 }
2568}
2569
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002570void BestPractices::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2571 const VkClearColorValue* pColor, uint32_t rangeCount,
2572 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002573 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002574 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002575 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002576
2577 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002578 QueueValidateImage(funcs, "vkCmdClearColorImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002579 }
2580}
2581
2582void BestPractices::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
2583 const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount,
2584 const VkImageSubresourceRange* pRanges) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002585 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002586 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002587 auto* dst = GetImageUsageState(image);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002588
2589 for (uint32_t i = 0; i < rangeCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002590 QueueValidateImage(funcs, "vkCmdClearDepthStencilImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::CLEARED, pRanges[i]);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002591 }
2592}
2593
2594void BestPractices::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2595 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2596 const VkImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002597 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002598 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002599 auto* src = GetImageUsageState(srcImage);
2600 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002601
2602 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002603 QueueValidateImage(funcs, "vkCmdCopyImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].srcSubresource);
2604 QueueValidateImage(funcs, "vkCmdCopyImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002605 }
2606}
2607
2608void BestPractices::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
2609 VkImageLayout dstImageLayout, uint32_t regionCount,
2610 const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002611 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002612 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002613 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002614
2615 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002616 QueueValidateImage(funcs, "vkCmdCopyBufferToImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::COPY_WRITE, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002617 }
2618}
2619
2620void BestPractices::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2621 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002622 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002623 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002624 auto* src = GetImageUsageState(srcImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002625
2626 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002627 QueueValidateImage(funcs, "vkCmdCopyImageToBuffer()", src, IMAGE_SUBRESOURCE_USAGE_BP::COPY_READ, pRegions[i].imageSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002628 }
2629}
2630
2631void BestPractices::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
2632 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
2633 const VkImageBlit* pRegions, VkFilter filter) {
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01002634 CMD_BUFFER_STATE* cb = GetCBState(commandBuffer);
Hans-Kristian Arntzendd8acbb2021-03-22 13:41:47 +01002635 auto &funcs = cb->queue_submit_functions;
Hans-Kristian Arntzen5b466db2021-03-18 13:59:46 +01002636 auto* src = GetImageUsageState(srcImage);
2637 auto* dst = GetImageUsageState(dstImage);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002638
2639 for (uint32_t i = 0; i < regionCount; i++) {
Hans-Kristian Arntzenc8b831c2021-04-28 15:29:49 +02002640 QueueValidateImage(funcs, "vkCmdBlitImage()", src, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_READ, pRegions[i].srcSubresource);
2641 QueueValidateImage(funcs, "vkCmdBlitImage()", dst, IMAGE_SUBRESOURCE_USAGE_BP::BLIT_WRITE, pRegions[i].dstSubresource);
ZandroFargnoli1ced2b62020-06-18 16:49:34 +01002642 }
2643}
2644
Attilio Provenzano02859b22020-02-27 14:17:28 +00002645bool BestPractices::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo* pCreateInfo,
2646 const VkAllocationCallbacks* pAllocator, VkSampler* pSampler) const {
2647 bool skip = false;
2648
2649 if (VendorCheckEnabled(kBPVendorArm)) {
2650 if ((pCreateInfo->addressModeU != pCreateInfo->addressModeV) || (pCreateInfo->addressModeV != pCreateInfo->addressModeW)) {
2651 skip |= LogPerformanceWarning(
2652 device, kVUID_BestPractices_CreateSampler_DifferentWrappingModes,
2653 "%s Creating a sampler object with wrapping modes which do not match (U = %u, V = %u, W = %u). "
2654 "This may cause reduced performance even if only U (1D image) or U/V wrapping modes (2D "
2655 "image) are actually used. If you need different wrapping modes, disregard this warning.",
Jeremy Gebbenda6b48f2021-05-13 10:46:18 -06002656 VendorSpecificTag(kBPVendorArm), pCreateInfo->addressModeU, pCreateInfo->addressModeV, pCreateInfo->addressModeW);
Attilio Provenzano02859b22020-02-27 14:17:28 +00002657 }
2658
2659 if ((pCreateInfo->minLod != 0.0f) || (pCreateInfo->maxLod < VK_LOD_CLAMP_NONE)) {
2660 skip |= LogPerformanceWarning(
2661 device, kVUID_BestPractices_CreateSampler_LodClamping,
2662 "%s Creating a sampler object with LOD clamping (minLod = %f, maxLod = %f). This may cause reduced performance. "
2663 "Instead of clamping LOD in the sampler, consider using an VkImageView which restricts the mip-levels, set minLod "
2664 "to 0.0, and maxLod to VK_LOD_CLAMP_NONE.",
2665 VendorSpecificTag(kBPVendorArm), pCreateInfo->minLod, pCreateInfo->maxLod);
2666 }
2667
2668 if (pCreateInfo->mipLodBias != 0.0f) {
2669 skip |=
2670 LogPerformanceWarning(device, kVUID_BestPractices_CreateSampler_LodBias,
2671 "%s Creating a sampler object with LOD bias != 0.0 (%f). This will lead to less efficient "
2672 "descriptors being created and may cause reduced performance.",
2673 VendorSpecificTag(kBPVendorArm), pCreateInfo->mipLodBias);
2674 }
2675
2676 if ((pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2677 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
2678 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER) &&
2679 (pCreateInfo->borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK)) {
2680 skip |= LogPerformanceWarning(
2681 device, kVUID_BestPractices_CreateSampler_BorderClampColor,
2682 "%s Creating a sampler object with border clamping and borderColor != VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK. "
2683 "This will lead to less efficient descriptors being created and may cause reduced performance. "
2684 "If possible, use VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK as the border color.",
2685 VendorSpecificTag(kBPVendorArm));
2686 }
2687
2688 if (pCreateInfo->unnormalizedCoordinates) {
2689 skip |= LogPerformanceWarning(
2690 device, kVUID_BestPractices_CreateSampler_UnnormalizedCoordinates,
2691 "%s Creating a sampler object with unnormalized coordinates. This will lead to less efficient "
2692 "descriptors being created and may cause reduced performance.",
2693 VendorSpecificTag(kBPVendorArm));
2694 }
2695
2696 if (pCreateInfo->anisotropyEnable) {
2697 skip |= LogPerformanceWarning(
2698 device, kVUID_BestPractices_CreateSampler_Anisotropy,
2699 "%s Creating a sampler object with anisotropy. This will lead to less efficient descriptors being created "
2700 "and may cause reduced performance.",
2701 VendorSpecificTag(kBPVendorArm));
2702 }
2703 }
2704
2705 return skip;
2706}
Sam Walls8e77e4f2020-03-16 20:47:40 +00002707
2708void BestPractices::PostTransformLRUCacheModel::resize(size_t size) { _entries.resize(size); }
2709
2710bool BestPractices::PostTransformLRUCacheModel::query_cache(uint32_t value) {
2711 // look for a cache hit
2712 auto hit = std::find_if(_entries.begin(), _entries.end(), [value](const CacheEntry& entry) { return entry.value == value; });
2713 if (hit != _entries.end()) {
2714 // mark the cache hit as being most recently used
2715 hit->age = iteration++;
2716 return true;
2717 }
2718
2719 // if there's no cache hit, we need to model the entry being inserted into the cache
2720 CacheEntry new_entry = {value, iteration};
2721 if (iteration < static_cast<uint32_t>(std::distance(_entries.begin(), _entries.end()))) {
2722 // if there is still space left in the cache, use the next available slot
2723 *(_entries.begin() + iteration) = new_entry;
2724 } else {
2725 // otherwise replace the least recently used cache entry
2726 auto lru = std::min_element(_entries.begin(), hit, [](const CacheEntry& a, const CacheEntry& b) { return a.age < b.age; });
2727 *lru = new_entry;
2728 }
2729 iteration++;
2730 return false;
2731}
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002732
2733bool BestPractices::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout,
2734 VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex) const {
2735 const auto swapchain_data = GetSwapchainState(swapchain);
2736 bool skip = false;
2737 if (swapchain_data && swapchain_data->images.size() == 0) {
2738 skip |= LogWarning(swapchain, kVUID_Core_DrawState_SwapchainImagesNotFound,
2739 "vkAcquireNextImageKHR: No images found to acquire from. Application probably did not call "
2740 "vkGetSwapchainImagesKHR after swapchain creation.");
2741 }
2742 return skip;
2743}
2744
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002745void BestPractices::CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(CALL_STATE& call_state, bool no_pointer) {
2746 if (no_pointer) {
2747 if (UNCALLED == call_state) {
2748 call_state = QUERY_COUNT;
2749 }
2750 } else { // Save queue family properties
2751 call_state = QUERY_DETAILS;
2752 }
2753}
2754
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002755void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,
2756 uint32_t* pQueueFamilyPropertyCount,
2757 VkQueueFamilyProperties* pQueueFamilyProperties) {
2758 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties(physicalDevice, pQueueFamilyPropertyCount,
2759 pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002760 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002761 if (bp_pd_state) {
Nathaniel Cesario56a96652020-12-30 13:23:42 -07002762 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState,
2763 nullptr == pQueueFamilyProperties);
2764 }
2765}
2766
2767void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,
2768 uint32_t* pQueueFamilyPropertyCount,
2769 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2770 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(physicalDevice, pQueueFamilyPropertyCount,
2771 pQueueFamilyProperties);
2772 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2773 if (bp_pd_state) {
2774 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2State,
2775 nullptr == pQueueFamilyProperties);
2776 }
2777}
2778
2779void BestPractices::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(VkPhysicalDevice physicalDevice,
2780 uint32_t* pQueueFamilyPropertyCount,
2781 VkQueueFamilyProperties2* pQueueFamilyProperties) {
2782 ValidationStateTracker::PostCallRecordGetPhysicalDeviceQueueFamilyProperties2KHR(physicalDevice, pQueueFamilyPropertyCount,
2783 pQueueFamilyProperties);
2784 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2785 if (bp_pd_state) {
2786 CommonPostCallRecordGetPhysicalDeviceQueueFamilyProperties(bp_pd_state->vkGetPhysicalDeviceQueueFamilyProperties2KHRState,
2787 nullptr == pQueueFamilyProperties);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002788 }
2789}
2790
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002791void BestPractices::PostCallRecordGetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures) {
2792 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002793 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2794 if (bp_pd_state) {
2795 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2796 }
2797}
2798
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002799void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,
2800 VkPhysicalDeviceFeatures2* pFeatures) {
2801 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002802 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2803 if (bp_pd_state) {
2804 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2805 }
2806}
2807
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002808void BestPractices::PostCallRecordGetPhysicalDeviceFeatures2KHR(VkPhysicalDevice physicalDevice,
2809 VkPhysicalDeviceFeatures2* pFeatures) {
2810 ValidationStateTracker::PostCallRecordGetPhysicalDeviceFeatures2KHR(physicalDevice, pFeatures);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002811 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2812 if (bp_pd_state) {
2813 bp_pd_state->vkGetPhysicalDeviceFeaturesState = QUERY_DETAILS;
2814 }
2815}
2816
2817void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(VkPhysicalDevice physicalDevice,
2818 VkSurfaceKHR surface,
2819 VkSurfaceCapabilitiesKHR* pSurfaceCapabilities,
2820 VkResult result) {
2821 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2822 if (bp_pd_state) {
2823 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2824 }
2825}
2826
2827void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(
2828 VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2829 VkSurfaceCapabilities2KHR* pSurfaceCapabilities, VkResult result) {
2830 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2831 if (bp_pd_state) {
2832 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2833 }
2834}
2835
2836void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(VkPhysicalDevice physicalDevice,
2837 VkSurfaceKHR surface,
2838 VkSurfaceCapabilities2EXT* pSurfaceCapabilities,
2839 VkResult result) {
2840 auto* bp_pd_state = GetPhysicalDeviceStateBP(physicalDevice);
2841 if (bp_pd_state) {
2842 bp_pd_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS;
2843 }
2844}
2845
2846void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice physicalDevice,
2847 VkSurfaceKHR surface, uint32_t* pPresentModeCount,
2848 VkPresentModeKHR* pPresentModes, VkResult result) {
2849 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2850 if (bp_pd_data) {
2851 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfacePresentModesKHRState;
2852
2853 if (*pPresentModeCount) {
2854 if (call_state < QUERY_COUNT) {
2855 call_state = QUERY_COUNT;
2856 }
2857 }
2858 if (pPresentModes) {
2859 if (call_state < QUERY_DETAILS) {
2860 call_state = QUERY_DETAILS;
2861 }
2862 }
2863 }
2864}
2865
2866void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface,
2867 uint32_t* pSurfaceFormatCount,
2868 VkSurfaceFormatKHR* pSurfaceFormats, VkResult result) {
2869 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2870 if (bp_pd_data) {
2871 auto& call_state = bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState;
2872
2873 if (*pSurfaceFormatCount) {
2874 if (call_state < QUERY_COUNT) {
2875 call_state = QUERY_COUNT;
2876 }
2877 }
2878 if (pSurfaceFormats) {
2879 if (call_state < QUERY_DETAILS) {
2880 call_state = QUERY_DETAILS;
2881 }
2882 }
2883 }
2884}
2885
2886void BestPractices::ManualPostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice,
2887 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
2888 uint32_t* pSurfaceFormatCount,
2889 VkSurfaceFormat2KHR* pSurfaceFormats, VkResult result) {
2890 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2891 if (bp_pd_data) {
2892 if (*pSurfaceFormatCount) {
2893 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) {
2894 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT;
2895 }
2896 }
2897 if (pSurfaceFormats) {
2898 if (bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) {
2899 bp_pd_data->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS;
2900 }
2901 }
2902 }
2903}
2904
2905void BestPractices::ManualPostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(VkPhysicalDevice physicalDevice,
2906 uint32_t* pPropertyCount,
2907 VkDisplayPlanePropertiesKHR* pProperties,
2908 VkResult result) {
2909 auto* bp_pd_data = GetPhysicalDeviceStateBP(physicalDevice);
2910 if (bp_pd_data) {
2911 if (*pPropertyCount) {
2912 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) {
2913 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT;
2914 }
2915 }
2916 if (pProperties) {
2917 if (bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) {
2918 bp_pd_data->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS;
2919 }
2920 }
2921 }
2922}
2923
2924void BestPractices::ManualPostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo,
2925 const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain,
2926 VkResult result) {
2927 if (VK_SUCCESS == result) {
2928 swapchain_bp_state_map.emplace(*pSwapchain, SWAPCHAIN_STATE_BP{});
2929 }
2930}
2931
Nathaniel Cesariof121d122020-10-08 13:09:46 -06002932void BestPractices::PostCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
2933 const VkAllocationCallbacks* pAllocator) {
2934 ValidationStateTracker::PostCallRecordDestroySwapchainKHR(device, swapchain, pAllocator);
Nathaniel Cesario24184fe2020-10-06 12:46:12 -06002935 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2936 if (swapchain_state_itr != swapchain_bp_state_map.cend()) {
2937 swapchain_bp_state_map.erase(swapchain_state_itr);
2938 }
2939}
2940
2941void BestPractices::ManualPostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain,
2942 uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages,
2943 VkResult result) {
2944 auto swapchain_state_itr = swapchain_bp_state_map.find(swapchain);
2945 assert(swapchain_state_itr != swapchain_bp_state_map.cend());
2946 auto& swapchain_state = swapchain_state_itr->second;
2947 if (pSwapchainImages || *pSwapchainImageCount) {
2948 if (swapchain_state.vkGetSwapchainImagesKHRState < QUERY_DETAILS) {
2949 swapchain_state.vkGetSwapchainImagesKHRState = QUERY_DETAILS;
2950 }
2951 }
2952}
2953
2954void BestPractices::ManualPostCallRecordEnumeratePhysicalDevices(VkInstance instance, uint32_t* pPhysicalDeviceCount,
2955 VkPhysicalDevice* pPhysicalDevices, VkResult result) {
2956 if ((nullptr != pPhysicalDevices) && ((result == VK_SUCCESS || result == VK_INCOMPLETE))) {
2957 for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) {
2958 phys_device_bp_state_map.emplace(pPhysicalDevices[i], PHYSICAL_DEVICE_STATE_BP{});
2959 }
2960 }
2961}
2962
2963void BestPractices::ManualPostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo*, const VkAllocationCallbacks*,
2964 VkDevice*, VkResult result) {
2965 if (VK_SUCCESS == result) {
2966 instance_device_bp_state = &phys_device_bp_state_map[gpu];
2967 }
2968}
2969
2970PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) {
2971 if (phys_device_bp_state_map.count(phys_device) > 0) {
2972 return &phys_device_bp_state_map.at(phys_device);
2973 } else {
2974 return nullptr;
2975 }
2976}
2977
2978const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP(const VkPhysicalDevice& phys_device) const {
2979 if (phys_device_bp_state_map.count(phys_device) > 0) {
2980 return &phys_device_bp_state_map.at(phys_device);
2981 } else {
2982 return nullptr;
2983 }
2984}
2985
2986PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() {
2987 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2988 if (bp_state) {
2989 return bp_state;
2990 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
2991 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
2992 } else {
2993 return nullptr;
2994 }
2995}
2996
2997const PHYSICAL_DEVICE_STATE_BP* BestPractices::GetPhysicalDeviceStateBP() const {
2998 auto bp_state = (reinterpret_cast<BestPractices*>(instance_state))->instance_device_bp_state;
2999 if (bp_state) {
3000 return bp_state;
3001 } else if (!bp_state && phys_device_bp_state_map.count(physical_device_state->phys_device) > 0) {
3002 return &phys_device_bp_state_map.at(physical_device_state->phys_device);
3003 } else {
3004 return nullptr;
3005 }
3006}
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003007
3008void BestPractices::PreCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) {
3009 ValidationStateTracker::PreCallRecordQueueSubmit(queue, submitCount, pSubmits, fence);
3010
3011 QUEUE_STATE* queue_state = GetQueueState(queue);
3012 for (uint32_t submit = 0; submit < submitCount; submit++) {
Hans-Kristian Arntzen69ace7d2021-04-28 14:17:19 +02003013 const auto& submit_info = pSubmits[submit];
Hans-Kristian Arntzen66f4b522021-03-22 11:35:58 +01003014 for (uint32_t cb_index = 0; cb_index < submit_info.commandBufferCount; cb_index++) {
3015 CMD_BUFFER_STATE* cb = GetCBState(submit_info.pCommandBuffers[cb_index]);
3016 for (auto &func : cb->queue_submit_functions) {
3017 func(this, queue_state);
3018 }
3019 }
3020 }
3021}
Hans-Kristian Arntzen7a5fdc52021-03-29 11:39:51 +02003022
3023void BestPractices::PreCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo* pBeginInfo) {
3024 ValidationStateTracker::PreCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo);
3025 // This should not be required, but guards against buggy applications which do not call EndRenderPass correctly.
3026 queue_submit_functions_after_render_pass.clear();
Hans-Kristian Arntzenb2147952021-04-28 14:32:00 +02003027}